# Question
Title: Using composer - basics with localhost Mamp
My goal is to try updating drupal/core with Composer and to learn composer basics. Composer is installed on OS X. From terminal i can run

```
My-MacBook-Pro:~ osxuser$ composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.4.1 2017-03-10 09:29:45

Usage:
command [options] [arguments]...

```

So how do I make composer find my drupal8 install in Mamp?

I have tried both:

```
composer -d, --working-dir=/Applications/MAMP/htdocs/test_d8

```

and

```
cd /Applications/MAMP/htdocs/test_d8

```

If I am running several drupal 8 installs in /Applications/MAMP/htdocs/ how do I tell composer witch one to work on?

From what I've red you don't need drush any more. I am not sure Composer has all it needs to work with Drupal 8 either.

```
composer show
symfony/css-selector      v3.2.6  Symfony CssSelector Component
symfony/dom-crawler       v2.8.13 Symfony DomCrawler Component
symfony/finder            v3.2.6  Symfony Finder Component
symfony/polyfill-mbstring v1.3.0  Symfony polyfill for the Mbstring extension

composer diagnose
Checking composer.json: WARNING
No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
require.symfony/dom-crawler : exact version constraints (2.8.13) should be avoided if the package follows semantic versioning
Checking platform settings: WARNING
The OpenSSL library (0.9.8zc) used by PHP does not support TLSv1.2 or TLSv1.1.
If possible you should upgrade OpenSSL to version 1.0.1 or above.

Checking git settings: OK
Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking github.com rate limit: OK
Checking disk free space: OK
Checking pubkeys:
Tags Public Key Fingerprint: ---numbers here---
Dev Public Key Fingerprint: ---numbers here---
OK
Checking composer version: OK

```

Can someone point me in the right direction here? Do I need to use/install other composer submodules/libraries?

Is it possible to do some sort of `composer update drupal/core --dry-run` as a test?

# Answer
Posting as an answer instead of a comment.

You run Composer from the project directory, which is where your composer.json and .lock file (which will get generated for you) lives.

I can work on any project at any time in the CLI by `cd` ing to the project I want to work on. Composer understands that **this** is the working directory in that execution.

So, no matter where you are in your server, Composer will execute in the directory you are currently in.
> 3 votes

---
Tags: 8, composer
---


title: Restore missing main menu

text:
# Question
Title: Restore missing main menu
I have managed to hide/lose the main menu bar - drupal 7.x.

overview of work I was doing:

* I added mediaelements.js
* I began adding videos to the site with add content
* I attempted to make a Videos menu in the main menu

It was during some point of this process that I noticed the main menu bar was missing. I have searched SE for solutions similar to mine and have not had success with what was presented as solutions (having main menu in block and appearance settings toggled). I have, so far, tried to go through each setting and compared them against settings in dev environment. Are their other troubleshooting tasks I should follow which may point to a resolution?

thank you

# Answer
> 0 votes
resolved - I had restricted the main menu block to specific content types. Removing the restriction restored main menu block across all content types.

---
Tags: nodes, navigation, configuration
---


title: How can I style the WYSIWYG content?

text:
# Question
Title: How can I style the WYSIWYG content?
Let's say I'm currently editing a page and there is a WYSIWYG editor in the backend to edit a specific part.

