# Question
Title: How to save a date value in a node programatically?
I'm saving a node programmatically. Every thing works fine except the date field which gives me an error.

My date field in cck is in Date-time format as I need to capture both and the widget type is date popup.

```
$node = new StdClass();

//creating a bare node
$node->created = $value['article_creation_date'];
$node->type = 'media';
//giving it type
$node->uid = $user->uid;
$node->status = 1;

//give it a published status

$node->title = $value['article_title'];
//gives title

node_object_prepare($node);
$node->field_publish_date[LANGUAGE_NONE][]['value'] = date("d/m/Y H:i:s ", 1289799000);
$node->field_publish_date[LANGUAGE_NONE][]['timezone'] = "Asia/Kolkata";
$node->field_publish_date[LANGUAGE_NONE][]['timezone_db'] = "Asia/Kolkata";
$node->field_publish_date[LANGUAGE_NONE][]['date_type'] = "datetime";

node_save($node);

```

This is the error:

> Error is: \`PDOException: SQLSTATE\[22007\]: Invalid datetime format: 1292 Incorrect datetime value: '15/11/2010 11:00:00 ' for column 'field\_date\_value' at row 1: INSERT INTO {field\_data\_field\_date} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_date\_value) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 3 \[:db\_insert\_placeholder\_2\] =\> 3 \[:db\_insert\_placeholder\_3\] =\> article \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> 15/11/2010 11:00:00 ) in field\_sql\_storage\_field\_storage\_write() (line 514 of '

I'm open to suggestions. Thanks!

# Answer
> 3 votes
You are making 4 different arrays and putting part of the date config in each array.

Each time you put `[]` you are making a new array.

What you want is:

```
$node->field_publish_date[LANGUAGE_NONE][] = array(
  'value' => date("d/m/Y H:i:s ", 1289799000),
  'timezone' => "Asia/Kolkata",
  'timezone_db' => "Asia/Kolkata",
  'value' => "datetime",
);

```

# Answer
> 0 votes
for me this solved the issue:

```
  $node->field_publish_date[LANGUAGE_NONE][]['value'] = date("d-m-Y H:i:s ", 1289799000); I just changed the date format.

```

Thanks for help.

---
Tags: nodes, hooks, datetime
---


title: Creating a filter of content types?

text:
# Question
Title: Creating a filter of content types?
I have a content type called college facilities. This displays ALL the college facilities that are added. I would like to create more content types called:

* Services
* Food
* College Supplies
* Other

I was wondering is it possible to create a drop down filter on the college facilities page so that if a user select all then all of them are displayed or Food then only food content types are displayed?

This is what I would like it to look like with ALL being pre selected. Is this possible? I apologize I am very new to drupal and Im using Drupal 7.

# Answer
If I understand correctly, you need to create Views page where you add exposed filter on the content types.

This is how you create an exposed filter https://www.youtube.com/watch?v=2Yk6rre3vi8

If that is unclear for you, I will make a screenshot.

Regards,

Oleg
> 2 votes

---
Tags: 7, views
---


title: Cannot activate parameter cors.config

text:
# Question
Title: Cannot activate parameter cors.config
I am using the **RESTful Web Services** that is included in core of Drupal 8.2.7. I need to activate CORS to be able to call the API from another domain.

I put this configuration in this file: "core/lib/Drupal/Core/core.services.yml" but it didn't work. I don't have the header *Access-Control-Allow-Origin*.

```
cors.config:
  enabled: true
  allowedHeaders: ['*']
  allowedMethods: ['*']
  allowedOrigins: ['*']
  exposedHeaders: true
  maxAge: true
  supportsCredentials: true

```

I found also this configuration is present in "sites/default/default.services.yml".

What is the proper way to configure CORS ?

# Answer
To override container variables you have to enable this line in `sites/default/settings.php` (is enabled by default)

```
$settings['container_yamls'][] = __DIR__ . '/services.yml';

```

and then copy `sites/default/default.services.yml` to `sites/default/services.yml`.

Now you can configure the variables in `services.yml`.
> 2 votes

---
Tags: 8, configuration
---


# Question
Title: list all used & unused views in site or panels, as a site audit
Is there a way to list all used & unused views in site? or in panels? (as fields are listed in /admin/reports/fields). I have some complex sites with a lot of views (pages, blocks, entityreference, panes, etc.) and panels pages. While building a site we all make views to test something, then clone view, etc. at the end i may have a lot of unused views, i'm trying to delete unused views to clean site, all my views are rendered inside a panel page. I run D7, but i think this will be helpfull also in D8

# Answer
> 2 votes
I think this module might help you.

https://www.drupal.org/project/views\_maintenance

*Module provides administrative page with detailed information about each display use cases and its status for each enabled view. It helps you to detect unused and broken displays to modify them or completely remove from your site.*

Regards,

Oleg

---
Tags: views, panels
---


# Question
Title: stylesheets-remove in .info.yml file doesn't work
I'm following Drupal 8 Theming Fundamentals, Part 1 to create a Drupal 8 theme. They say that default CSS styles are added by modules in the core as shown in the following screenshot.

>

Those CSS files can be removed from the .info.yml theme file using code similar to the following one.

```
stylesheets-remove:
  - core/assets/vendor/normalize-css/normalize.css
  - core/modules/system/css/system.module.css
  - core/modules/system/css/system.theme.css
  - core/modules/views/css/views.module.css

```

I've done that, but nothing happens (it's says the same). Plus, when I watch to the source of the page, I see the following.

>

The CSS styles are aggregrated. What is happening here? How can I fix this?

# Answer
> 7 votes
I was also having trouble with this and I found a change record which states:

> "In cases where a Drupal core asset is being removed (for example, a CSS file in jQuery UI) the full file path is needed. In cases where the file is part of a library that belongs to a module or theme, a token can be used. Note that when using the token it needs to be quoted because @ is a reserved indicator in YAML."

In my case I was trying to remove the eu\_cookie\_compliance.css file from the eu\_cookie\_compliance module. To do this I used the following in mytheme.info.yml:

```
stylesheets-remove:
  - '@eu_cookie_compliance/css/eu_cookie_compliance.css'

```

To remove module (even core ones) provided css you could try something like:

```
'@system/css/system.module.css'

```

To answer your second question about the aggregation of css files, you can switch off aggregation by visiting `/admin/config/development/performance` and unchecking "Aggregate and compress CSS files"

---
Tags: 8, theming
---


title: Form Submit without module

text:
# Question
Title: Form Submit without module
Is a module required to submit a form ? I get a standard form from our designer and try to send it as follow:

```
<form action="/kontakt" class="sky-form" method="POST" name="kontakt">
  ...
  <input type="submit" class="btn btn-u btn-u-lg" value="Nachricht absenden">
</form>

```

I have tried different function calls without success

```
MYTHEME_form_submit(array &$form, FormStateInterface $form_state)
contact_form(array &$form, FormStateInterface $form_state)
contact_form_submit(array &$form, FormStateInterface $form_state)
MYTHEME_contact_form_submit(array &$form, FormStateInterface $form_state)
...

```

i have to say, that i am a beginner in Drupal 8, so help is very appreciated.

thank you.

# Answer
Two ways to approach this.

One way is to use the Webform module. If this is just a simple contact form, you can get this done with Webform in five minutes.

The second way is create a custom module that implements a route, Form class and related methods. Wouldn't take an intermediate long, but a beginner should try Webform first.

You cannot simply paste form HTML into a twig file and expect it do anything. Drupal is ignorant to its existence and therefore no hooks will work, as you already saw.

https://www.drupal.org/project/webform
> 1 votes

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


# Question
Title: What is the purpose of _services_controller_execute_preserve_user_switch_anonymous()?
I have been having a problem persisting the authenticated session after a successful registration using Services 7.x.3.11 in Drupal 7.

I've sort of solved that issue by commenting out the call to `_services_controller_execute_preserve_user_switch_anonymous()` inside of *sites\all\modules\services\includes\services.runtime.inc*. The file's comments read:

> As authentication methods should authenticate user themselves changing global $user variable we preserve incoming session authenticated user and his session so changes made by authentication do not interfere.

Aside the grammer, I do not understand the purpose of this method nor how Services authentication works and integrates with Drupal's core. Can anyone explain why this is necessary for Services to honor Drupal's roles and permissions.

# Answer
> 1 votes
The user register action (which is essentially just an alias of the user.create resource) executes the user register form. Doing so affects the global `$user` object, which overwrites any existing `$user` object. Other resources related to the user will also do the same thing.

This is undesirable, as it replaces the global user that you're using to authenticate against the endpoint. So the Services module saves your session before executing any callbacks, and restores it afterwards. This ensures the integrity of the original session.

I think the misunderstanding is simply that you're expecting the user register resource to automatically invalidate the current session, and replace it with a session for the newly created user. I can't see anything in the code that would suggest that's supposed to happen, and it makes sense that it wouldn't...

Imagine your app needed to register 10 users in a batch; if your session was invalidated each time you made a call to user.register, and replaced with a session for the new user, you'd have to logout and potentially re-authenticate before each subsequent registration. Not an ideal situation to be in.

# Answer
> 0 votes
I know this is old but just for the record in case someone else came to the same problem, Drupal Services are preserving the user session who originally requested the service resource and restoring it after fulfilling the requested service resource. This is intentionally desired as long as the resource used will not login or log out the customers in drupal site.

An exception to this is dealing with other login provider like LDAP or Social Login through services, Thus the added service definition need to authenticate the user and log him in so he can resume using the other services.

Solution to this is to include the "login" word in your service call back definition, as this will grantee that drupal will keep the session that you created and consider it as valid session.

**An example is as below for service definition**

```
$definition['my_module']['actions']['connect'] = array(
'help' => 'Services login using my_module_logic ',
  // Please note that login is mandatory in the name of call back
  // this will allow drupal to preserve the session that we get here
  // check _services_controller_execute_preserve_user_switch_anonymous
'callback' => 'services_my_module_login',
'args' => array(
 array(
    'name' => 'provider',
    'type' => 'string',
    'description' => 'A valid my_module login provider ',
    'source' => 'data',
    'optional' => FALSE,
  ),
),
'access callback' => 'services_access_menu',
);