Now I add a table via the WYSIWYG. How can I apply CSS styles on that table WITHOUT altering the CKEditor plugin settings (I don't want to provide classes in the "Styles" dropdown)?

# Answer
> 3 votes
You can either implement hook\_ckeditor\_css\_alter or you can add `ckeditor_stylesheets` to your themes info.yml file.

See: hook\_ckeditor\_css\_alter for more.

Example:

```
function mymodule_ckeditor_css_alter(array &$css, Editor $editor) {
  $css[] = drupal_get_path('theme', 'mytheme') . '/css/mymodule-ckeditor.css';
}

```

Or in mytheme.info.yml:

```
ckeditor_stylesheets:
  - css/styles.css

```

# Answer
> 0 votes
You can do this by flipping to HTML source, and adding a class in the html.

Perhaps this is for a user that you do not want to give privileged permissions to? (which I assume would include 'Source' button on a WYSIWYG)

If so maybe you can generally style a table in a nice way (ie not need a class or inline styling) or perhaps target the area that this table will be displaying, if its a particular node type you could target that existing class and style the table beneath that:

```
.custom_content_type table {
  /* Your styles here*/
}

```

---
Tags: 8, wysiwyg
---


# Question
Title: 'invalid render array key' error when using an associated array for a twig variable
I have a list of images, and I want access to both the direct path to the image, and the path with an image style applied to it available to a Twig template.

I'm grabbing the images in my .theme file like so.

```
$images = $node->get('field_image');

foreach($images as $image){
    $image_style =Drupal\image\Entity\ImageStyle::load('photos')->buildUrl($image->entity->getFileuri()),
    $image_path = file_create_url($image->entity->getFileuri()),
}

```

I want to be able to access these attributes for each image by storing them in the `$variables` array.

I attempted to do so by using

```
foreach($images as $image){
    $image_style =Drupal\image\Entity\ImageStyle::load('photos')->buildUrl($image->entity->getFileuri()),
    $image_path = file_create_url($image->entity->getFileuri()),
    $variables['photos'][]['image_style'] = $image_style;
    $variables['photos'][]['image_path'] = $image_path;
}

```

However that didn't work and I received errors. After that I figured that maybe I needed to supply a more explicit associative array so I tried

```
    $variables['photos'] = array();
    $photo_paths = array();
    foreach($images as $image){
        $photo_paths += [
            $i => [
                'image_style' => Drupal\image\Entity\ImageStyle::load('photos')->buildUrl($image->entity->getFileuri()),
                'image_path' => file_create_url($image->entity->getFileuri()),
            ],
        ];

        $i += 1;
    }
    $variables['photos']= $photo_paths;

```

But then I receive the errors

> User error: "image\_style" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

and

> User error: "image\_path" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

These errors continue for each image. I'm guessing that `$variables` can't handle nested associative arrays? Is there a way I can use an associative array inside a Twig variable? Or is there another way to accomplish the same task or storing the path and image style for each individual image to be displayed in a for loop in Twig?

# Answer
> 5 votes
Twig doesn't understand what you put in the keys `image_style` and `image_path`. Twig can handle only arrays when the children are renderable. And this means they have to contain a `'#type'` or `'#theme'` key with a valid render element or theme name. For image styles use the theme `image_style`:

```
$variables['photos'] = [];
foreach ($images as $image) {
  $variables['photos'][] = [
    '#theme' => 'image_style',
    '#style_name' => 'photos',
    '#uri' => $image->entity->getFileUri(),
  ];
}

```

Then Twig can render the images like they're supposed to be rendered without the need for custom PHP code.

---
Tags: theming, 8
---


# Question
Title: How to apply dynamic block layout depending upon number of nodes in it (Drupal 8)?
I have very challenging task. Can any expert guide me?

(NOTE: This is for Drupal 8)

There is a requirement to show nodes in a block in a way that block must adopt style automatically depending upon the number of nodes in it.

For Example: If there is only node published under news content type then block must adopt single news article layout in teaser mode, And If there are published 2 nodes under news content type then block must now adopt the layout of 2 nodes and so on.

and this continues to 10 nodes

I know we can create views but how to apply conditions to check how many nodes are there under any content type and apply block layout accordingly?

Can anybody help?

Thanks Mithow

# Answer
Not everything is clear in your question, but there are some approaches for that task. For example if you are using views module you can count number of views rows in twig template:

```
{% if rows|length == 2 %}
   {% for row in rows %}
//Here some staff for two rows
   {% endfor %}
{% endif %}

```

About twig, about views templates

Also you can use jquery `$('.some-class-for-every-row').length` and add some style using js.
> 0 votes

---
Tags: 8, blocks
---


title: Embed RichFilemanager

text:
# Question
Title: Embed RichFilemanager
I want to embed RichFilemaneger (https://github.com/servocoder/RichFilemanager) in a Drupal-8 site. RichFilemanager has its own index.html and a php-conncetor for implementation in other sites.

But it's not clear to me which approach to follow.

Should i keep RichFilemanager in it's own directory in the Drupal-root and connect to it via the php-connector? In that case it seems to me that Drupal can't take care of the security... or should i copy the content of the index.html to a twig template? But that would make it hard to keep up with updates of RichFilemanager.

Can anyone point me in the right direction? Are there similar tools implemented which i could use as an example?

# Answer
You should include it with composer to your Drupal project. That is step one. You don't need to consider package management - composer will do this for you.

How you wire it up from there is basically up to you and your use case. I assume first you start with a basic controller and go from there in a custom module.
> 0 votes

---
Tags: 8
---


title: Selecting an entity reference once

text:
# Question
Title: Selecting an entity reference once
I am working on this project, parking management system. I have the admin populating the parking slots available in the building. Then an anonymous user visits the site, puts their details and those of their car, and then in drop down selects a parking slot. The parking slots are an entity reference fetched from what the admin populated. How do I make the system dynamically populate this dropdown so that the user only sees the empty slots? Like after they book slot A, I want it to disappear so that the next person booking does not see it in the dropdown list of available slots. This is to avoid two or more people booking the same slot. The image below shows the drop down am talking about.

# Answer
I guess the Parking slot 1, Parking slot 2, etc. are nodes or fieldable entities. Most likely those nodes (or entities) have a boolean field which indicates if the parking slot is reserved already. For the sake of this example, I call it field\_reserved.

In this case you need to implement in a custom module a `hook_form_alter().` I am going to write a pseudo code.

```
function mymodule_form_alter($form, $form_state) {

  // Check if the form id is the id of your form.

  // Use entity query that selects the node ids  of the nodes that are reserved.

  //Store the result in some array (let's say reserved_slots array).

  // With a foreach loop, check each select option id against the reserved_slots array of ids.

  //If such option exists, unset it.
}

```

Hopefully this gives you some guidance. If you need a complete snippet, you will have to provide more data about your setup, like machine name of the fields, etc.
> 1 votes

---
Tags: 8
---


# Question
Title: How to configure list page/detail page view?
I have created a new content type and show a list of all content of this type (list page). I have used the page URL article.

The detail page should be a child of article f.e. **article/1**. I configured the second view with path **article/%**.

How can I configure the detail view correctly and change the link in the list?

# Answer
You don't need a URL argument for this. You can make the View path '`articles`' and give it the following:

* Filter by content type = article
* Filter by status = published
* Sort by created date, descending
* Enable pager

That will give you a basic View listing articles, paged out, in descending order, on the url "articles".
> 1 votes

# Answer
For your list page, set the path to be "/article" in your view. For the node page (detail page) use Pathauto to configure the path for each node. Under Pathauto configuration add a pathauto pattern and choose your content type. In the Path Pattern field enter article/\[node:nid\]. This should give the desired url "article/1". Hope this answer your question.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to display previous and next arrows in views
I am trying to create a views block that will display one item on a page. I like to display next and previous arrows but I see the next arrow by default and I do not see the previous arrow until I am on 2nd page. I can remove the numbers but how can I display only next and previous arrows by default?

# Answer
> 1 votes
There can only be a previous button if there are content before the current page. So logically there is no content before page 1. So obviously there will not be any previous page to go to.

---
Tags: views
---


title: REST won't work

text:
# Question
Title: REST won't work
On a Drupal6 installation I have the REST service enabled (6.x-3.3).

All seems to setup correctly, but I cannot query any data and get always 404 Not Found.

What is the correct URL for retieve node #1:

```
    http://local.host/rest/node/1
    http://local.host/services/rest/node/1

```

None of them returns any data.

```
$endpoint = new stdClass;
$endpoint->disabled = FALSE; /* Edit this to true to make a default endpoint disabled initially */
$endpoint->api_version = 3;
$endpoint->name = 'rest';
$endpoint->server = 'rest_server';
$endpoint->path = 'rest';
$endpoint->authentication = array();
$endpoint->server_settings = array(
  'rest_server' => array(
    'formatters' => array(
      'json' => TRUE,
      'bencode' => FALSE,
      'jsonp' => FALSE,
      'php' => FALSE,
      'rss' => FALSE,
      'xml' => FALSE,
      'yaml' => FALSE,
    ),
    'parsers' => array(
      'application/json' => TRUE,
      'application/vnd.php.serialized' => FALSE,
      'application/x-www-form-urlencoded' => FALSE,
      'application/x-yaml' => FALSE,
      'multipart/form-data' => FALSE,
    ),
  ),
);
$endpoint->resources = array(
  'node' => array(
    'operations' => array(
      'retrieve' => array(
        'enabled' => 1,
      ),
      'create' => array(
        'enabled' => 1,
      ),
      'update' => array(
        'enabled' => 1,
      ),
      'delete' => array(
        'enabled' => 1,
      ),
      'index' => array(
        'enabled' => 1,
      ),
    ),
    'relationships' => array(
      'files' => array(
        'enabled' => 1,
      ),
      'comments' => array(
        'enabled' => 1,
      ),
    ),
  ),
  'system' => array(
    'actions' => array(
      'connect' => array(
        'enabled' => 1,
      ),
      'get_variable' => array(
        'enabled' => 1,
      ),
      'set_variable' => array(
        'enabled' => 1,
      ),
      'del_variable' => array(
        'enabled' => 1,
      ),
    ),
  ),
);
$endpoint->debug = 0;

```

*Update*

Get this running now:

# Answer
> 1 votes
```
$endpoint = new stdClass();
$endpoint->disabled = FALSE;
$endpoint->api_version = 3;
$endpoint->name = 'rest';
$endpoint->server = 'rest_server';
$endpoint->path = 'rest';
$endpoint->authentication = array();
$endpoint->server_settings = array(
  'rest_server' => array(
    'formatters' => array(
      'json' => TRUE,
      'bencode' => FALSE,
      'jsonp' => FALSE,
      'php' => FALSE,
      'rss' => FALSE,
      'xml' => FALSE,
      'yaml' => FALSE,
),
'parsers' => array(
  'application/json' => TRUE,
  'application/vnd.php.serialized' => FALSE,
  'application/x-www-form-urlencoded' => FALSE,
  'application/x-yaml' => FALSE,
  'multipart/form-data' => FALSE,
  ),
 ),
);
$endpoint->resources = array(
 'comment' => array(
  'operations' => array(
  'create' => array(
    'enabled' => '1',
  ),
  'retrieve' => array(
    'enabled' => '1',
  ),
  'update' => array(
    'enabled' => '1',
  ),
  'delete' => array(
    'enabled' => '1',
  ),
  'index' => array(
    'enabled' => '1',
  ),
),
'actions' => array(
  'countAll' => array(
    'enabled' => '1',
  ),
  'countNew' => array(
    'enabled' => '1',
  ),
),
  ),
'file' => array(
'operations' => array(
  'create' => array(
    'enabled' => '1',
  ),
  'retrieve' => array(
    'enabled' => '1',
  ),
  'delete' => array(
    'enabled' => '1',
  ),
  'index' => array(
    'enabled' => '1',
  ),
),
'actions' => array(
  'create_raw' => array(
    'enabled' => '1',
  ),
 ),
),
'node' => array(
'operations' => array(
  'retrieve' => array(
    'enabled' => '1',
  ),
  'create' => array(
    'enabled' => '1',
  ),
  'update' => array(
    'enabled' => '1',
  ),
  'delete' => array(
    'enabled' => '1',
  ),
  'index' => array(
    'enabled' => '1',
  ),
),
'relationships' => array(
  'files' => array(
    'enabled' => '1',
  ),
  'comments' => array(
    'enabled' => '1',
  ),
),
'targeted_actions' => array(
  'attach_file' => array(
    'enabled' => '1',
  ),
  ),
 ),
 'system' => array(
 'actions' => array(
  'connect' => array(
    'enabled' => '1',
  ),
  'get_variable' => array(
    'enabled' => '1',
  ),
  'set_variable' => array(
    'enabled' => '1',
  ),
  'del_variable' => array(
    'enabled' => '1',
  ),
 ),
 ),
 'taxonomy_term' => array(
'operations' => array(
  'retrieve' => array(
    'enabled' => '1',
  ),
  'create' => array(
    'enabled' => '1',
  ),
  'update' => array(
    'enabled' => '1',
  ),
  'delete' => array(
    'enabled' => '1',
  ),
  'index' => array(
    'enabled' => '1',
  ),
),
'actions' => array(
  'selectNodes' => array(
    'enabled' => '1',
  ),
),
),
'taxonomy_vocabulary' => array(
'operations' => array(
  'retrieve' => array(
    'enabled' => '1',
  ),
  'create' => array(
    'enabled' => '1',
  ),
  'update' => array(
    'enabled' => '1',
  ),
  'delete' => array(
    'enabled' => '1',
  ),
  'index' => array(
    'enabled' => '1',
  ),
),
'actions' => array(
  'getTree' => array(
    'enabled' => '1',
  ),
),
),
'user' => array(
'operations' => array(
  'retrieve' => array(
    'enabled' => '1',
  ),
  'create' => array(
    'enabled' => '1',
  ),
  'update' => array(
    'enabled' => '1',
  ),
  'delete' => array(
    'enabled' => '1',
  ),
  'index' => array(
    'enabled' => '1',
  ),
),
'actions' => array(
  'login' => array(
    'enabled' => '1',
  ),
  'logout' => array(
    'enabled' => '1',
    'settings' => array(
      'services' => array(
        'resource_api_version' => '1.0',
      ),
    ),
  ),
  'register' => array(
    'enabled' => '1',
  ),
 ),
),
);
$endpoint->debug = 0;

```

can you check with this code

# Answer
> 1 votes
Take a look at Services Installation and Setup

Also you can read Testing resources on a test server to dig deeper.

### Adding a REST server

* Browse to admin/build/services
* Click on the Add tab
* Set the name of you rest server for example rest\_server
* Select the **REST** to be the Server Type
* Type the Path to endpoint, I set to rest\_server\_endpoint
* Authentication to be **Session authentication**
* Save
* Switch to the Server tab and allow application/x-www-form-urlencoded as a request paring type
* Switch to the resources tab and select the resources you need to manipulate with rest client for example if you need to login check on users-\> login
* Save

# Answer
> 0 votes
After successful installation of rest service, and setup the endpoint url. If you still getting the page not found error means, try to change the path to end point and try . it will work fine !

---
Tags: services, 8
---


# Question
Title: How to use views to display a list of views pages?
I currently have a view that outputs all the current nodes on a site in a table format to display things like:

* Title
* Nid
* Path
* Metatag Title
* Metatag Description
* Metatag Keywords
* Post Date
* Updated Date
* and an edit link.

We mainly use this view to review our SEO optimisation in terms of the meta tags and the path constructions for each "page" on the site.

It's a nice system, but it has one major failing - it does not include any views pages - things like event listings or news listing pages. These views pages are just as important for SEO optimisation but I cannot get them to be included in this review list.

The metatag information is provided by the D7 Metatag module. With that module, we can add tag information to views pages, which is great, but to complete this admin view, it would be good to be able to include the views pages on the site in the above list as well.

It would be fine for this to be displayed in a standalone output (ie not included in the full table page above) but I cannot for the life of me find a way to get this done.

Is there any way to create a view that will list all view pages on a site with their associated meta information?

Thanks!

# Answer
> 1 votes
What you're asking is not possible. De data that the views stores is not provided back to the views module. As you've noticed, you're not able to create a list of views using a view.

I can think of two options to make this possible:

* Create a (complete) custom module that selects and outputs the values you desire
* or, provide the views module with the data you need to create the list you want

Both options require custom code to make it possible. At this moment, both views and metatags don't allow you to do what you want.

# Answer
> 0 votes
I am not aware of a way to list views pages in a view. What I do as a workaround, though, is to create a content type called something like "Interface Element" and give it text and image fields and create nodes with direct links to the views pages. Then I can create a view that lists those nodes.

# Answer
> 0 votes
You can achieve this by using Views Field View Module. You might have to drill down some tutorial on the web.

---
Tags: views
---


# Question
Title: How to let flexslider's picture point to its own node uri?
I do several step below:

1 Add a PIC field to "artical" node type. 2 Make a view and set it flexslider,then limited type "artical",show "PIC" field.

And now I need to make slider that when I click on picture,the browser jump to the exect node that picture own.

How to do so?

# Answer
> 0 votes
you can set the configuration in the view configuratin page, just see my screen shot.

---
Tags: javascript
---


# Question
Title: Drupal 8, The file used in the Image field may not be referenced
I am using managed file type to upload image in my custom form (Drupal-8). I am able to retrieve the given image while editing by using the below code

```
$form['image_field'] = array(
   '#type' => 'managed_file',
   '#title' => t('Image'),
   '#default_value' => array($fid),
);

```

While i am trying to save once edit, i am getting the "The file used in the Image field may not be referenced." error.

Please let me know to over come this error and let me what this error trying to convey.

# Answer
> 2 votes
Check \Drupal\file\Element\ManagedFile for answer, it appears that your file is being saved as permanent, but there is no entry in file\_usage table:

```
if ($file = File::load($fid)) {
      if ($file->isPermanent()) {
        $references = static::fileUsage()->listUsage($file);
        if (empty($references)) {
          // We expect the field name placeholder value to be wrapped in t()
          // here, so it won't be escaped again as it's already marked safe.
          $form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
        }
      }
    }

```

If you want to store your files permanently, you need to make sure they've got usage entries, to do so, you can tweak you form submit handler a little bit, here's some quick example:

```
// get file fid wherever it is
$values = $form_state->getValues();
$fid = $values['my_file_field'];

// call file usage service and load file
$file_usage = \Drupal::service('file.usage');
$file = File::load($fid);

// set file status permanent
if(!$file->isPermanent()){
  $file->setPermanent();
}

// check file usage , if it's empty, add new entry
$usage = $file_usage->listUsage($file);
if(empty($usage)){
  // let's assume it's image
  $file_usage->add($file,'mymodule','image',$fid);
}
$file->save();

```

---
Tags: 8, files
---


title: Date field comparison in Rules

text:
# Question
Title: Date field comparison in Rules
I'm trying to check if a date field value has been changed on a node update. (Rules Drupal 7)

Here's my rule configuration:

```
    { "rules_node_update" : {
    "LABEL" : "Update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--expedient" : { "bundle" : "expedient" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node-unchanged" ], "field" : "field_tria" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-tria" ],
          "value" : [ "node:field-tria" ]
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "UPDATED DATE" } } ]
  }
}

```

Event: Before saving (i have already tried with node update)

NOT data comparison Parameter: Data to compare: \[node:field-tria\], Data value: \[node-unchanged:field-tria\]

What i'am trying to do here is... IF the (new) date value IS NOT EQUAL to unchanged field value (old)... THEN do something. (like print message on screen)

The result of the data comparison returns always TRUE and don't know why.

**Notes**:

* Having proven the suggested changes, the result remains the same. I edit a node, and whether I change the value of the "tria" field or not, it still returns true.
* If I (temporary) OMIT the data comparison it shows the final message. Here's an example of what i'm getting with my setup: Edit a node of this content type, the node already has a date data in the "tria" field. Without making any changes, just save. It shows the message. If i change that field value to another and then save. It also shows the message. So, i think node-unchanged value must me empty because she's not doing the data comparison the right way.
* Here is the debug of the variables after saving/updating a content : Debug value Parameter: Value to debug: \[node-unchanged:field-tria\] ... (Array, 1 element) 0 (Array, 6 elements) value (String, 19 characters ) 2001-01-10 01:00:00 value2 (String, 19 characters ) 2001-01-10 01:00:00 Debug value Parameter: Value to debug: \[node:field-tria\] ... (Array, 1 element) 0 (Array, 10 elements) value (String, 19 characters ) 2001-01-20 01:00:00 value2 (String, 19 characters ) 2001-01-20 01:00:00 Values are there, and they are different! as expected!
* The rule evaluation log shows this once the node has been updated with different values:

The rule evaluation log shows this once the node has been updated with no changes on the values... just saved

# Answer
> 4 votes
### Part 1 - Just to be sure

Add an extra Rules condition like "entity has field", related to that `field-tria`, before your existing Rule Condition where you do that data comparison.

If that doesn't seem to help, then (temporary) remove the data comparison, to make sure your message is shown for those scenarios as in your Rules Event / Condition (that the entity has that field). If you even don't get the message in this case, then something is really wrong with your rule (eg: you'd be using the wrong Rules Event).

### Part 2 - Rules debugging needed

If the above doesn't help, I suggest you start some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?", to get more details about why your rule doesn't seem to work as you'd want it to.

### Part 3 - Why your data comparison cannot work

As per your additional comment "*this is a multi value field*": THAT pretty much explains why your rule seems to behave bizarre ... But sorry, it's rather that you're trying to make Rules do something (compare 2 values), without providing Rules all the info it needs.

If I was to show you 10 glasses of beer (each with their own label say), and I also show you another glass and ask you "is this other one the same?", then the predictable question that would come up is "as compared to which of those 10 glasses?". So that's similar to what's happening in your current rule.

### How to move forward

Your Rules Event is pretty sure OK, but you're missing a crucial Rules Action: a Rules **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should add a loop related to that list of dates (which you confirmed to be a multi value field). After you do, you should iterate over each item in that list (= each date). And for each iteration you should then perform the "*equivalent of the Rules Condition*" you are trying to get to work, whereas you should be using the list item being processed in the current iteration step).

To be honest, I'm afraid that the above will get you closer to the complete solution, but the remaining challenge appears to be "how to specify the date value (a single one) that is to be compared with each of those date-list-items?". Correct me if I'm wrong, but your question is still not clear on that.

PS: this answer (cearly) relates to D7.

# Answer
> 2 votes
The problem here was that the date field was a multi value field. So the data comparison does not work. Instead of using that function, (after much debugging. Thanks to @Piere.Vriens) I have chosen to create my own validator in php and it is simple like this:

```
if(isset($node->field_tria['und'])){
$day1 = $node->field_tria['und'][0]['value'];
$day2 = $node_unchanged->field_tria['und'][0]['value'];
if ($day1 != $day2) {
return true;
}
}

```

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


# Question
Title: How to set programmatically multiple arguments for views contextual filters
How to set programmatically multiple arguments for views contextual filters?

I can do it with one argument, it works great, but not with multiple arguments.

I want to select all nodes created by a list of people, but views only takes first in array into consideration:

```
$array = array(3250,32);
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();

```

Am I doing something wrong?

# Answer
First you should set this option: View → Advanced → Your Contextual Filter → More → Allow Multiple Values. Then when passing array should be with '+', so, your example:

```
$array = array('3250+32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();

```
> 11 votes

# Answer
If you're simply looking to render the view with its arguments (and don't need to do any more work on it), you can just call views\_embed\_view(). It's called like so:

```
<?php print views_embed_view($view, $display, $arg1, $arg2, ...); ?>

```

The $view and $display are the machine names of same. See the above-linked documentation for details.
> 6 votes

# Answer
Another one approach, which proved to be quite useful:

```
$array = array('3250', '32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->pre_execute($array);
$view->execute();
$content = $view->render();

```

`pre_execute()` method of view object accepts arguments, that will be passed to corresponding contextual filters. E.g. `'3250'` will be passed to the first contextual filter, `'32'` \- to the second one.

More info about method here.
> 1 votes

# Answer
are you sure your view is looking for integer values here? try this:

`$array = array('3250','32'));`
> 0 votes

# Answer
Also you can replace this `$array = array(3250,32);` to `$array = array('3250,32');`
> 0 votes

---
Tags: views
---


# Question
Title: How to get the main menu and sub menu of a main menu
I've three main menus, like "About", "Organisation", and "For us"

For the main menu About, it has three sub menus, they are "About You", "About Us", and "About the people around you". I've created a twig like menu--main--main-navigation.html.twig

In this i've tried to include this code, but it gives the first main menu, its sub menus, also second sub menus (sub main menu doesn't show up).

How do I do this

```
    {% import _self as menus %}

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul class="main-menu full-width relative-position center-container">
    {% else %}
      <ul class="sub-menu full-width">
    {% endif %}
    {% for key,item in items %}
      {#{{ kint(key) }}#}
      {#{{ kint(item) }}#}
          <!-- First coloumn -->
          <li class="col-1 relative-position">
            {% set title %}
              {{ item.title|striptags('<i>, <a>')|raw }}
            {% endset %}
            {{ link(title, item.url) }}
            {% if item.below %}
              {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
            {% endif %}
          </li>
    {% endfor %}
      </ul>
    {% endif %}
  {% endif %}

{% endmacro %}

```

# Answer
> -1 votes
You need to create `menu--main.html.twig` template and add below code.

```
{#
 /**
  * @file
  * Default theme implementation to display a menu.
  *
  * Available variables:
  * - menu_name: The machine name of the menu.
  * - items: A nested list of menu items. Each menu item contains:
  *   - attributes: HTML attributes for the menu item.
  *   - below: The menu item child items.
  *   - title: The menu link title.
  *   - url: The menu link url, instance of \Drupal\Core\Url
  *   - localized_options: Menu link localized options.
  *   - is_expanded: TRUE if the link has visible children within the current
  *     menu tree.
  *   - is_collapsed: TRUE if the link has children within the current menu tree
  *     that are not currently visible.
  *   - in_active_trail: TRUE if the link is in the active trail.
  *
  * @ingroup themeable
  */
  #}
  {% import _self as menus %}
  {#
    We call a macro which calls itself to render the full tree.
    @see http://twig.sensiolabs.org/doc/tags/macro.html
  #}
  {{ menus.menu_links(items, attributes, 0) }}
    {% macro menu_links(items, attributes, menu_level) %}
      {% import _self as menus %}
        {% if items %}
          {% if menu_level == 0 %}
             <ul{{ attributes.addClass('nav navbar-nav') }}>
          {% else %}
             <ul {{ attributes.addClass('submenu dropdown-menu') }}>
          {% endif %}
             {% for item in items %}
               <li{{ item.attributes }}>
                 {{ link(item.title, item.url) }}
                 {% if item.below %}
                   {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                 {% endif %}
              </li>
            {% endfor %}
            </ul>
         {% endif %}
      {% endmacro %}

```

---
Tags: 8, theming, navigation
---


# Question
Title: Using a field in many content types? Usual or completely wrong?
A basic question: Is there anything wrong with using a defined field in many content types? For example: body, image\_field? Are there any problems to be expected when I do this? My guess is: No. No problems. But: is that right?

# Answer
> 3 votes
Deciding if what your question is about is right or wrong, is something you'd have to decide for yourself. However by reusing field you're actually using one of the typical Drupal facilities to define fields.

In the context of "reusability", one would think that it is a good practise to reuse whatever can be reused.

The challenge (problem?) is that when changes are needed to a reused field, it'll be more difficult to do so for reused fields as compared to a field that is not reused at all.

To get a feeling of this, do some experiments with the Features module, for 2 scenarios: (a) changes to a reused field and (b) changes to a field that is not reused anywhere. Just look at the size of the features created in both scenarios.

My approach is becoming more and more to NOT reuse fields, to not complicate things when later on (design) changes are needed (to ensure maintainability as much as I can). This approach is also partially based on what I've learned from what's further detailed below, which applies to any release of Drupal ... (though I'm curious myself to see how things will evolve related to Relativity for Drupal 8).

### Relativity model

There is an (illuminating) article "Relativity Model for Drupal", especially the related page about "Wrapping Information Architecture and Documentation". Here is a quote from it:

> To create an Event content type in Drupal is a simple task. But there's a nuance to that task that is overlooked very often. That nuance is the machine name. But why is the machine name of a content type such an important step?
>
> * It gives the content type an explicit name of your choosing and allows database indexing to act on that machine name while being queried.
> * All fields contained within that content type will share the same machine name before the field name. This allows the Views module to clearly gather field data in a very defined manner using the indexed machine name.
> * Fields that are entity references out to other content types also begin with the same machine name followed by their own machine name. This allows simple and visual identification for origination and destination of data relationship.

It also contains an interesting example of what seems to be a great naming convention.

**Remark** (cfr comment from Kevin): The most difficult part is knowing when you would reuse a field vs when you won't. The big obstacle is shared field settings - changing certain settings affects all fields, when you probably only want to affect that instance.

---
Tags: theming, nodes
---


# Question
Title: How do I programmatically render a custom entity?
I created a custom entity (*submenu*) in Drupal 8. I need to render this custom entity in my custom module. This is the code I am using.

```
$entity_type = 'submenu';
$entity_id = '1'; // static for example purpose
$view_mode = 'full';

$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('submenu');
$pre_render = $view_builder->view($entity, $view_mode);
$render_output = render($pre_render);

```

I keep getting the following error.

> TypeError: Argument 1 passed to Drupal\Core\Entity\EntityViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given

Why do I get this error?

# Answer
Make sure the entity id exists and the error disappears.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: How to add query parameters to a CacheableJsonResponse's cache?
I have an API which returns various json, like terms of a vocab, nodes of a type, with specific fields and so on.

Now, in my API I am getting the requested language like so:

```
$request = \Drupal::request();
$lang = $request->query->get('lang', 'en');

```

And load the respective translations of the entities.

Now, how can I add that `$lang` parameter as a cache indicator? So that:

```
/myapi/nodes?lang=en

```

creates another cache than:

```
/myapi/nodes?lang=klingon

```

Also, is that the right way to deliver language specific content in an API?

# Answer
Add a cache context for the query parameter to the response:

```
$cache_metadata = (new CacheableMetadata())->addCacheContexts(['url.query_args:lang']);
$response->addCacheableDependency($cache_metadata);

```

---

About the second question, when this issue is resolved you can use core REST to deliver translated entities: https://www.drupal.org/node/2135829
> 5 votes

---
Tags: routes, caching, 8
---


# Question
Title: Get the value of a field inside a paragraph field in hook_preprocess_field
I'm usign the module Paragraphs for Drupal 8. I need to print the raw value of a paragraph field in the twig template, so I'm trying to access to the value of the field in the hook\_preprocess\_field, but I don't know how to access the value in $variables.

Any idea?

# Answer
> 4 votes
You can use preprocess field hook which is supported in drupal 8 also . Example below:

```
function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
   print_r($variables);
    // add a class to the field
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}

```

# Answer
> 4 votes
To get at the value of a paragraphs field for manipulation etc you can use `template_preprocess_paragraph(&$variables)` or more specifically `template_preprocess_paragraph__PARAGRAPH_TYPE(&$variables)`

# Answer
> 0 votes
One Good solution for that is to first install Devel module and then you can use dsm function.

this function is easy to use just write `dsm($variables)` and it will print a hierarchical form of element.

Using that you will know how to have access to your desired values and fields.

---
Tags: 8
---


# Question
Title: How to change the 'Name' label on term add/edit pages programmatically?
In Drupal 7 this was pretty easy. But now when I try to change the term name label on the term add/edit form all I find are protected methods.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'taxonomy_MYVOCABULARY_form') {
    ksm($form['name']);
    // ?????
  }
}