```

You can get more information by checking the code here

```
_services_controller_execute_restore_user

_services_controller_execute_preserve_user_switch_anonymous

```

---
Tags: 7, services
---


# Question
Title: Enter order level data in Drupal Commerce
I am running a store, that allows anonymous users to purchase product.

I would like to collect a small amount of "order-level" data from a users before they make a purchase. An example would be whether or not the purchaser is a member of our organization.

The question is where best to do this? I do not want to include a field in each line item, because this is order level and not line item level data.

I could add a field to a checkout pane, but I actually want to use the information I'm gathering to determine what kind of checkout information to collect. People who are already members of our organization, for example, would have to enter much less information because we already have it.

# Answer
> 0 votes
I think I have figured out how to do this, at least conceptually.

What I need to do is expose the order level data in a form without a Submit button. Then, use javascript to populate hidden fields in the real Add to Cart form with data that the purchaser enters in the exposed order level data fields.

Then use hook\_form\_alter to redirect the Add to Cart button to my own php routine where I will use the \[now filled in\] hidden fields in the Add to Cart form to populate order entity properties. \[I might also be able to do this in my commerce\_mycheckout\_submit routine.\]

Whether my skills, and the exigencies of project deadlines will let me get this down now remains to be seen, but I think I now have a way forward.

---
Tags: commerce
---


# Question
Title: Using a View in a tooltip for an image map hover link
I have a **imagemap** with various tags, it works well in my Drupal instance, I can click on the various areas to get to my pages.

Now I want to hover one area and display a **tooltip** with information inside (example: if I hover France, I will have a tooltip showing little information on Paris, with a picture). I will find myself how to do it by the way if you can't help with it - that's just my final goal.

Following various sites tutorials, I made a View with contextual filters in order to display the city content by passing an argument to the view. It works like a charm. I also rewrote the output to use tokens for display

I have actually no idea **how to display my View in a tooltip** \- and searching didn't help me either ...

Modules I am using :

* Views
* Tipsy (or qTip or else, I don't have any preferences, as long as it works)

# Answer
You can easily use `replacement patterns` to achieve something similar. Add the fields you would want as the view and then in replacement pattern you can `render a views block` or even customize the display via `html`.
> 0 votes

---
Tags: 7, views, tooltips
---


title: Query returns no result

text:
# Question
Title: Query returns no result
I want to select all the nodes from the database where a specific taxonomy term is defined (in Drupal 7).

I already know the taxonomy term (IDs). So I want to use a join to get the latest node thats created for that taxonomy.

For the moment I have this:

```
$query = db_select("node","n");
$query->join('taxonomy_index', 'i', 'n.nid = i.nid');
$query->fields("n",array('nid','title','created'))
        ->orderby("created","desc")
        ->range(0,1);

drupal_set_message($id);

$query->where('(i.tid = :type)', array(':type' => $id));

drupal_set_message($query);

$query->execute();

$array = array();
foreach ($query as $record) {
    $array[] = $record;
}
return $array;

```

This is (some of ) the output of the messages:

Id: 1

> SELECT n.nid AS nid, n.title AS title, n.created AS created FROM {node} n INNER JOIN {taxonomy\_index} i ON n.nid = i.nid WHERE ((i.tid = :type)) ORDER BY created DESC LIMIT 1 OFFSET 0

If I use the following string directly in PHPMYADMIN, I have results:

> SELECT n.nid AS nid, n.title AS title, n.created AS created FROM drpl\_node n INNER JOIN drpl\_taxonomy\_index i ON n.nid = i.nid WHERE ((i.tid = 1)) ORDER BY created DESC LIMIT 1 OFFSET 0

The result directly in Drupal returns an empty array.. What am I doing wrong?

# Answer
> 1 votes
Usually it's better if you use EntityFieldQuery instead of `db_select`. See EntityFieldQuery vs Db\_select()

From EntityFieldQuery use page:

> The EntityFieldQuery API lets you fetch information about entities (nodes, users, taxonomy terms et cetera) from Drupal without actually building SQL queries. EntityFieldQuery is a class that allows retrieval of a set of entities based on specified conditions. It allows finding of entities based on entity properties, field values, and other generic entity metadata. The syntax is really compact and easy to follow, as well. And, best of all, it's core Drupal; no additional modules are necessary to use it.

In your case:

```
$nodeQuery = new EntityFieldQuery();
$query = $nodeQuery->entityCondition('entity_type', 'node')
  // get only nodes that are 'published'
  ->propertyCondition('status', 1)
  // replace field_food_menu with field_TAXONOMY_NAME
  // replace 2 with the taxonomy ID (tid) you're wanting
  ->fieldCondition('YOUR_TAXONOMY_FIELD_NAME', 'tid', $SEARCHED_TID)
  // SOrt by creation date.
  ->propertyOrderBy('changed', 'DESC')
  // Retrieve only last item.
  ->range(0,1)
  // USe user 1 to query all nodes, not only those that current use can access.
  ->addMetaData('account', user_load(1));

// Get a list of nids that match given criteria (because if the use of range() a list of 1 elem, at most.
$result = $query->execute();

```

(Code it's not tested, probably you have to tweak it a little).

I should add that this method also checks if user is allowd to access to the nodes that returns. That's the reason for the last line, it makes all nodes available, not just those the current user can access. If you want to see only nodes for that user just remove that line.

---
Tags: nodes, database
---


title: Upstream cache clear issues

text:
# Question
Title: Upstream cache clear issues
I'm running into issues with caching on my Drupal 7 site, where it seems that users are receiving stale pages, despite not having "cache pages" or "cache blocks" settings enabled. There is no additional server-side caching enabled. I've cleared the cache via `drush cc all`, as well as clearing the cache through the UI.

After clearing the cache, and with js aggregation enabled, I've pulled up pages where I receive an old version of the js. With aggregation turned off, I get the new js, as expected. Turn aggregation back on and pull up the page in an incognito window, and I get the old js.

However, even with aggregation turned off, I've also seen in our logs that we're getting "Page not found" messages for expired, aggregated js files. This indicates to me that users are getting served pages with references to these old files, though I'm open to other possibilities.

The headers for our homepage include `Cache-Control: no-cache, must-revalidate` and an `Expires` value in the past. The headers for our main.js file include `Cache-Control: max-age=1209600`, an `ETag` value, and an `Expires` value set to 2 weeks from now. I thought that by clearing Drupal caches, there would be an update to the `ETag` value that would force users to download an updated asset. Our hosting support has suggested that the settings on these assets may be impacting the upstream cache (I'm assuming they mean the cache on the homepage, for example).

So it seems like there is page caching that's happening on some level. Since I don't have server-side caching or page / block caching set through Drupal, it seems that the cache settings on the assets are impacting page cache.

Any input or thoughts on troubleshooting would be appreciated!

UPDATE: In paying more attention to the details of aggregated files and cache clearing, today after clearing the cache, I had an updated, aggregated CSS for a while, and non-aggregated JS with a cache-busting `?examplestring` appended. In loading the site a few hours later, I'm being served the old aggregated CSS with the new non-aggregated JS. So it's got to be something wrong with how Drupal includes what it determines to be the newest version of the aggregated files.

# Answer
> 0 votes
I'm not familiar with the term "upstream caching / caches." I'm assuming it has something to do with edge caching... which I definitely suggest you look into; regardless of host service. I've seen many odd occurrences because of edge caching.

Also try any of the following:

check file permissions for the ability for your web server to write the JS/CSS that it's generating. Look in your sites/default/files or site/\[site\]/files directory for css and js subdirectories. Check the permissions on those two AND delete the .css, .css.gz, .js, and .js.gz files in them. truncate (with discretion - backup your database) all tables with a \_cache at the end of them.

---
Tags: caching, css-js-aggregation
---


title: Cannot retrieve value on client side

text:
# Question
Title: Cannot retrieve value on client side
I use this PHP snippet on the server side after a submission of a webform:

```
function mymodule_webform_submission_insert($node, $submission) {
 // $node will give you the node id of your webform
 // $submission will give you the id of your data which you inserted in web form
 $sid = $submission->sid ? $submission->sid : FALSE;
 if($sid){
   dsm($sid); // yes, the sid is shown after a submission
   if(!isset($_SESSION['mymodule'])){
     $_SESSION['mymodule'] = array();
   }
   $_SESSION['mymodule']['webform_id'] = $sid;
   drupal_add_js(array('mymodule' => array('webform_id' => $_SESSION['mymodule']['webform_id'])), 'setting');
 }
}

```

... and then on the client side I have ths JS snippet:

```
(function ($) {

     Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

                var sid = Drupal.settings.mymodule.webform_id;
                console.log('the submission ID is: '+ sid);
        }
    };

}(jQuery, Drupal));

```

.. but the variable sid is "undefined" in the console (after a submission) no matter what I try to do. Can anyone see what I am doing wrong?

# Answer
> 2 votes
The problem here appears to be the location in which you are calling drupal\_add\_js(). The way Drupal works with form submissions, is that after processing is complete, it does a redirect to the page again. This way when you click back (or forward) in the browser, you don't get the message asking you if you want to post the data again. You are adding your JS in a processing function, which happens before the redirect, so it is getting lost after the redirect.

You'll need to find a different location to put your call to drupal\_add\_js(), that comes after the redirect. It should go in the same place where you are loading your script in the first place.

---
Tags: 7, javascript, webforms
---


# Question
Title: How do I sort nodes in node_view_multiple()?
I created a block with node teasers loaded with `node_view_multiple($nodes)`.

Now I want to order the results:

* By Node ID
* By the time is was created/updated
* Random

Of course I can order them with PHP array functions, but is there a Drupal specific way to do it?

# Answer
The best way I can think of to do this is using EntityFieldQuery:

```
$query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'your_type')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('nid', 'ASC')
    ->propertyOrderBy('changed', 'DESC')
    ->addTag('random') //this gets the query passed through hook_query_alter
    ->execute();

```

And you will need hook\_query\_alter to do the random sort because EFQ doesn't do that natively

```
function icac_custom_query_random_alter(QueryAlterableInterface $query) {
  $query->orderRandom();
}

```

To get the nid's for node\_load\_multiple

```
$nids = array_keys($entities['node']);

```
> 0 votes

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


title: Filter not filtering

text:
# Question
Title: Filter not filtering
I have a field for which I used REWRITE RESULTS for a dropbox to turn 1 -\> yes, and turn 0 -\> no.

I want to add a filter to allow users to sort this field. When I create my sort, I get 1 // 0 as sorting options (rather than yes, no).

How do I get yes/no (which I had previously established in rewrite results) be what shows up for my sort of that field?

Thank you!

Tan

# Answer
> 0 votes
Is this a boolean field? If so, you should be able to use the Output format dropbox that appears when you click on the field. Yes/No is one of the choices. (I'm using Views in Drupal 8--I don't know whether it's the same for Drupal 7.)

---
Tags: views
---


# Question
Title: Set pager none in a view programmatically
I want set pager none in a view programmatically, but I can not find a way to do it, the object "$view" does not seem to exhibit a way

# Answer
> 0 votes
I believe you can do something like:

```
$view->display_handler->options['pager']['type'] = 'none';

```

in your function. This calls the view's display handler to set the pager type option to 'none'.

---
Tags: views, 8
---


# Question
Title: Is there a solution which could keep information about actions and updating of data on the site?
For example, there is a site. And it's necessary to create a news feed on the site. Approximately, like on the Facebook.

Thas is, if someone added a new forum topic, article or page of another content type, this event should be added to the news feed. Also if someone changed any page, information about it also should be added to the news feed. Also, if someone commented or liked something. Also if a new used added to the site. And so on.

I need to clarify, is there a solution, which could perform it ? And this solution should have opportunity to customize, which data should be added to the news feed and which data shouldn't. And I need to have possibility to customize its output design.

I don't want to try to use the dblog module for it. Moreover, the data on the dblog module can be deleted.

P.S. In my opinion, it's not possible to perform it using the views module only. Because views doesn't allow to use different types of entity, such as nodes, comments, users and so on in the same view. Therefore, I see the way to put it together using some entity, which keeps information about actions and which can be outputed using views.

# Answer
By using the Message module (which already has a beta version for D8), you can create your own custom "*Events logging*" (to register things that happened in a site).

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

The Message module is an amazing module, though there is not a lot of documentation about it. It is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and (only for D7 for now, not yet for D8) Rules.

# Additional info

For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation. And/or checkout the video introduction "Your Drupal site can talk" (if you want you can fast forward to about 03:30 where it really starts).
> 2 votes

---
Tags: 8
---


# Question
Title: Changing node values directly to database exhibits erratic behaviour
I needed to create a new field for each node in my website that would have as its value a concat of two existing fields.

I firstly inserted the new rows in the newly created field table, and then updated each of the rows with he corresponding information. But when I check on the browser in the edit page of several nodes some of them have the correct value inside the field while others have that field blank. The strange part is that there is no apparent difference in the database between the nodes with a value in the field and those that have it blank.

After investigating the issue I copied all the table to its correspondent revision table, leaving revision\_id as 0. This didn't solve the problem.

I know I'm not supposed to directly modify the database like this but it has half-worked and I was wondering if there's a way to execute a method or a module so all nodes will have their field filled, or if I should erase all contents of the table and use db\_update() or node\_save() to do the job.

thanks in advance

# Answer
> 1 votes
The safest way would be adding field data and saving it with node\_save. If you write it to the database, you have to also duplicate the record to the revision table of that field and keep track of vids. The API will just do this for you. You do not (should not) write field data via db\_insert or other functions like it. Doing so may irreparably harm your database.

To apply the data retroactively, I would advise that you create a batch op via Batch API. Query up all nodes, create batch operations, and in your batch callback, process the node and save it with node\_save.

There is a docs page on getting started with the Batch API.

Here is a blog post that demonstrates a basic batch job that is close to what you'd want to start out with. You'd want to populate the `$operations` array with node ids, and every time the batch callback is called, the node id is passed. Then you load the node with it, set the field, then save the node.

edit: tutorial author also provides a Drupal 8 version.

# Answer
> 0 votes
I had forgotten to fill the 'bundle' field. After it had the correct value all nodes have now the correct value in the newly created field. – Jaime Marcos del Ser

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


title: Cron removes dblog watchdog

text:
# Question
Title: Cron removes dblog watchdog
I set the cron to run every day.

I want to prevent the cron from deleting some of the watchdog table content.

But i didn't find a way to do it, i still want the cron to run for the search index.

How can i prevent the cron from deleting dblog (watchdog) informations only ?

# Answer
> 2 votes
What you can do easily is configure how many records are kept at /admin/config/development/logging, you can set it up to 1 million, which is quite a lot.

To disable it completely (which I would *not* recommend), you could use a module like ultimate cron, which allows to control how often the cron job of each module is called separately.

---
Tags: 8, cron
---


# Question
Title: AJAX auto on views (without clicking submit button)
I'm working on a view with exposed filters ; I want it to be reloaded when a select list (based on a taxonomy) has its value changed by an user. However, by default, AJAX in Views needs a click on the submit button : "Options such as paging, table sorting, and exposed filters will not initiate a page refresh."

How can we improve that ? Why does Views not offer an option for that, it's not just about perfs considerations ?

thanks !

# Answer
> 2 votes
If you enable AJAX in Views, you can also edit "Exposed Form Style" settings. There is a checkbox in there that says "Autosubmit" which will react whenever a user changes an exposed filter.

Edit: sorry, that is for Drupal 7. I see you have listed Drupal 8. For Drupal 8, this was removed and is now being added in an effort in the CTools module. You can see the updates here: https://www.drupal.org/node/2475595

According to this comment, you can apply the latest patch in that thread to CTools 8.x beta1 release, enable "CTools Views" module to add the functionality back in.

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


# Question
Title: hook_tokens_alter() not applying to [user:one-time-login-url] Token
I'm trying to alter the one time login token. I am implementing hook\_tokens\_alter to do this.

```
/**
 * Implements hook_tokens_alter
 * @param $replacements
 * @param $context
 */
function portalapi_tokens_alter(&$replacements,  $context){
  if(isset($context['data']['user'])){
    foreach($context['tokens'] as $name => $original){
      switch ($name) {
        case 'one-time-login-url':
          $timestamp = REQUEST_TIME;
          $token = user_pass_rehash($context['data']['user']->pass, $timestamp, $context['data']['user']->login, $context['data']['user']->uid);
          $resetpath = url(variable_get('portal_frontend_url').'/reset-password/'.$token.'-'.$timestamp);
          $replacements[$original] = $resetpath;
          break;
      }
    }
  }
}

```

Logging the $replacements array at the end of the function call shows the expected changes. However, the token output isn't altered when used (for example when sending password reset emails).

As a quick background here - We're implementing an entirely headless front end serviced by an API, we need to use a different domain in the one time login link and a different structure.

What am i missing?

# Answer
> 4 votes
You cannot alter it because that token is not returned from `user_tokens()`. You get that token only with code similar to the following one.

```
$text_with_tokens_replaced = token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));

```

The problem is that first the implementations of `hook_tokens_alter()` are called, then the callback passed to `token_replace()` is called. The effect is that every value you set for that token is then changed from the callback.

This is the code used from `token_replace()`.

```
  $replacements = array();
  foreach ($text_tokens as $type => $tokens) {
    $replacements += token_generate($type, $tokens, $data, $options);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }

```

`token_generate()` is the function invoking the token hooks (including the alter hooks).

```
  $replacements = module_invoke_all('tokens', $type, $tokens, $data, $options);

  // Allow other modules to alter the replacements.
  $context = array(
    'type' => $type,
    'tokens' => $tokens,
    'data' => $data,
    'options' => $options,
  );
  drupal_alter('tokens', $replacements, $context);

```

---
Tags: 7, users, tokens
---


title: Conditional Fields

text:
# Question
Title: Conditional Fields
I want to add specific number of fields depending on list(integer) field. For example, I have field named number that has 1,2,3,4, and 5 as data. So, when adding a content and the user chooses 3, then three fields that have list(text) field should pop up.

so, this is how the form should look at first.

```
         -
Number: |0|
         -

```

Then, when we choose 3, it will look like this.

```
         -
Number: |3|
         -
        ----------
Field1:|list field|
        ----------
        ----------
Field2:|list field|
        ----------
        ----------
Field3:|list field|
        ----------

```

Thank you.

# Answer
> 2 votes
Consider using the Conditional Fields module. Excerpt from its project page:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

---
Tags: 7, ajax
---


# Question
Title: Can I write two cron( hook_cron() ) in one module
I have a custom module abc\_xyz and i want to write two seperate cron for this module.

below is the code which i am trying but it is creating only one cron , with name abc\_xyz\_cron. it is not creating for zzz\_yyy\_cron

file name : abc\_xyz.module

```
abc_xyz_cron(){

}

zzz_yyy_cron(){

}