```

This is no translation issue.

# Answer
> 4 votes
If you mean you want to change the title of the form element, then it is basically the same as it was in 7.x.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'taxonomy_MYVOCABULARY_form') {
    $form['foo']['#title'] = t('New Title');
  }
}

```

Adding in what 4k4 said... field widgets behave differently than general form items:

```
$form['name']['widget'][0]['value']['#title'] = 'New Title';

```

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


# Question
Title: Set xdebug.max_nesting_level to higher value
On my Drupal 8 installation, I am getting this Requirement Problem:

```
Xdebug settings
   xdebug.max_nesting_level is set to 100.
   Set xdebug.max_nesting_level=256 in your PHP configuration as some pages in your Drupal site will not work when this setting is too low.

```

On my server, I tried setting it under `/opt/app-root/etc/php.ini.template` but doesn't work.

Can this be done on the settings.php or .htaccess?

# Answer
> 2 votes
Since xdebug.max\_nesting\_level is not available/cannot be found in my php.ini file.

What I did is adding this line to .htaccess from Drupal directory and this solves my issue.

```
php_value xdebug.max_nesting_level 256

```

---
Tags: 8
---


# Question
Title: menu block or view that shows only siblings and parents
It seems like this function was removed in drupal 8 so I am trying to find a solution that doesn't involve created a large amount of blocks or hard coding something. (Best would be a block or a view)