```

# Answer
> 1 votes
No. You can implement hooks once per module due to the namespacing of the hook (mymodule\_cron). However you can put conditions within the cron hook to do different things.

You might be looking for this instead: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_cron\_queue\_info/7.x

---
Tags: cron
---


title: One account shared by multiple sites

text:
# Question
Title: One account shared by multiple sites
I have two different domain names, e.g. www.exampleA.com and www.exampleB.com.

exampleA.com contain all the reading material.

exampleB.com contain practices or quiz.

Although they are installed at the same server, but different drupal sites.

Recently, I receive an instruction. User need to access both website by using same account ID and password. Once they login, they can read material and take quiz too. However, both domain name are still different due to two different company.

I had installed domain access module successfully, but it cant access to another website due the permission denied. It looks like they need me to point both websites to one drupal site. (or actually dun need?)

Any advice what should I do?

# Answer
> 1 votes
You can do it in two ways.

1. Single Sign On (SSO) (Please read https://www.drupal.org/node/2402397): Bit harder to setup but gives you full control and you can have separate drupal installation for each sites.
2. domain\_access: With domain access module, you will need to point both those domain to same drupal installation. Once you setup this module, you will see a checkbox in node add form to publish this content to (This is how the content will be displayed on each site). You can then edit your user account to have access to both sites and can login to both sites using same login details.

Please let me know if you have any questions.

---
Tags: 7
---


# Question
Title: Multiple Different AJAX Enabled Forms on the Same Page
I currently have a form that is being loaded by AJAX and is working perfectly. I now need to add a second form (Add Single Stat) to the same page via AJAX as well. The Add Single Stat form is being loaded to the page perfectly but when the AJAX callback is fired for the db\_selection select list, I get "An AJAX HTTP error occurred. HTTP Result Code: 200" AJAX error. I'm really not sure where this error being caused from and would like to find a fix to this issue.

The Add Single Stat Form is being built with the following code:

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

   $form['db_selection'] = array(
    '#title' => t('Data Location'),
    '#title_display' => 'invisible',
    '#type' => 'select',
    '#options' => array("" => "Select", "enrollmentdata" => "Student Enrollment Data", "summerenrollmentdata" => "Summer Enrollment Data"),
    '#prefix' => '<div id="db_selection" class="AddQueryFormElement">',
    '#suffix' => '</div>',
    '#ajax' => array(
        'callback' => 'Drupal\dashboard\Controller\DashboardController::SingleStatOnDBSelection',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => array(
            'type' => NULL,
            'message' => NULL,
            ),
        ),
   );
   $form['term_selection'] = array(
    '#title' => t('Select Term'),
    '#title_display' => 'invisible',
    '#type' => 'select',
    '#prefix' => '<div id="term_selection">',
    '#suffix' => '</div>'
   );
   $form['ss_id'] = array(
    '#title' => t('Single Stat ID'),
    '#type' => 'hidden',
    '#prefix' => '<div id="ss_id" class="AddQueryFormElement">',
    '#suffix' => '</div>',

   );
   return $form;
}

```

I am then loading The Add Single Stat Form to the page via this ajax callback:

```
public static function AddSingleStatToPanel(array &$form, FormStateInterface $form_state){
    $ajax_response = new AjaxResponse();

    //Generate a Unique ID for the single stat
    $SingleStatID = self::GenerateRandomID(15, 'single_stat_info', 'single_stat_id');

    //Add The "Add Single Stat" To the correct DIV
    $AddSingleStat = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddSingleStat');
    self::SetUniqueAddSingleStatFormDivIDs($AddSingleStat, $SingleStatID, TRUE);
    $ajax_response->addCommand(new AppendCommand('#AddSingleStatForm_'.$SingleStatID, $AddSingleStat));

    return $ajax_response;
}

```

I handle updating the form to contain unique element id values as well as unique ids for the divs surrounding the form elements in this function:

```
private function SetUniqueAddSingleStatFormDivIDs(&$FormRenderArray, $SingleStatID, $HideFields = TRUE){
    $FormFields = array('term_selection', 'ss_id');

    $FormRenderArray['db_selection']['#prefix'] = '<div id="db_selection_'.$SingleStatID.'" class="AddQueryFormElement">';

    foreach($FormFields as $FormField){
        //Set Each DIV's ID to the Form Field ID_SingleStatID
        if($HideFields || $FormField == 'chart_type'){
            $FormRenderArray[$FormField]['#prefix'] = '<div id="'.$FormField.'_'.$SingleStatID.'" class="hide" style="display:none" >';
        } else {
            $FormRenderArray[$FormField]['#prefix'] = '<div id="'.$FormField.'_'.$SingleStatID.'" class="AddQueryFormElement">';
        }
    }

    $FormRenderArray['ss_id']['#value'] = $SingleStatID;
    $FormRenderArray['#attributes'] = array('id' => array('ss_'.$SingleStatID));

}

```

Inside of the dashboard controller I have the AJAX callback that I would like to be called when the user changes an option in the db\_selection select list.I have reduced the code here to just a simple JS alert.

```
public static function SingleStatOnDBSelection(array &$form, FormStateInterface $form_state){

    $ajax_response = new AjaxResponse();

    $ajax_response->addCommand(new AlertCommand('It Works!'));

    return $ajax_response;
}

```

Update: I have done a little more debugging and the only way I can make this form work correctly is if I pass the form's render array to twig file and load it that way. The form doesn't seem work at when using AJAX to loads the form's HTML.

# Answer
> 0 votes
I believe your problem is here:

```
$SingleStatID = self::GenerateRandomID(15, 'single_stat_info', 'single_stat_id');

//Add The "Add Single Stat" To the correct DIV
$AddSingleStat = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddSingleStat');
self::SetUniqueAddSingleStatFormDivIDs($AddSingleStat, $SingleStatID, TRUE);

```

You are altering the form in SetUniqueAddSingleStatFormDivIDs(), after it has already been generated by the formbuilder. You cannot alter forms in Drupal after they have been generated. If you want to make alterations to the form, it needs to happen in hook\_form\_alter() or one of its variants.

---
Tags: 8, forms, ajax
---


# Question
Title: What's the best way to add a form in a node template?
I already have a node created with some custom fields, I would like to show a specific form in the detail page of the node that i created (using the ***node.tpl.php*** file)

Why? because I need to use some values of the node to custom parts of that form

What's the cleanest way to do this?

# Answer
> 2 votes
The best way to do it is to create a variable for your template in hook\_preprocess\_node():

```
function hook_preprocess_node(&$vars)
{
  $form = drupal_get_form('form_name');
  $vars['my_form'] = render($form);
}

```

Now you can drop the form anywhere in your template as the variable `$my_form`

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


# Question
Title: How do I specify an image reference in a Drupal 8 REST POST request body?
We have a content-type that includes a field of type Image. There is also an image file that has been uploaded to Drupal.

We are trying to add new content via a Drupal 8 REST POST. A new node is successfully created when the POST finishes, but the image field is never set. Here is what we are trying:

POST to: http:///entity/node?\_format=hal\_json
The normal 4 headers are set
POST Body:

```
{
    "_links": {
    "type": {
      "href": "http://localhost:8087/rest/type/node/product"
    }
  },
    "title": [{"value":"ProductC"}],
    "field_description": [{"value":"ProductC Description"}],
    "field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],
    "field_product_name": [{"value":"ProductCName"}],
    "field_product_n": [{"value":"prodC"}]
}

```

Any pointers on how to construct the "field\_product\_image" line in the payload to link the image to new content node?
Thanks

# Answer
> I tried again with just the image ID, and it worked perfectly. Thanks very much!

To elaborate...

After the image file has been created in Drupal, and you have the File ID you'll be ready to create/update Nodes. Instead of setting the `src` value on the image field you just need to set the `target_id` value.

Change this:

```
"field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],

```

To something like this:

```
"field_product_image": [{"target_id": 123}],

```

If you're using JavaScript this would typically be accomplished with 2 async calls. The first call would POST the binary file data to Drupal (or base 64 encoded string) to obtain the File ID, the second call (which takes places in the "success" callback of the first call) would then be used to create/update the node's image field with the new File ID.

The following d.o issue is an important one to follow and is very much related to the Question: https://www.drupal.org/node/1927648
> 2 votes

---
Tags: media, 8
---


# Question
Title: Field twig template : override HTML output
Still converting my D6 theme to D8 and I need to override the HTML output for a custom field in a node twig template. After some readings, I don't find an example for this. My field contain files and I want them to display in a HTML list instead of a div + span. So I created a file named field--field-fichier-joint.html.twig and added inside the code from this post , but I get a WSOD. This is my actually code:

```
{% extends "@stable/field/field.html.twig" %}

{# Create classes array #}
{% set classes = [] %}

{# BEM inspired class syntax: https://en.bem.info/
   Enable this code if you would like field classes like "article__tags", where article is the content type and field_tags is the field name.
{% set classes = classes|merge([
  bundle ~ '__' ~ field_name|replace({'field_' : ''})|clean_class
]) %}
#}

{% set attributes = attributes.addClass(classes) %}

{#
  Ensures that the visually hidden option for field labels works correctly.
  @todo: Remove when https://www.drupal.org/node/2779919 is resolved.
#}
{% set title_attributes = title_attributes.addClass(label_display == 'visually_hidden' ? 'visually-hidden') %}
<ul>
  {% for item in items %}
      <li>{{ item.content }}</li>
  {% endfor %}
</ul>

```

If someone can help me. Thanks

EDIT: 4k4 solution work fine but I need to add some classes and I saw a very smart solution but I need help to use it. This is here

EDIT2: adding classes work but how can specify which one to apply to an element ? Then when I want to add some flexibility to the code with this:

```
{# Définition des variables et classes #}
{%
  set classes = classes ?: [
    'field',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class
  ]
%}
{% set wrapper_element = wrapper_element ?: 'ul' %}

{% set element = element ?: 'li' %}

{# Mise en forme sortie HTML #}
<{{ wrapper_element }}{{ attributes.addClass(classes) }}>
  {% for item in items %}
      <{{ element }}>{{ item.content }}</{{ element }}>
  {% endfor %}
</{{ wrapper_element }}>

```

I get Multiple items like this, why ?:

```
< Un fichier joint pour test Autre fichier test > Un fichier joint pour test Un fichier joint pour test Autre fichier test > < Un fichier joint pour test Autre fichier test > Autre fichier test Un fichier joint pour test Autre fichier test >

```

2- Adding classes I want to add classes to my HTML output, in particular, the odd/even and I found this code but only odd class is applied:

```
{%
  set li_classes =  classes ?: [
    'field__li',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class,
    'ligne__' ~ cycle(['odd', 'even'], loop.index0),
  ]
%}

```

then, my `li` classes inherit from `ul` classes, how can I avoid this ? This code work better but the cycle loop result is out of the class..