I have menu structure like this:

```
Parent 1
- Child 1.1
-- Grandchild 1.1.1
-- Grandchild 1.1.2
- Child 1.2
-- Grandchild 1.2.1
-- Grandchild 1.2.2
Parent 2
- Child 2.2
-- Grandchild 2.2.1
-- Grandchild 2.2.2

```

When I am on Grandchild 1.1.1 I want to see **only** the entire tree of Parent 1 (that means parent 1 plus all of its child and grandchild items), nothing from Parent 2 and below.

# Answer
If you need a solution quickly, you may want to see my post in the Menu Block issue queue:

https://www.drupal.org/node/2811337#comment-11752266

It sounds like I had the same issue you had, and this was the only way I could figure to get the behavior. You'll need the patch that introduces "Active Trail" and "Active Trail Parent" first, as options for Menu Block.
> 3 votes

# Answer
It seems this question has an ongoing patch at https://www.drupal.org/node/2811337 (which i found just after offering the bounty! :)
> 2 votes

# Answer
You can do this with css if there is no quick fix available by drupal
> -3 votes

---
Tags: 8, navigation
---


title: Downloading core via command-line

text:
# Question
Title: Downloading core via command-line
I usually download the latest Drupal 7 using `drush dl drupal --select`, but but Drupal 8 doesn't get listed.