```
 <li {{ attributes.addClass(li_classes) }}{{ cycle(['odd', 'even'], loop.index0)}}>{{ item.content }}</li>

```

render:

```
<li class="field__ul field--fichier-joint field__li ligne__odd" odd="">
</li>
<li class="field__ul field--fichier-joint field__li ligne__odd" even="">
</li>

```

EDIT: **the Final code**

```
{# Les classes a jouter à la liste UL #}
{%
  set ul_classes = classes ?: [
    'field__ul',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class
  ]
%}

{# Mise en forme HTML #}
<ul {{ attributes.addClass(ul_classes) }}>
  {% for item in items %}
      {# Les classes a jouter aux lignes LI #}
{%
  set li_classes =  classes ?: [
    'field__li',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class,
    'ligne__' ~ cycle(['odd', 'even'], loop.index0),
    ]
%}
      <li {{ item.attributes.addClass(li_classes) }}>{{ item.content }}</li>
  {% endfor %}
</ul>

```

# Answer
You only need the twig content between `<ul> ... </ul>`. The variables you set are not used anywhere. And you don't need to extend the field template from the base theme to override it. Only if you want to replace twig blocks.

**field--field-fichier-joint.html.twig**

```
{%
  set classes = [
    'class1',
    'class2',
  ]
%}

<ul{{ attributes.addClass(classes) }}>
  {% for item in items %}
      {% set zebra = cycle(['odd', 'even'], loop.index0) %}
      <li{{ item.attributes.addClass(zebra) }}">{{ item.content }}</li>
  {% endfor %}
</ul>

```

If you still get an WSOD enable error reporting to see in which file and line number the error occurs.
> 1 votes

---
Tags: theming, 8, entities
---


title: Drupal query fields

text:
# Question
Title: Drupal query fields
I have to implement the following SQL query in Drupal.

```
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

```

In my case, it may be something like this.

```
query->fields('n', array('nid', 'type',1 as 'sort_order'));

```

Can anyone help?

# Answer
> 1 votes
You can use addExpression method, which is unfortunately not chainable. The snippet that would make it work is the following.

```
$query = db_select('Table1', 't1')
  ->fields('t1', array('col1', 'col2');
  ->condition('col1', 0,'=')
$expression= $query->addExpression('ABC', 'col3');
$query->execute()
  ->fetchAssoc();

```

For more information on expressions, here is the official documentation: https://www.drupal.org/docs/7/api/database-api/dynamic-queries/expressions

---
Tags: database
---


title: How to create views tabs in D8?

text:
# Question
Title: How to create views tabs in D8?
I can't get views tabs to work in D8, following the exact UI procedure that does work in D7.

To be more precise, in D8 at /mypage I see no tabs at all, and at /mypage/tab2 and /mypage/tab3 I do see tabs "tab2" and tab3" but no "MyDefaultTab".

In D7, I see all 3 tabs when viewing any of the 3 URLs.

The following procedure works to create a Views page with tabs in D7 on simplytest.me, but does not work for D8 beta 15:

* Manage \> Structure \> Views \> Add new view
* View name = "Myview"; Show "Content" of type "all"; save and edit.
* Add page display; name="MyPage"; path = "mypage"; menu = "Normal menu entry" with menutitle ="MyPage" and parent="" (its default value) and weight=0;
* Add page display; name="MyDefaultTab"; path="mypage/defaulttab"; menu = "Default menu tab" with menutitle ="DefaultTab" and parent menu item ="Already exists";
* Add page display; name="tab2"; path="mypage/tab2"; menu="Menu tab" with menutitle="Tab2" and parent ="" (its default value) and weight=0.
* Add page display; name="tab3"; path="mypage/tab3"; menu="Menu tab" with menutitle="Tab3" and parent ="" (its default value) and weight=0.

Is this a D8 bug, or am I missing something?

Things I have tried (all made no difference, good or bad):

* Selecting "MyPage" (the non default but sensible seeming value) in the "parent" drop down for tab2 and tab3 (there are more menu options available in D8 than D7).
* Selecting "Normal menu item" instead of "Already exists" for the parent menu item of the default tab.
* Configuration \> Performance \> Clear All Caches

Any suggestions?

# Answer
> 18 votes
I have just created a views page with tabs. Following are the instructions. Add a views display of type page

1. Set its path to "/test" Then its menu option: Select "Default menu tab" and on next screen select "Already exist" under the "parent menu item".
2. Then adds another page display set its path to "test/tab1" and in its menu option: select "Menu tab" and save.

Visit the "/test" page and both tabs appear. Hope it may help you.

# Answer
> 1 votes
If you want your tabs displayed **/tabsparent/tab1**, **/tabsparent/tab2**, etc.., without **/tabsparent** default tab, please visit https://www.drupal.org/node/2693069#comment-12025897 page.

Just import configuration files on the link with ready to use view and see the difference.

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


# Question
Title: Drupal 7 Views, Nested User > Content views filter by exposed date
I have a nested View. The outer view is a list of users, and that view has a field which includes a content View of everything that user has created. I have chosen to expose the date of that inner view in the hopes I can have an exposed filter on the outer view to control them. Ideally, I'd choose a month and year in the main view and see how much content, if any, each user has created in the last month.

Since the outer view is not a content view, I can't choose a date filter and hook that into the inner view fields. And I need to show all users regardless of whether or not they have content, so I can't go to a Content \> Content nested view. Is there a date filter that's independent of content type that I could choose to inherit the exposed filter from the inner view, or that I could use to send a contextual filter to the inner view?

# Answer
In the outer view, add a relation Via this relation add the field filters (for example - field\_date) In the outer view field which references the inner view you can pass arguments -\> field\_date.

In the inner view -\> add contextual filters, which will be field\_date.

I hope this gives you some direction.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to display products without selling them (or using the typical ecommerce modules)?
I am working on a project with drupal 7. My drupal experience is limited and Im a bit stuck on how to achieve a good structure.

The site will have products like wine, sherries and spirits. Each of these product types will have subcategories. (example: like red / white wine) Within these subcategories there will be certain brands of wines.

Since the website is focussing only on displaying the products and not selling them, I really do not want to use any ecommerce software, or modules.

Preferably I would like the products to be a content type. There is a little catch to it. All categories, so in the examples above; wines, sherries, spirits BUT ALSO red / white wines should have a description and a image.

Can anyone shed some light on how to create this in drupal 7. I have searched a lot but I'm not sure what the right approach would be. Thanks!

# Answer
The easiest way to achieve this without using "commerce" modules are taxonomy and vocabularies, using the Entity Reference Module.

A simple workflow to achieve this would be:

1).Create the corresponding **Vocabulary** with the desired **term structure** from admin/structure/taxonomy/add, for example:

* Wine
* + Red
* + - Brand #1 etc.

2). Create The **Content Type** with the desired Fields

3). In the content type, add an "Entity Reference" Field, assigning it to the **vocabulary**

4). Create your products (Add content)

5). Create **Views** to customize the display of each page depending on the term level (using filters)
> 0 votes

---
Tags: 7
---


title: How do I use API versioning?

text:
# Question
Title: How do I use API versioning?
I'm using the Services module to produce a REST API. According to the official documentation, there is a way to version services resources. I believe version here means supplying a single API (e.g. `example.com/api`) and allowing clients to specify which version they want per resource with headers.

So I think that means that these two requests would return different results, despite living at the same URL:

Version 1.0:

```
POST /api/v1/system/set_variable HTTP/1.1
Host: example.com
Accept: application/json
Content-Type: application/json

```

Version 1.2:

```
POST /api/v1/system/set_variable HTTP/1.1
Host: example.com
Accept: application/json
Content-Type: application/json
services_system_set_variable_version: 1.2

```

I cannot make this work for the life of me. Here are the steps I took:

1. Enabled the system/set\_variable service
2. Added the following code to mymodule.module (cribbed directly from services.versions.api.php)

.

```
function _system_resource_set_variable_update_1_1() {
  $new_set = array(
    'help' => 'Create a node with an nid test',
  );
  return $new_set;
}

function _system_resource_set_variable_update_1_2() {
  $new_set = array(
    'help' => 'Create a node with an nid optional prams.',
    'args' => array(
      array(
        'name' => 'name',
        'optional' => TRUE,
        'source' => array('data' => 'name'),
        'description' => t('The name of the variable to set.'),
        'type' => 'string',
      ),
      array(
        'name' => 'value',
        'optional' => TRUE,
        'source' => array('data' => 'value'),
        'description' => t('The value to set.'),
        'type' => 'string',
      ),
    ),
  );
  return $new_set;
}

```
3. Cleared cache
4. Attempted to use the system/set\_variable service with postman.
5. Saw that the system/set\_variable service was working
6. Attempted to use the system/set\_variable service without arguments, per `_system_resource_set_variable_update_1_2`
7. Saw that arguments were still required

So what am I doing wrong here? I'm pretty sure I followed all the instructions.

# Answer
> 0 votes
Quote from services.versions.api.php

> For clients that want to request a specific version they need to pass a certain header
>
> * services\_RESOURCE\_METHOD\_version = version
> * as an example, services\_system\_set\_variable\_version = 1.2
> * @see ServicesVersionTests for code examples

Make sure to use set acceptable Content-Type.

> ```
> Content-Type: application/x-www-form-urlencoded
>
> ```

```
GET /v1/status HTTP/1.1
Content-Type: application/x-www-form-urlencoded
API-KEY: AAAAAAA
TOKEN: VVVVVVV
services_status_index_version: 1.1
Host: local.mywebsite.com
Connection: close
User-Agent: Paw/3.0.16 (Macintosh; OS X/10.11.6) GCDHTTPRequest

```

---
Tags: 7, services
---


# Question
Title: Create menu link for authenticated user programatically
So here is what I've tried in custom module dir I've created `module.links.menu.yml` file here is code. I want to just for authenticated user beside Content link have my custom link to access Webform. Also, do I need routing file to?

```
description: "Link descr"
menu_name: main
parent: system.admin
url: 'internal:/admin/structure/webform'
  route_name: entity.webform.collection
title: "Webforms"
weight: -48
requirements:
      _role: 'authenticated'

```