What are some nice and quick ways of download the latest version of Drupal 8, even though it is still in alpha stage?

# Answer
> 35 votes
```
drush dl drupal-8

```

Since there are no *stable* releases of Drupal 8, you must use the --all option to see the tagged alpha releases:

```
drush dl drupal-8 --select --all

```

This also works.

```
drush dl drupal --default-major=8 --select --all

```

Both of these are now working in the current version of Drush, without the `--all` flag:

* `drush dl drupal-8 --select`
* `drush dl --default-major=8 --select`

Note that the Drush pm-\* commands only work with one major version of Drupal at a time, and that version currently defaults to Drupal 7. Therefore, `drush dl drupal` only shows the various Drupal 7 releases available, and does not include any versions of Drupal 8. This much has not changed.

`drush dl drupal-8` now works fine with the Drupal 8.0.0-rc1 release.

# Answer
> 4 votes
Since `drush dl` has been deprecated in recent Drush 9, so you need to use Composer in order to download Drupal 8 sources from the command line. E.g.

```
composer require drupal/drupal

```

Prefix with `sudo` to override the permissons (not recommended).

If you're in `/var/www/html` directory and you want to place your Drupal 8 sources there, you can run the following commands:

```
cd /var/www/html
sudo composer create-project drupal-composer/drupal-project:8.x-dev --no-interaction .
sudo ln -vs web/.* web/* .

```

Read about differences between `drupal/drupal` and `drupal-composer/drupal-project` here.

---

Alternatively download Drupal sources and extract them manually via:

`curl -s https://ftp.drupal.org/files/projects/drupal-8.2.7.tar.gz | tar --strip-components=1 -zxvf -`

Notes: Change the version to the latest one. Prefix `tar` with `sudo` if required.

---
Tags: drush, 8
---


title: Entity Translation for custom entity

text:
# Question
Title: Entity Translation for custom entity
I've created a custom entity and in the next step, I would like to use the Entity Translation module to make the entity translatable.

My entity is defined like this

```
/**
 * Implements hook_entity_info().
 */
function MY_MODULE_entity_info() {
  $info['custom_entity'] = array(
    'label' => t('Custom Entity'),
    'base table' => 'custom_entity',
    'module' => 'MY_MODULE',
    'uri callback' => 'custom_entity_basic_uri',
    'controller class' => 'EntityCustomController',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'qid',
      'label' => 'title',
    ),
    'translation' => array(
      'entity_translation' => array(
        'default settings' => array(
          'default_language' => 'de',
        ),
        'base path' => 'my-path/%custom_entity',
        'view path' => 'my-path/%custom_entity',
        'edit path' => 'admin/my-path/%custom_entity/edit',
        'translate path' => 'my-path/%custom_entity/translate',
        'path wildcard' => '%custom_entity',
      ),
    ),
    'static cache' => FALSE,
    'bundles' => array(
      'custom_entity' => array(
        'label' => 'Custom bundle',
        'admin' => array(
          'path' => 'admin/structure/custom/manage',
          'access arguments' => array('administer custom entities'),
        ),
      ),
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full'),
        'custom settings' => FALSE,
      ),
    ),
  );
  return $info;
}

```

With this definition, my custom entity appears in the Entity Translation admin view (`admin/config/regional/entity_translation`) and I can configure it. This seems to be correct, because in the 'manage field' tab, the language selector field appears and the 'translate' tab appears also in the edit form.

The only strange thing I found is that the language selector is not rendered in the edit form in any time. If I save the translation, the source entity is overriden with the changes, but no translation is added.

I thought the problem is my Controller class, but this seems to work correctly too:

```
class EntityCustomController extends EntityAPIControllerExportable {
  public function create(array $values = array()) {
    $values += array(
      'created' => REQUEST_TIME,
      'type' => 'custom_entity',
      'qid' => 0,
      'bundle_type' => 'custom_entity',
      'title' => '',
    );
    return parent::create($values);
  }

  /**
   * Save Task Type.
   */
  public function save($entity, DatabaseTransaction $transaction = NULL) {
    parent::save($entity, $transaction);
  }

}

```

In my custom edit form, I use `field_attach_form` function to render all the defined themes.

And, if it helps, this is my save handler:

```
/**
 * Save entity by using the controller.
 */
function MY_MODULE_custom_entity_save(&$entity) {
  return entity_get_controller('custom_entity')->save($entity);
}

```

# Answer
In my case the issue ended up being pretty simple to fix. I found that the function `entity_translation_form_alter()` was testing to see if my entity's edit form was suitable for alteration. My edit form failed the very first test because `entity_translation_edit_form_info()` was returning false.

`entity_translation_edit_form_info()` was returning false because my form didn't have `$form_state[$entity_info['translation']['entity_translation']['edit form']]` set and set to the entity I was trying to edit.

**tl;dr**: Make sure you set a value in your edit form's `$form_state` at the path you declare in the `edit form` element of the settings array for your entity returned by your implementation of hook\_entity\_info().
> 0 votes

---
Tags: 7, entities, i18n-l10n
---


# Question
Title: Loop trough items in view template and access field values?
Drupal 8 name of twig: views-view-grid--places.html

I'm extremely new to Drupal so bare with me and excuse any incorrect lingo.

I created a content type called places and added 2 fields (*body* and *field\_location*). *title* is a default for fields.

In my view twig, how do I get those values in my for loop?

```
{% for item in items %}
    <section>
        <div>{{ item.title }}</div>
        <div>{{ item.field_location }}</div>
        <div>{{ item.content }}</div>
    </section>
{% endfor %}

```

This only outputs the body. What am I missing?

# Answer
> 1 votes
Use `{{ dump(item) }}` to see the structure.

Once you have the structure you can reference in a faily regular way: if a sub-item is an array or an object, then it's a dot, if an array with a #, reference as an array eg xxx.yyy\['#zzz'\]

---
Tags: views, entities
---


# Question
Title: How do I retrieve the query parameters from a path?
How do I retrieve the query parameters from a path. Here's my path:

> /search?keys=hello

Here is what I've tried:

```
$test1 = \Drupal::request()->request->get('name');
$test2 = \Drupal::request()->query->get('name');
$test3 = \Drupal::service('path.current')->getPath();
$test4 = \Drupal::request()->server->get('REQUEST_METHOD');
$test5 = \Drupal::request()->query->get('q');
$test6 = \Drupal::request()->request->get('keys');
$test7 = \Drupal::request()->query->get('keys');
$test8 = \Drupal::request()->query->get('destination');
$test9 = \Drupal::request()->request->all();
$test10 = \Drupal::request()->getRequestUri();

```

Here are the results:

> Test 1: NULL
>
> Test 2: NULL
>
> Test 3: '/search'
>
> Test 4: 'GET'
>
> Test 5: NULL
>
> Test 6: NULL
>
> Test 7: NULL
>
> Test 8: NULL
>
> Test 9: array ( )
>
> Test 10: '/search'

Why is this not working?

# Answer
> 15 votes
This is a duplicate. If you look at the change log, there's a beautiful example for how to retrieve $\_GET and $\_POST variables.

I have tested locally at /search?keys=hello and

```
\Drupal::request()->query->get('keys');

```

works, as well as

```
\Drupal::request()->get('keys');

```

I tested your custom block and it works fine. Have you tried clearing cache?

Update:

If it is caching, you can set your block to not cache, since it's a search block. Or you can set it to cache for each set of parameters. Thanks @clive for the link.

# Answer
> 13 votes
You were close. All you need to do is get:

```
$keys = \Drupal::request()->get('keys');

```

Here is an example of me using it:

```
/**
 * Implements hook_preprocess_views_view()
 * @param $variables
 */
function mytheme_preprocess_views_view(&$variables) {
  if ($variables['id'] == 'acquia_search' && $variables['display_id'] == 'results') {
    $variables['get']['keywords'] = Xss::filter(\Drupal::request()->get('keywords'));
    $variables['get']['sort_by'] = Xss::filter(\Drupal::request()->get('sort_by'));
    $variables['get']['sort_order'] = Xss::filter(\Drupal::request()->get('sort_order'));

    if (!Unicode::strlen($variables['get']['sort_by'])) {
      $variables['get']['sort_by'] = 'search_api_relevance';
    }

    if (!Unicode::strlen($variables['get']['sort_order'])) {
      $variables['get']['sort_order'] = 'DESC';
    }
  }
}

```

# Answer
> 11 votes
The problem was the block was cached. See Clive's comment:

```
public function build() {
  $test = \Drupal::request()->query->get('keys');
  return array(
    '#markup' => $test,
    '#cache' => array(
      'contexts' => array(
        'url.query_args:keys',
      ),
    ),
  );
}

```

---
Tags: 8
---


# Question
Title: Is it possible to have placeholder text on a view filter with type date_text?
I've got an exposed filter on my view that allows users to specify a date, and I want to specify a placeholder for this text field.

I've tried doing this using the following code in a hook:

```
$form['field_start_end_dates_value']['value']['#attributes'] = array('placeholder' => array(t('Search')));

```

(I know this is in the correct hook as I'm successfully altering other form elements within the same form)

I've `var_dump`ed the form variable, and I'm getting the following output for the date filter:

```
[field_start_end_dates_value] => Array
        (
            [#tree] => 1
            [value] => Array
                (
                    [#title] =>
                    [#type] => date_text
                    [#size] => 20
                    [#default_value] =>
                    [#date_format] => j M Y
                    [#date_label_position] => within
                    [#date_year_range] => -3:+3
                    [#process] => Array
                        (
                            [0] => date_text_element_process
                        )

                    [#prefix] =>
                    [#suffix] =>
                    [#attributes] => Array
                        (
                            [placeholder] => Array
                                (
                                    [0] => Specify Date
                                )

                        )

                )

        )

```

This looks right to me, but I'm not seeing the placeholder on the front end.

I've tried flushing the cache multiple times, and loading the page without JavaScript enabled.

What am I doing wrong?

# Answer
*You are doing it wrong way*

Form alter doesn't work here. This is how it can be achieved:

It depends on which date element you are using There are few hooks available

```
hook_date_text_process_alter()
hook_date_popup_process_alter()
hook_date_combo_process_alter()
hook_date_select_process_alter()

```

I am showing for hook\_date\_text\_process\_alter()

```
/**
 * Implements hook_date_text_process_alter().
 */
function MYMODULE_date_text_process_alter(&$element, &$form_state, $context) {
  if ($form_state['complete form']['#form_id'] == 'views_exposed_form') {
    //dpm($form_state);
    if ($element['#id'] == 'edit-field-appintment-date-value-value') {
      $element['date']['#attributes']['placeholder'] = t('Demo placeholder');
      //dpm($element);
    }
  }
}

```

**For Other text elements** Below is the correct example of adding a placeholder to views\_exposed\_form to any other text field but date field can't be done like this.

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#attributes'] = array('placeholder' => array(t('Your Placeholder')));
}

```

Hope this helps
> 3 votes

# Answer
Apply the attributes to the element and not its value. The following should work:

```
$form['field_start_end_dates_value']['#attributes'] = array('placeholder' => array(t('Search')));

```
> 1 votes

# Answer
Or In Page load you can hack that text field using JQuery Like below

```
$("#yourId").attr('placeholder', 'Search');

```
> 1 votes

# Answer
You can check this. Its work fine for me...

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'views_exposed_form' && ($form['#id'] == 'views-exposed-form-test-date-page')) {
           // check for your field. here 'changed' value for 'update field'.
           $form['changed']['#attributes'] = array('placeholder' => array(t('Your Placeholder')));
    }
}

```
> 1 votes

# Answer
Here is what worked for me on Drupal 7 in 2017 (for a popup):

```
function MYMODULE_date_popup_process_alter(&$element, &$form_state, $context) {
  if ($form_state['complete form']['#form_id'] == 'views_exposed_form') {
    $form_state['complete form']['field_event_date_value2']['value']['#default_value'] = "";
    $form_state['complete form']['field_event_date_value2']['value']['#attributes'] = array('placeholder' => array(t('End Date')));
  }
}

```