# Answer
> 1 votes
Given that you are simply moving a link of an *existing* route in a drupal menu, you are probably better off using the more simple hook\_menu\_links\_discovered\_alter(). A custom link/route is probably a bit of overkill.

But, presuming you do want to go the way you are in your example, you would need to have both a `my_module.routing.yml` and `my_module.links.menu.yml`

In the menu links file you might have something like:

```
my_module.hello_admin_user:
  title: 'Hello Admin User'
  description: 'See a Hello Admin User Message'
  parent: system.admin_config_development
  route_name: my_module.hello_user
  weight: 100

```

and in the routing file you might have:

```
my_module.hello_user:
  path: '/hello-user'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::helloUser'
    _title_callback: 'Hello Admin User'
  requirements:
    _permission: 'access content'
    _role: 'authenticated'
  options:
    _admin_route: TRUE

```

You've got a bit of a mix going in your example. Note that route names and links names need to be unique across the drupal system. Using your module name as the start is a convention but not required.

---
Tags: 8, routes
---


# Question
Title: Possible to have variables in migration configuration?
We are running a continuous migration (using migrate\_plus) from a JSON API which supports `last_modified_since` as a query parameter. I would like to run this job every hour, and use the time of the previous run as parameter.

What would be the best way to achieve this? I tried tried overriding the variable by adding to the `$config` array in settings.php, but that is probably not even supposed to work.

# Answer
Yes you can! However, depending on the plugin you are using, it might be picky about what you put *in* the variable. Here are two examples of variables being used in a migration config:

**A file import**

```
source:

  plugin: csv
  track_changes: true
  path: 'public://migration/csv/image_download.csv'
  header_row_count: 1
  keys:
    - image

  fields:
    image: 'Image'
    media_name: 'Media name'

  constants:
    uri_file: 'public://photos'

process:
  uri_file:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/uri_file
        - media_name

  uid:
    plugin: default_value
    default_value: 1

  filename: display_name

  uri:
    plugin: download
    source:
      - image
      - '@uri_file'

```

In the above, both `constants/uri_file` established in the "source" step of the migration, and `uri_file` passed as `@uri_file` to the download plugin in "process" step are variables.

The documentation for the migrate\_plus process plugin "merge" has another good example:

```
source:
     plugin: d7_node
   process:
     temp_body:
       plugin: iterator
       source: field_section
       process:
         target_id:
           plugin: migration
           migration: field_collection_field_section_to_paragraph
           source: value
     temp_images:
       plugin: iterator
       source: field_image
       process
         target_id:
           plugin: migration
           migration: image_entities_to_paragraph
           source: fid
     paragraphs_field:
       plugin: merge
       source:
         - @temp_body
         - @temp_images
   destination:
     plugin: 'entity:node'

```

In both these example, the vars are used in arrays. That's just what the plugin expects, not something inherent to using variables.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: How do I use a template file for preparing HTML message body for emails?
I want to use a template file for preparing the email message body using the table tag, and putting the submitted form data by user in table rows. I have implemented `hook_mail()` with the following code.

```
function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      $message['body'][] = $params['message'];
      break;
   }
}

```

I created a template file (get\_price/templates/mail-to-eberhard.html.twig), but the message body is not using my template file.

How do I make Drupal 8 use my template file?

# Answer
So here is the answer: Inside the hook theme function of your module use this code

```
function get_price_theme() {
  return [
    'mail_to_eberhard' => array (
        'template' => 'mail-to-eberhard',  // TWIG File
        'variables' => array('submitted_data'=>[]),
    ),
  ];
}

```

where variables is the array of parameter you want to send to the template file. Now create a template file named as mail-to-eberhard.html.twig inside your modules template folder. Then inside the hook\_mail() alter function use this code.

```
function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      //$message['subject'] = t('Article created: @title', array('@title' => $params['node_title']), $options);
      // Render the template to HTML
      // Set up email template
      $body_data = array (
         '#theme' => 'mail_to_eberhard',
         '#submitted_data' => $params['message']
      );
      //$message['body']['#theme'] = 'mail_to_eberhard';
      $message['body'][] = \Drupal::service('renderer')->render($body_data);
      break;
  }
}

```

now inside you template file you can use the array variables like this

```
You have received one new message from the Get Price Tab.<br/><br/>
<b>Full Name</b> : {{ submitted_data['user_full_name'] }}<br/>
<b>Email</b> : {{ submitted_data['user_email'] }}<br/>
<b>Phone</b> : {{ submitted_data['user_number'] }}<br/>
<b>State</b> : {{ submitted_data['user_state'] }}<br/>
<b>Product SKU</b> : {{ submitted_data['product_sku'] }}<br/>
<b>Product URL</b> : <a href='{{ submitted_data['product_url'] }}'>{{ submitted_data['product_url'] }}</a>
<br/><b>Message</b> : {{ submitted_data['user_message'] }`