I had to override the #default\_value (which, if is not a date, just leaves it blank), and THEN the placeholder will show. I guess it is populating the form with #default\_value, thus leaving it without a placeholder.
> 0 votes

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


# Question
Title: Updating Views Module Not Working 7.x-3.13 --> 7.x-3.15
Drupal has been telling me to update my views module from 7.x-3.13 to 7.x-3.15.

Everything seems to work fine. However, when I return to the admin pages, I receive "No update information available. Run cron or check manually." I proceed to run cron and Drupal simply tells me that I need to update the module again.

I've manually updated to the newest version (7.x-3.15) and even to the dev version (7.x-3.x-dev). In both cases, Drupal continued to tell me I needed to update the module.

Any ideas what's going on?

# Answer
I checked Views module versions from 7.x-3.13 to 7.x-3.15 and it seems that there are no changes needed to be applied to the database (the views.install file didn't change between the two versions). I think you need just to override the module directory with the new version and clear all caches.
> 0 votes

---
Tags: views
---


# Question
Title: How to add third column to the drupal view (Format: Table), col3=col1/col2 with sorting by col3?
I am using Views module. The view has two columns. In the third column, I want to "col1/col2", but the most important is that the column can be sorted

# Answer
> 0 votes
If you are using Table format, you should have 1 col for each visible Field you have added to your View. So if you have two Cols, add a third Field.

---
Tags: views
---


# Question
Title: Block caching not working for anonymous users despite setting cache contexts
I have a block plugin that displays different dynamic content depending on whether you're logged in or not. I attempted enabling this by setting the max-age setting in the #cache attribute of my render array to 0 like so

```
    if ($user->hasRole('anonymous')) {
            if ($loginrequired) {
                $content = [
                    '#markup' => '<p> Login required. <a href="/user/login">Click Here to Login</a></p>',
                ];
                return $content;
            }
    }
    $content = [
        'header'   => [
            '#markup' => $header_text,
        ],
        '#cache'   => [
            'max-age' => 0,
        ],
        $webform,
    ];
    return $content;

```

The dynamic content updates for logged in users, but for anonymous users it just displays exactly what the logged in user saw, instead of showing the login required message.

After doing some research it seems that drupal ignores max-cache for anonymous visitors and cache contexts would be required, according to this page

Disable form or block cache for anonymous users?

So I changed my code to reflect this

```
        '#cache'    => [
            'max-age'  => 0,
            'contexts' => ['user.roles']
        ],

```

I used user.roles since the content depended on whether the user was logged in or not. This had no effect. I then tried.

```
        '#cache'    => [
            'max-age'  => 0,
            'contexts' => ['user.roles:anonymous']
        ],

```

This also had no effect. Why does my method not work? What cache settings are required in order for the cache to be disabled even for anonymous users? Or is there a completely different method I should be using?

Note: I do not want to disable caching site wide. I would like to be able to disable caching on a plugin to plugin basis.

UPDATE: Looking at examples I also tried

```
   '#cache' => [
            'max-age'  => 0,
            'contexts' => ['url.path', 'url.query_args']
    ],

```

but that didn't work either.

# Answer
> 0 votes
The issue was that I had different render arrays set depending on whether the user was logged in or not, but the cache context only applied to one of the render arrays but not the other. If I have different possible render arrays being returned every single one needs to have the cache settings added.

I resolved the issue by changing my code to

```
if ($user->hasRole('anonymous')) {
        if ($loginrequired) {
            $content = [
                '#markup' => '<p> Login required. <a href="/user/login">Click Here to Login</a></p>',
                '#cache'   => [
                     'max-age' => 0,
                     'contexts' => ['url.path']
                 ],
            ];
            return $content;
        }
}
$content = [
    'header'   => [
        '#markup' => $header_text,
    ],
    '#cache'   => [
        'max-age' => 0,
        'contexts' => ['url.path']
    ],
    $webform,
];
return $content;

```

---
Tags: 8, blocks, caching
---


# Question
Title: How do I dynamically change an autocomplete route for a field depending on another field's value?
On my node edit form, I have a select field (Field A) and another taxonomy reference field (Field B). Field B is currently using "views" as a reference method to filter for the options.

When the select field has a value selected, I want the taxonomy reference field to show a different set of autocomplete options.

I was wondering if there was a good way to dynamically update the "argument" for the views reference filter for the taxonomy reference field depending on what was selected in the select field?

# Answer
> 1 votes
If I understand your question correctly, you may want to include one term reference field for each taxonomy you want included on the form. You could then create a template for the page and use Javascript to control which fields are visible. So if the user chooses Option A it gives them one set of choices for the Taxonomy and if they choose B it gives them another..

You may also have luck with https://www.drupal.org/project/conditional\_fields

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


# Question
Title: Display certain field values of submissions from multiple webforms in one view
I have two separate webforms, and I want to be able to display all submissions from both webforms that have the same value of a specific field. I also want different fields to be displayed based on what form they're coming from.

For example, both webforms have a field called area. I would like to display the submissions of both these webforms if they both have area set to the same value. Amongst these submissions, if they're from form 1, I want to display the values for field1,field2,and field3 in the view. If they're from form2, I want to display the values for field4,field5, and field6 in the view.

Is there a way to accomplish this in a view?

# Answer
You may want to read this: https://www.drupal.org/node/2497183

> Views cannot display information from more than one webform at a time **unless the webforms share the same components**.
>
> One solution would be to add order# as a hidden field so that all webforms have a component by this field key. I haven't tried having mixed component types for with the same field key, but I suspect it will work, at least with some view configurations

You may wind up having to create a template for a module to get the report you are looking for.

Drupal answers actually already has a post on this: Multiple Webforms in one View
> 1 votes

---
Tags: views, webforms
---


# Question
Title: Inject SQL_CALC_FOUND_ROWS into db_select()?
I've recently learned that `SQL_CALC_FOUND_ROWS` can give the number of rows in a table from almost any `SELECT` statement. It's raw SQL syntax is `SELECT SQL_CALC_FOUND_ROWS field1, field2, ... FROM ...`

Is there an existing way I can that inject that syntax into `db_select()`?

I want to use this for creating a pager, so I'm already selecting some rows in the first place. It would be handy to get a count out of the query I'm already running. Doing a separate count query would be extra work in my case.

# Answer
> 3 votes
As made evident in Compare db\_query() and db\_select() performance, `db_query()` is faster than `db_select()`, which should then be used when you need to make the query you are executing alterable from other module via `hook_query_alter()`, for example when you need to get a list of nodes for which a user has access.

If that is not your case, then you can use `db_query()` and using the query you are showing is quite straight as `db_query("SELECT SQL_CALC_FOUND_ROWS field1, field2 FROM ...")`.

---
Tags: database
---


# Question
Title: 'File used may not be referenced' if form field submits same image twice
I've built a custom module with a form that allows users to define custom site wide settings such as the icons that are meant to be used.

I'm able to upload and save images into the form using `managed_file` elements. However if I resubmit the form without changing what files are used I receive the message:

> The file used in the *First Icon Image* field may not be referenced.

*First Icon Image* was the name of my field in that case. Everytime I change the image used I don't receive the image. It's only when I submit the form again with the same values for the image fields.

I'm handling the image field with the following code:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.settings');
    $form['icon1_file'] = [
                '#type'            => 'managed_file',
                '#name'            => 'icon1',
                '#title'           => t('First Icon Image'),
                '#default_value'   => $config->get('icon1_file'),
                '#upload_location' => 'public://',
    ];
}

public function submitForm(array&$form, FormStateInterface $form_state) {
    $imageid = $form_state->getValue('icon1_file');

    $file = file_load($imageid[0]);
    if (gettype($file) == 'object') {
        $file->status = FILE_STATUS_PERMANENT;
    }
    $filename = File::load($imageid[0])->getFilename();
    $this->config('mymodule.settings')
         ->set('icon1_file', $form_state->getValue('icon1_file'))
        ->save();
    $file->save();
    $this->config('mymodule.settings')
         ->set('icon1_filename', $filename)
         ->save();
}

```

After doing some research I saw that a possible solution might be using `\Drupal::service('file.usage')->add` however I'm not sure what I'd use for the `entity_type` and `entity_id` parameters if that, indeed, is the solution.

How would I prevent the "File used in the field may not be referenced" when occurs on the second time I submit the form with the same file?

UPDATE: I added

```
$file_usage = \Drupal::service('file.usage');

```

and

```
$file_usage->add($file, 'mymodule', 'managed_file', $imageid[0]);

```

to the code, but it did not resolve my issue.

# Answer
> 3 votes
Using the skumy's approach worked for me, but instead of putting 'managed\_file' as the third parameter for $file\_usage-\>add(), I put 'file'.

```
$fid = $config['image'][0];
$file = File::load($fid);
$file->status = FILE_STATUS_PERMANENT;
$file->save();
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', 'file', $fid);

```

That's because putting 'managed\_file' causes an error when I check the file usages, following the links in the "*Used in*" column in /admin/content/files, since in my installation does not exist any entity called 'managed\_file'.

> *The "managed\_file" entity type does not exist*

Using 'file' instead of 'managed\_file' solves the problem.

# Answer
> 2 votes
Have you added this after

```
$file->save();

```

? Here is my code and it works with no errors :

```
$imageID = $config['image'][0];
$file = File::load($imageID);
$file->status = FILE_STATUS_PERMANENT;
$file->save();
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', 'managed_file', $imageID);

```

---
Tags: forms, 8, files
---


# Question
Title: Assigning (adding) an entity reference when an Order process is completed
In Drupal 8, I am needing to know how to assign/add an entity reference of an e-book to an multivalue entity reference field of the user when an order with the e-book is placed. This will allow the user to then access only the e-books attached to his user account.

What hook do I use? how do I know if there is a product in the order that have field\_ebook=true? Then how do add it to the list of entity references?

# Answer
> 2 votes
Not a hook but an event.

Orders have an attached workflow. You can listen to the event of an order being placed, see the state\_machine module for documentation on this. Basically, you need to define an event subscriber service, subscribe to the event `commerce_order.place.post_transition`, then check if order is an ebook and if so act based on the order customer ID.

The subscriber method needs like this:

```
public function orderStateChange(WorkflowTransitionEvent $transition_event) {
  $entity = $transition_event->getEntity();
  // Check the transition id and whetever else you need on the order and then do your thing.
  if ($transition_event->getToState()->getId() == 'completed' && ...) {

  }
}

```

---
Tags: 8, commerce, entities
---


# Question
Title: Load all/multiple fields from entity of certain type
I'm quite new to Drupal so bear with me here.

I've created an entity using Drupal Console, specifically using `drupal generate:entity:content`. Which works perfectly. Kudos to the Drupal console guys.

This specific entity will deal with adding some meta tags on specific URLs thru the site.

It has several fields that need to be completed: `url`, `keywords`(if any), one open graph tag, and a tag value.

After looking through this question I've decided that using `hook_page_attachments` is the way to go for me.

The logic for adding the tags is quite simple:

* Get the entity.
    + `$entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')`
* Grab the current url.
* Loop through the entity `url` fields and check if any matches the current url.
* If it does, simply add the tags.

And that's it.

---

The problem boils down this.

After I've loaded the entity (`$entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')`) I have no idea how to grab all the `url` fields.

I've looked over this question but it's not quite what I'm looking for.

# Answer
You should be able to use either get or getFields on your entity object if it is derived from ContentEntityBase.

See: https://drupal.stackexchange.com/a/232219/57

So, after you load the entity:

```
$fields = $my_entity->getFields();

```

Or:

```
$foo = $my_entity->get('bar')->value;

```
> 0 votes

# Answer
getStorage() does not load the entity.

It loads the storage handler that is able to load entities.

Usually you don't have one entity, you have many, one for each URL.

So you don't want to loop over fields in PHP, you want to do a query against the DB to find if you have an entity that matches the current url.

Look for entity query, there are various related questions on this site as well as documentation/tutorials elsewhere. For example: https://www.sitepoint.com/drupal-8-version-entityfieldquery/. Try that and if you still have a problem, I'd recommend you ask a more specific question with code you came up with.

Also, did you consider using the metatags module, which does something very similar, although based on a field on other entities and not a standalone entity: http://drupal.org/project/metatag
> 0 votes

---
Tags: 8
---


# Question
Title: Taxonomy images display in different view rows
I have a vocabulary that has an image field. To access this field in views, I added a relationship and then added the field in the fields section.

However, I have multiple terms and each term creates a new row... As this is highly undesirable, I would like to know how to fix it without making and embedding an additional view.

# Answer
Received answer from @Lendude on drupal forums here:

> Yeah, adding relationships will add rows, that is the way of SQL queries.
>
> If you enable aggregation and then group the results on the right column, that works in some use cases (make sure to set/save the column for your image field or you will run into this #2815881: Switching on aggregation on generates fatal "Column not found: 1054 Unknown column" SQL error when using multi-column Fields) Using the 'rendered entity' field with a specific view mode can work. This would possibly allow you to remove the relationship from the View itself.
> 0 votes

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


title: Pathauto and dynamic branch depth

text:
# Question
Title: Pathauto and dynamic branch depth
I downloaded the Pathauto module to have the taxonomy aliases generated dynamically. The problem is that the pattern apparently expects a fixed depth, while my taxonomy is not that stiff - some items have one, and some up to 3 branches underway. Can such a scenario be addressed by pathauto?

# Answer
> 1 votes
Well, I'm really surprised such important functionality hasn't been implemented in D7.
Here we go: too much talk, not so much work.
In short: currently there's no token for dynamic taxonomy depth like `termpath` in D6.

# Answer
> 0 votes
I'm also quite miffed by this missing bit of critical functionality.

A workaround you could use for now is to use the token \[node:field-section:url:relative\] (replace "section" with the name of the taxonomy term that you've made a field on your node content type).

But then you must do a second step and that is to turn OFF the default handling of slashes in strings in the Pathauto \> Settings tab. It is all the way at the bottom under "Punctuation". You must change the dropdown setting to "No action (do not replace)".

Although this should get you where you want, it is risky, as it now opens up the possibility of 404 errors if there is an unencoded slash in the title of a node or any other field that would find its way into your pretty URLs.

I'm also trying to get this quick and dirty module to work -- http://drupal.org/node/741914#comment-5025862 -- but thus far it is only outputting the deepest term in the URL and not the entire hierarchical chain. I'll keep you posted if I do get it to work.

# Answer
> 0 votes
Since this question was asked a lot of things changed and this is possible now so for anybody that stumbles upon this question the way to go is using the "join-path" token for the full url including the current term

```
[term:parents:join-path]/[term:name]

```

It will output all the parent's names no matter if you have 1,2 or ..x making the depth dynamic.

---
Tags: 7, tokens, path-aliases
---


title: How node_access tag works with query?

text:
# Question
Title: How node_access tag works with query?
I'm not able to understand the use and role of the node\_access tag. I used the Node View permission module to restrict the access to the *article* content type for anonymous users.

Now I have created an auto-complete search box that searches node titles. This is the query I used.

```
$query = \Drupal::entityquery('node');
$query->condition('title', trim($search));
$query->condition('status', 1);
$query->addTag('node_access');
$nids = $query->execute();
$nodes = Node::loadMultiple($nids);

```

I don't want this search box to search titles that belong to the *article* content type, and I used the *node\_access* tag.

Will this tag serves my purpose here or is there any other approach to achieve the same?

# Answer
No, it will not serve for the purpose you have in mind. It checks the currently logged-in user has view access to the node, which means that if the currently logged-in user is the user #1, it will see every node, including the ones that aren't published, and independently from the content type.

As @Neograph734 says, you should not use that tag to filter out nodes basing on their content type. If you want to filter the result by content type, you should use a line like `$query->condition('type', 'article');` to built the query.
> 2 votes

---
Tags: 8, nodes
---


title: Drupal 8 Commerce views filter Price

text:
# Question
Title: Drupal 8 Commerce views filter Price
I have a views with products and I want to sow products with price \>= 100. I add Relationship 'Product variation'. All of my products are with one variation, so there shouldn't have duplication. When I add Filter "Price" in popup no configuration options and filter no additional setting like in other numeric fields.

How I can get this filter to set \>=?

# Answer
> 0 votes
My solution for this is in little custom module here, in short: added new filter "Commerce Product variation Price", of course views should have relationship "Product variation".

Module contain also taxonomy term with depth filter (contextual is not work) for commerce\_product, the same thing like on node.

---
Tags: 8, commerce, views
---