```
> 7 votes

---
Tags: theming, emails
---


title: empty drupal commerce cart with a url?

text:
# Question
Title: empty drupal commerce cart with a url?
Is it possible to empty the cart with drupal commerce by visiting a url?

/cart/empty

Trying to create a test case for selenium

# Answer
> 13 votes
The code would look something like this:

```
function MYMODULE_menu() {
  $items['cart/empty'] = array(
    'title' => 'Empty Cart',
    'access arguments' => array('access content'), // or whatever permission you want
    'page callback' => 'MYMODULE_empty_cart',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_empty_cart() {
  global $user;
  // Load the order and empty the cart
  $order = commerce_cart_order_load($user->uid);
  commerce_cart_order_empty($order);

  // As this page won't display anything you need to redirect somewhere
  drupal_goto('some/page');
}

```

# Answer
> 1 votes
You could define a URL with a callback function in which you just programmatically clear the cart's content.

# Answer
> 0 votes
I know this is an old thread, but there is now a module for this see Commerce Empty Cart Paths. This module allows site administrators to define multiple paths, and when a user visits a non-declared page, their shopping cart is emptied.

# Answer
> 0 votes
As suggested, try Commerce Empty Cart Paths module.

> It allows site administrators to define multiple paths, and when a user visits a non-declared page, their shopping cart is emptied.
>
> Usage:
>
> 1. Download and enable the module.
> 2. Go to admin/commerce/config/empty-cart-paths and enter any additional paths. checkout, checkout/*, cart and cart/* are declared by default.

Or combert's sandbox: Commerce Clear Cart module which simply adds a page that when visited will empty the current users Commerce cart. It also adds a link to that page to the Commerce cart view.

# Answer
> 0 votes
I hope this helps someone having the same issue... I installed Path Rules https://www.drupal.org/project/pathrules. From there create a custom rule... 1. Event -\>Drupal is initializing 2. check path cart/empty 3. Actions: Remove all products from an order 4. goto Parameter: URL: \[site:url\]

---
Tags: 7, commerce
---


# Question
Title: Import xml with Feeds from a folder outside site directory
I need to import data from multiple xml files. my site is in **/var/www/sites/automationstats** and the folder with the data is in subfolders of **/var/lib/jenkins**

If I use as directory in the import **/var/lib**, I get this error message: Directory needs to be a valid URI.

By the way, that folder (/var/lib) has owner and group **jenkins**. My first idea was to set that folder in the file system settings as private and then use **private://** as URI but it says the folder is not writable.

So, is it possible to read from outside my site file structure or I have to get the files inside?

# Answer
> 0 votes
yes you were right the correct way is to add in file system configuration (/admin/config/media/file-system) a private file system path that you need "*/var/lib/jenkins*", and then use it in your feed fetcher with prefix **private://**.

Please if it is possible move yor files form /var/lib to a user subfolder to avoid security problems.

---
Tags: feeds
---


# Question
Title: How can I get the content type name inside the hook_form_BASE_FORM_ID_alter() hook?
I need to obtain the content type name inside an implementation of the `hook_form_BASE_FORM_ID_alter()` hook for the node edit/add form to made some validations.

I can't find any node object reference using `kint()` to access to the `$node->getType()` value.

I need to do a validation like this:

```
if ($node->getType() == 'article') {
...
}

```

So, how can I get the content type name inside the `hook_form_BASE_FORM_ID_alter()` hook?

# Answer
> 7 votes
You can get the node from the form object.

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

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function yourmodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /* @var \Drupal\node\NodeInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if (!$node->getType() == 'article') {
    // ....
  }
}

```

Note that `getEntity()` doesn't exist on `\Drupal\Core\Form\FormInterface`, which is why it doesn't show up as a method in an IDE. It only exists on `\Drupal\Core\Entity\EntityFormInterface`, you can add an explicit instance of for that.

# Answer
> 1 votes
The only way that I found using the `kint()` output with the help of the Search Kint module to find the content type name is this:

```
$form['#process'][1][0]->getTargetBundle()

```

Is working, but is not the best way to obtain the value.

```
if ($form['#process'][1][0]->getTargetBundle() == 'article') {
 ...
}

```

---
Tags: 8, forms
---


# Question
Title: How to update drupal (with composer) and not update to the latest major drupal release
not very familiar with composer yet

I run `composer update` on a dev version (thank GOD) but from 8.2.6 drupal was updated to 8.3.0 but some functionality was broken due to the upgrade ... how can I safely run `composer update` and not upgrade to latest drupal ... or is there some other command I should run instead ?

I understand that I probably have to change the composer.json to do it but I don't quite know what it is that it I need to include in it

Any help would be appeciated

this doc article don't quite explain such a thing

**UPDATE**

I run the command from eyal `composer require drupal/drupal:8.2.*` but creates problem and site was unusable after that (received 500 error)

```
giorgos@glaptop:~/websites/domain.com$ composer require drupal/drupal:8.2.*
./composer.json has been updated
No patches supplied.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/drupal (dev-8.2.x 2125663)  Cloning 2125663da0 from cache
Writing lock file
Generating autoload files

Installation failed, reverting ./composer.json to its original content.

  [RuntimeException]
  Could not scan for classes inside "docroot/core/lib/Drupal.php" which does not appear to be a file nor a folder

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

```

I had to run `composer update` and now with the 8.3.1 version of drupal the `composer update` run smoothly. I just needed to run `drush up rules-8.x-3.x-dev` after that since there was a problem with rules and 8.3.1

**EDIT** Anyone knows why my question received -2 ? (was I downvoted ? what is the reason ?)

# Answer
> 1 votes
It depends on the version you specify in the `composer.json` file. You can specify broad versioning, or exact version, and composer will adhere to that.

---
Tags: 8, updating, composer
---


title: Add the date of the order after the ID

text:
# Question
Title: Add the date of the order after the ID
how do I add the order date after the order ID ?

Here is the contents of my file "commerce\_order--commerce\_order--pdf.tpl.php" :

```
<?php

/**
 * @file
 * Template for invoiced orders.
 */

?>

<?php
//The code to get payment type

$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}
?>

<div class="invoice-invoiced">
  <div class="header">
    <img src="<?php print $content['invoice_logo']['#value']; ?>"/>
    <div class="invoice-header">
        <p><?php print render($content['invoice_header']); ?></p>
    </div>
  </div>

  <hr/>

  <div class="customer-billing"><?php print render($content['commerce_customer_billing']); ?></div>
  <div class="customer-shipping"><?php print render($content['commerce_customer_shipping']); ?></div>
  <div class="invoice-number"><?php print render($content['order_number']); ?></div>
  <div class="invoice-header-date"><?php print render($content['invoice_header_date']); ?></div>
  <div class="order-id"><?php print render($content['order_id']); ?></div>
  <div class="invoice-header-date"><?php print render($content['invoice_header_date']); ?></div>

  <div class="line-items">
    <div class="line-items-view"><?php print render($content['commerce_line_items']); ?></div>
    <div class="order-total"><?php print render($content['commerce_order_total']); ?></div>
  </div>
  <div class="invoice-text"><?php print render($content['invoice_text']); ?></div>
  <?php print("Mode de règlement : " .$payment_method); ?>

  <div class="invoice-footer"><?php print render($content['invoice_footer']); ?></div>
</div>

```

# Answer
> 1 votes
Well, since you already loaded the order, I guess you could do:

```
<div class="order-id">
  <?php print render($content['order_id']); ?>
  <?php print format_date($order->created, 'custom', 'd-m-Y'); ?>
</div>

```

---
Tags: 7, commerce
---


# Question
Title: How to get user permissions for the role Administrator?
I need to get permissions for all user roles, which are used. The code looks something like this:

```
$anonymous = Role::load('anonymous');
$anonymousPermissions = $anonymous->getPermissions();

```

The code for anonymous (and also for authenticated) returns an array of permissions, but the same code for administrator returns null:

```
$administrator = Role::load('administrator');

```

How can I get permissions for the role Administrator? (The machine name of role Administrator is administrator and also in the database is nothing suspicious.)

---

I have tried also:

```
$administratorPermissions = user_role_permissions(['administrator']);

```

It returns:

```
array(1) {
    ["administrator"] =>
        array(0) {
    }
}

```

---

If I try:

```
$roles = Role::loadMultiple();
foreach ($roles as $role => $rolesObj) {
    $role_list[$role] = $rolesObj->get('label');
}
print_r($role_list);

```

Then I get:

```
Array
(
    [anonymous] => Anonymous user
    [authenticated] => Authenticated user
)

```

# Answer
> 5 votes
See the Role::getPermissions() method code:

```
  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

```

So, if the user has all permissions the returned value is an empty array.

Why? I really don't know and I can't find the answer, maybe other user knows Why Role::getPermissions() method return an empty array for admin users?.

The good news is that you can get all the Administrator permission with this code:

```
array_keys(\Drupal::service('user.permissions')->getPermissions());

```

Test this code (You'll need the Devel module to use `dpm()`):

```
$administrator = Role::load('administrator');
if($administrator->isAdmin()) {
  dpm(array_keys(\Drupal::service('user.permissions')->getPermissions()));
}

```

---
Tags: 8, users
---


# Question
Title: Aggregated CSS & JS files revert to old version
I'm troubleshooting an odd issue on my Drupal 7 site where it seems that old versions of our aggregated CSS & JS files are used some amount of time after a cache clear. How this is playing out is that I'll make some update to our CSS or JS, then clear the cache via `drush cc all` (I've also used the UI to manually clear the cache). I get an updated version of the CSS / JS for a while. At some point (typically I've noticed it a few hours later), the page serves the old version of the aggregated file.

I've pulled mysqldumps of the site, and can see that the values in the `variable` table for `drupal_css_cache_files`, for example, contain a reference to the old aggregate rather than the new.

I found this issue on drupal.org (and I'm not sure it's exactly the same thing), but one of the suggestions involves deleting all files in `<root>/cache`, which I don't have. Would this be the same as deleting the files in `sites/default/files/js/`?

Another part of this that may or may not be related is that I see in my site logs "page not found" requests for old aggregated files that don't exist anymore.

I'm hitting a wall in troubleshooting, since it seems like the actual database value for the new aggregated file is being reverted. Anyone know what might be going on here?

# Answer
> 0 votes
Couple things to look into. An external cache (Varnish/Boost/etc...) could be referencing the old files. This issue will help with the variable\_set's with css/js aggregation https://www.drupal.org/node/886488#comment-9668583. Also see this issue: https://www.drupal.org/node/1014086. I'd guess it's an external caching issue based off of what your describing but I can't say for sure due to the flaws in core that have still not been fixed.

In all honesty advagg will fix these issue for you. Drupal.org uses it due to issues with deployments https://www.drupal.org/node/1412130 https://www.drupal.org/node/2446971

---
Tags: caching, css-js-aggregation
---


# Question
Title: What does -1 signify in system.schema_version?
The Drupal 7 {system} table has a schema\_version column. Its default value is -1 as indicated by the `DESCRIBE system;` MySQL command.

Sometimes an update function won't run if the module's schema\_version is -1. For instance, I have site that migrated from Drupal 6 to Drupal 7 quite some time ago. Recently I found that a database column that should have been introduced by `honeypot_update_7100()` never ran. I'm not sure whether or not the version of honeypot at the time of the migration contained that function. After changing the schema\_version to 0, update.php ran that update and the missing column was introduced. See PDOException Column not found: 1054 Unknown column 'hostname' for similar stories.

Is -1 treated specially? Do all -1's potentially need to change to 0 for their update functions to run?

# Answer
> 4 votes
-1 means the module is not installed. Updates are only run on installed modules, which is why any update in a module with a status of -1 will not run. If the module is coded properly, when the module is installed, it will be installed in the same level as if all updates had been applied, as updates are used to bring the database in line with the current definition of it in hook\_schema().

---
Tags: database, updating
---


# Question
Title: How to get the files of a particular page?
I am new to Drupal, I want to edit the code of a particular page, let's say, www.mywebsite.com/login. Where can I find the code for the particular page/node. In static websites I could just navigate to the url and get the page, however, I am not sure how to get to the specific piece of code which is initiated when I go to the URL.

Please help with some direction or tutorial.

# Answer
> 1 votes
The way drupal works, is these requests are sent to the index.php where they are parsed, the database queried, the content fetched and built for the page. Aside from images and files embedded, none of the files are accessed directly (I guess except for theme files as well).

What do you want to do?

---

Based on your comment, \- you should probably implement `hook_page_bottom` \- Then get the path with this, Get the current path alias or path? \- Add an if based on the above path \- add your JS to the `page_bottom`array

Documentation, https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook\_page\_bottom/8.2.x

# Answer
> 0 votes
here's a good link:

JavaScript API overview

And also check out the links at the bottom of that page.

And if you want to understand the render process:

The Drupal 8 render pipeline

---
Tags: nodes
---


title: Get username in Twig

text:
# Question
Title: Get username in Twig
How would I go about making the currently logged in user's username available as a Twig variable in yamlform.html.twig? (From the YAML Form module.) I know there's something to do with the **themename.theme** PHP file, but I know next to nothing about the Drupal API and all of my copy-pasting hook\_preprocess functions has turned up nil.

# Answer
```
function THEMENAME_preprocess(&$variables, $hook, $info) {
  $variables['current_user_name'] = $variables['user']->getDisplayName();
}

```

in twig template:

```
{{current_user_name}}

```

With this solution current user name available in all twig template.
> 3 votes

---
Tags: theming, hooks
---


# Question
Title: Twig field collection theme get field id
I am trying to get the field ID of of a field collection item being rendered in a field collection theme twig file: `field-collection-item--field-name.html.twig.`

I am able to render content using `{{content.field_name}}` but I need a unique identifier to create an anchor link. I can see an id is available using kint(item) but cant seem to figure out the proper syntax.

Any help would be greatly appreciated...

# Answer
> 1 votes
You can get The field collection item ID in field-collection-item.html.twig

```
{{ item['#field_collection_item'].id() }}

```

or you can get it from field-collection-item--field-name.html.twig, or other field template of field collection item.

```
{{ element['#items'].getEntity().id() }}

```

You can find these functions under Available Methods Tab when you printing out variables from twig template. You can use public methods.

---
Tags: theming, 8, entities
---


# Question
Title: How to set Panel to homepage when setting the panel's path as homepage on Configuration > Site Information doesn't work?
I have created a panel for my home page and set its path to /home. I have changed the directory of the front page in Admin \> Configuration \> Site Information to mysite.com/home. Still, when I visit mysite.com/home, the custom panel saved to path /home doesn't populate.

I've made sure I'm saving correctly (rather than just updating) and have also cleared my cache.

Any ideas how else I might be able to fix?

Thanks in advance!

# Answer
I dont know what programes interferring the home page redirect. However, you can try variable\_set('site\_frontpage', 'front-page-panel-url');

http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable\_set
> 0 votes

# Answer
fix the issue instead of hacking your backend. Usually a module needs an update, or you didn't use the right type of panel. Did you setup a node template in Panels by enabling ...

System page\_manager node\_view Node template /node/%node In code ( Enable )

You have to go into Pages under the Structure menu. Then after you create the template you can create a page with the box that says "make this panel my front page".
> 0 votes

---
Tags: panels
---


# Question
Title: Why Role::getPermissions() method return an empty array for admin users?
Searching the answer for How to get user permissions for the role Administrator? I found that if you try to get the permissions for the admin user you will get an empty array.

From Role::getPermissions():

```
  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

```

But if the admin user have all the permissions why Drupal just return an empty array?

# Answer
That is because a role that is marked with *is\_admin* (which from the UI is possible for just a single role) has all the permissions. Consider it as an extension of the user #1 concept; the difference is that there is just a user #1, but there could be many users assigned to the role marked as *is\_admin*.
In fact, the code does the same it does for the user #1: It explicitly checks for the role being *is\_admin*. So, returning an array of permissions that will never be used doesn't make sense. See `Role::hasPermission()`.

```
  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

```

Similar code is present in other functions/methods, for example Role::revokePermission().

```
  if ($this->isAdmin()) {
    return $this;
  }
  $this->permissions = array_diff($this->permissions, array($permission));
  return $this;

```

As for why Drupal uses that code, it is because from the UI it is possible to change which role is marked as *is\_admin*, including one for which permissions were already set. Once it is marked *is\_admin*, the permissions explicitly set can be ignored, but they are kept, just in case you change from the UI the role marked as *is\_admin*. In such case, you would not want to set again the permissions you set for the old *is\_admin* role.
> 7 votes

---
Tags: 8, users
---


# Question
Title: Problem with adding custom CSS and JavaScript to a theme
I know it is not new case, but I'm still stack about add custom CSS styles and JavaScript. I followed the official web's tutorial but nothing happened (not showing like trees and not showing error too although debug twig was enabled).

I want to add JavaScript and CSS to show structural trees. In `global-styling` and `global-js` all I need is defined completely, for example jQuery and Bootstrap from Drupal itself. Can you spot errors in the code?

### mytheme.libraries.yml

```
treeview:
  version: 1.x
  css:
    theme:
      css/treeview.css: {}

  js:
    js/treeview.js: {}

```

### mytheme.info.yml

```
libraries:
  - mytheme/global-styling
  - mytheme/global-js
  - mytheme/treeview

```

### twig-template.html.twig

```
{{ attach_library('mytheme/treeview') }} // I attach customed files(css & js) direct into twig-template.html.twig

```

### Enable debugging Twig template

```
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
        debug: true

```

I tried this treeview without Drupal. It works perfectly.

# Answer
Add css and js in the global-styling:

```
global-styling:
  version: VERSION
  css:
    base:
      css/treeview.css: {}
  js:
    js/treeview.js: {}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Using drush when database and web server are separate
I am having trouble using drush on server setups where the web (111.11.11.1) and database (222.22.22.2) servers are separate.

```
drush sql-connect

```

gives me the correct output of

```
mysql --user=mysite_user --password=abcdef12345 --database=mysite --host=222.22.22.2

```

If i type this into the console of the web server it connects me to the mysql on the database server correctly, however...

Running

```
drush cc all --debug

```

results in the following messages

```
Executing: mysql --defaults-extra-file=/tmp/drush_j4KBOf --database=mysite --host=222.22.22.2 --silent  < /tmp/drush_xpMPoI
  ERROR 1045 (28000): Access denied for user 'root'@'111.11.11.1' (using password: YES)

```

It looks like drush is trying to connect using a different set of credentials and failing, i cannot find any my.conf where db credentials are hardcoded.

# Answer
The user name is taken from root's `.my.cnf` file (normally located in `/root/.my.cnf`. Either remove the user line from that file, or run Drush as another user than root (which might not have a `.my.cnf` file.)

Added: The relevant part of the MySQL documentation:

> If multiple instances of a given option are found, the last instance takes precedence, with one exception: For mysqld, the first instance of the `--user` option is used as a security precaution, to prevent a user specified in an option file from being overridden on the command line.
> 1 votes

---
Tags: drush
---


# Question
Title: How exactly does module_load_include() load a file into the calling script?
Here is the code:

```
function module_load_include($type, $module, $name = NULL) {
  static $files = array();

  if (!isset($name)) {
    $name = $module;
  }

  $key = $type . ':' . $module . ':' . $name;
  if (isset($files[$key])) {
    return $files[$key];
  }

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      $files[$key] = $file;
      return $file;
    }
    else {
      $files[$key] = FALSE;
    }
  }
  return FALSE;
}

```

`module_load_include()` is just a function that calls `require_once` from within itself to load an external file. But it seems to me that `require_once` should load external file into `module_load_include()` and subsequently, this loaded file should disappear when `module_load_include()` goes out of scope. Somehow "magically" the external file is successfully loaded into the calling script(eg: a page callback function) that calls `module_load_include()`. I don't understand how this is achieved.

# Answer
> 1 votes
It sounds like you're getting confused on scope. There's no "file scope" in PHP. The `include`/`require` statements are pretty much the equivalent of dropping the code within the scope that it's called.

Per PHP's docs on the `include` statement:

> When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

If definitions in the included file are global. For example:

* `global $base_url;`
* `define('MYMODULE_CONST', 123);`
* `function mymodule_function() { }`

Then they are global until the script execution ends.

If definition is not global (e.g. `$var1 = 'var1 value';`) then it only remains within the scope of the `include` statement.

---
Tags: 7
---


# Question
Title: Custom entity types with multiple value properties
I'm creating a custom entity type, that has the following base field (defined in a class that extends ContentEntityBase)

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields['recipient_id'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Recipient(s)'))
    ->setDescription(t('The recipient(s)'))
    ->setSetting('target_type', 'user')
    ->setSetting('handler', 'default')
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
    ->setDisplayOptions('view', array(
      'label' => 'above',
      'type' => 'entity_reference_label',
      'weight' => -3,
    ))
    ->setDisplayOptions('form', array(
      'type' => 'entity_reference_autocomplete',
      'settings' => array(
        'match_operator' => 'CONTAINS',
        'size' => 60,
        'autocomplete_type' => 'tags',
        'placeholder' => '',
      ),
      'weight' => -3,
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
}

```

I've set the field to have unlimited cardinality. I'm trying to create the getters and setters for this field, however I'm not finding any examples of entity types with multiple values.

I need to create the following getters and setters:

```
// Add a single recipient to the entity
public function setRecipient()
// retrieve all recipients for the entity
public function getRecipients()

```

Does anyone have an example of how to set up these functions to work with a multiple value field?

# Answer
> 4 votes
```
// Add a single recipient to the entity
public function setRecipient()

```

What now, add or set? If it is adding to the existing list, I'd recommend to name it addRecipient().

I'd also recommend to name the field recipients or so, to indicate that it has multiple values.

You can add an item to a field item list with `\Drupal\Core\TypedData\ListInterface::appendItem()`, for example $this-\>get('recipient\_id')-\>appendItem($recipient\_entity\_or\_id\_or\_value\_array)

To get all referenced entities, there is a referencedEntities() method on entity reference field item lists, or you can use a loop.

---
Tags: 8, entities
---


# Question
Title: Can recurring initial payment period be changed after purchase is made?
I've installed the drupal commerce framework and the Commerce recurring framework (it's awesome), and i've created a recurring product. That said, someone just made a purchase, and I realized that I accidentally set the initial period as 1 year (and it should be one month). I've since corrected it, but if someone has already purchased the recurring product, how can I change that period? Will it update for existing orders? If not, where can I go to change it for specific orders?

# Answer
> 0 votes
According to the official documentation

> **Recurring process**
>
> When an order containing a Recurring product is purchased for the first time for the current user, by default the module reacts on "Order is paid in full" event, **a Recurring entity will be created** associated with that product for the current order.
>
> On a cron event, the **recurring entities with past due dates are retrieved** and an order is created for each recurring entity associated with the recurring product and customer.
>
> Note: When this cron event runs it's the time to trigger the payments or use another technique to build a queue of payments.
>
> All this process is driven through Rules so most of it is modifiable

So from reading this, looks like all you gotta do is check the recurring entity that was created for that particular order and see if the due date is 1 month from now or if it's still 1 year from now. If the latter, then edit it and change the due date to 1 month from now.

---
Tags: 7, commerce
---


# Question
Title: Collapsable, grouped field in View (Bootstrap, D8)
I am setting up a view in Drupal 8, but am stuck on a problem. I'm using a table view, where some of the fields are grouped. These fields can have from 0 to maany values. Therefore, I would like to "collapse" them, showing only the first value unless you click to show them all.

I found a javascript that seemed to be just what I wanted ( https://jsfiddle.net/z0qvv7tk/11/ ), however, I can't seem to be able to utilize it. I loaded the script in and tried several things to get add the ul class to my list, including:

* Editing the tpl-files for view, both under my theme and on views directly. In hindsight I suspect I was editing the list-style view, and not the list for the fields in one of my attempts.
* Rewriting the fields - this also didn't yield any results since the field is grouped.
* Adding css-classes to the field - of course this didn't work, since I need to add it to the list, not the item.

I am using lists to show the grouped fields. The view can be found here. The field in question at the moment is the field for members, but I would like the same effect for some of the others eventually.

Since I couldn't get the script working, I started looking for modules. I tried Views Accordion, Views Fieldset, Views fieldsets among other, with none of them working as I intended.

After this I discovered that Bootstrap has various collapsable options, and I tried rewriting/editing the .tpl again - with no luck.

Can any one help me in the right direction? As long as it is collapsible, preferably showing the first value, I am open to any solution.

# Answer
I solved it using Bootstrap. I hid the field, then added it one more time. Then I rewrote the second field like this:

```
<a href="#{{ nid }}" class="btn btn-info" data-toggle="collapse">
Show members</a>
<div id="{{ nid }}" class="collapse">
{{ field_research_group_ext_members }}
{{ field_connected_user_names }}
</div>

```
> 0 votes

---
Tags: views, 8, entities
---