# Question
Title: drush sql-sync doesnt extract gzipped sql
I run the following command from a script:

```
drush -v sql-sync @tmp.stage @tmp.coe | tee ./sql-sync.log

```

My `@tmp.stage` server is Drush 7.0 and `@tmp.coe` servers is Drush 6.2.0

An SQL dumpfile is created locally rsynced to the destination server and attempted to be imported by mysql without first uncompressing. Is there a workaround? The source and destination servers have `gzip` installed.

**Log Output**

```
You will destroy data in server1/tmp and replace with data from 2016_tmp_mirror.
Do you really want to continue? (y/n): Include /var/www/2016/tmp/vendor/drush/     [notice]

Executing: mysql --defaults-extra-file=/tmp/drush_jUBS0A --database=2016_tmp_mirror --host=localhost --silent  < /tmp/drush_H19MvV
Calling system(mysqldump --defaults-extra-file=/tmp/drush_QRO7xg  2016_tmp_mirror --host=localhost --no-autocommit --single-transaction --opt -Q  | gzip -f > /home/dgurba/drush-backups/2016_tmp_mirror/20160407200242/2016_tmp_mirror_20160407_200242.sql.gz);
Include /var/www/2016/tmp/vendor/drush/         [notice]
You will destroy data from webuser@server1:/tmp/2016_tmp_mirror_20160407_200242.sql.gz and replace with data from /home/dgurba/drush-backups/2016_tmp_mirror/20160407200242/2016_tmp_mirror_20160407_200242.sql.gz
Do you really want to continue? (y/n): y
Calling system(rsync -e 'ssh -T' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --include="sites/mysite.foo.com/" --include="sites/all" --exclude="sites/*" --stats --progress --remove-source-files /home/dgurba/drush-backups/2016_tmp_mirror/20160407200242/2016_tmp_mirror_20160407_200242.sql.gz webuser@server1:/tmp/2016_tmp_mirror_20160407_200242.sql.gz);
sending incremental file list
2016_tmp_mirror_20160407_200242.sql.gz

         32,768   1%    0.00kB/s    0:00:00
      2,591,074 100%   26.52MB/s    0:00:00 (xfr#1, to-chk=0/1)
Number of files: 1 (reg: 1)
Number of created files: 1 (reg: 1)
Number of regular files transferred: 1
Total file size: 2,591,074 bytes
Total transferred file size: 2,591,074 bytes
Literal data: 2,591,074 bytes
Matched data: 0 bytes
File list size: 0
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 2,584,839
Total bytes received: 42

sent 2,584,839 bytes  received 42 bytes  469,978.36 bytes/sec
total size is 2,591,074  speedup is 1.00
Calling system(mysql --database=bar --host=localhost --user=foo --password='*****'  < /tmp/2016_tmp_mirror_20160407_200242.sql.gz);
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\8B

```

# Answer
In Drush 6, the sql-sync command on the source system composed `bash` commands, and executed them on the remote system as needed via ssh.

In Drush 7, the sql-sync command on the source system uses `drush_invoke_process` to operate on the remote system. Drush 6 did not support the gzip features that Drush 7's sql-sync command requires.

You don't specifically mention if the system you are running sql-sync on is Drush 7 or Drush 8 or something else, but Drush 8 is substantially similar to Drush 7 vis-a-vis sql-sync implementation.

You should be able to use gzip to send sql dumps to @tmp.coe, but only if you use Drush 6 on the source. Drush 6 is no longer supported, but I believe it also supported transfer between two remotes. You should therefore be able to install Drush 6 on your local system, and perhaps name it drush6 and use it only for this purpose.
> 0 votes

---
Tags: database, drush, importing-exporting
---


# Question
Title: Having issues upgrading from Drush 6.3.0 to 8.0.5
We have been successfully using Drush, latest version 6.3.0. In order to obtain Drupal 8 support, I am trying to upgrade to Drush 8.0.5.

First I located the 8.0.5.tar.gz file and tried getting success that way. It complains:

```
./drupal-cron.php.sh

```

> 20160407-204933 drush core-cron cron.php begin Unable to load autoload.php. Run `composer install` to fetch dependencies and write this file (http://docs.drush.org/en/master/install-alternative/). Or if you prefer, use the drush.phar which already has depdencies included (http://docs.drush.org/en/master/install). X-Powered-By: PHP/5.4.45 Content-type: text/html

So next I tried pulling down drush.phar as that appeared to have the dependencies built-in. Trying that version also did not seem to successfully execute Drupal cron:

```
./drupal-cron.php.sh

```

> 20160407-211633 drush core-cron cron.php begin
> X-Powered-By: PHP/5.4.45
> Content-type: text/html

We have been successfully running Drupal cron with Drush since our last update back in 2014 with this script:

```
#!/bin/bash
DATE=`/bin/date +%Y%m%d`
DATETIME=`/bin/date +%Y%m%d-%H%M%S`
LOGFILE=/kunden/homepages/35/d157794216/htdocs/reports/$DATE.${2}.drupal-cron.php.sh.log
export COLUMNS=132

echo $DATETIME drush core-cron cron.php begin | /usr/bin/tee -a $LOGFILE
/usr/bin/nice -n19 /usr/local/bin/php5.4 /kunden/homepages/35/d157794216/htdocs/drush/drush.php --root=$1 --uri=http://$2 --debug --nocolor core-cron 2>&1 | /usr/bin/tee -a $LOGFILE

```

And to try drush.phar I swapped out drush.phar for drush.php in the Bash script.

Suggestions how to get successfully upgrade to the latest version?

# Answer
It's not clear from your post how you are calling the phar, but you cannot call drush.php directly when using that variant. This technique (`php drush.php`) was recommended in Drush 3, but has been deprecated since Drush 4. The script you show above will work for calling cron, but will fail for commands that cause Drush to call itself.

If you want to use the .phar, make sure that the correct version of php is in your $PATH, and then call Drush directly.

Alternately, you could install `composer` and run `composer install` in the Drush directory after installing the .tar.gz file, or cloning from git. If you do this, set the DRUSH\_PHP environment variable to point at the php executable that you would like to use, and call the `drush` script (not `drush.php`).
> 1 votes

---
Tags: drush
---


title: How to chage the page suffix?

text:
# Question
Title: How to chage the page suffix?
My page is starting from 0,and I want to start with1. As follows:

Can implemented in Drupal?

# Answer
Yes. Sort of.

The **?page=X** query parameter in views pages is the offset from the SQL results (if you have the views admin section displaying generated SQL you can see this by the `OFFSET X` clause).

Hence, if you adjust your **Pager options** such that the **Offset** (normally 0) is set to opposite (e.g. -5) of the number in the **Items per Page** (e.g. 5) it will produce the effect of **/my-views-page?page=1** containing the first results of your query.

However, it will also produce the side effect of the first offset page (i.e. **/my-views-page** and **/my-views-page?page=0**) of having no results. You could probably mitigate this through some URL rewriting, but it's a bit of work for something that has very little value (how many people browse the web thinking about numbered results vs. index offsetting?).
> 2 votes

---
Tags: views
---


# Question
Title: Achievement Popup notification doesnt appear on cache page
I am using achievement module on site , it shows a popup notification when a particular achievement is reached . However due to caching (Authcache for authenticated user) , the popup doesn't appear .

The only way I could thought of is to prevent the site from grabbing the cached page ( from cache\_page) when the criteria for showing pop is satisfied .

Any pointers on how can it be done ?

Thanks , Murali

There is custom module which triggers the pop up :

```
   function geld_achievements_pks_response($user_id) {

   $current_count = achievements_storage_get('forum-node-count', $user_id) +      5;
   achievements_storage_set('forum-node-count', $current_count, $user_id);

   if ($current_count == 25) {
       achievements_unlocked('Level 1', $user_id);
       }

```

# Answer
Thanks everyone for helping on this issue . I finally got it working by a small hack . Authcache does'nt render page from cache if there are outstanding drupal messages . so when the condition for popup is met i , put drupal\_set\_message('!', warning) . The next page is avoided from cache to display the drupal message ( which I hide by css ) and the pop up . subsequently on clearance of messages the autcache begins fetching cache until the next condition of pop up is met .
> 0 votes

---
Tags: hooks, caching
---


# Question
Title: Views event listing by date with up/down infinite scroll
I have a content type called "**Event**" which contains a "**Date**" field. What I want to achive:

**1)** Create a view which can display 5 events sorted by "Date" and displayed as following:

* 2 events which are previous to the current date
* 1 event which is of current or the nearest date
* 2 events which are following current or the nearest date

**2)** When these things are ready I want to have a possibility to:

* **scroll up** and dynamically load 5 more "previous" events
* **scroll down** and dynamically load 5 more "following" events

I understand how to do it with 2 different views displays (one for current and upcoming events and a block before with past events), but the thing is that I need to create a page slider (where each fullscreen slide is one event) which can be slide both before and forward over all site events (there may be a lot of them, so i can't just load all events at once and need to do it dynamically when sliding over). Will be very thankful for any idea how to create such a display using one view.

# Answer
> 1 votes
You can achieve your requirement by following below steps.

1. Install Views Field View module.
2. Create first view of Event content type with 2 events which are previous to the current date
3. Create second view of Event content type with 2 events which are greater than current date.
4. Now create on third view with current date and into its header part add first view and into footer part add second view using Views Field View. Follow screenshot attached below

Regarding **scroll down** functionality install Views Load More module.

I don't know how to achieve **scroll up** functionality. It something like you have to write custom thing.

---
Tags: views, datetime
---


# Question
Title: How to add a description to the Goals used by the Goals module?
I'm using the Goals module in combination with Views. I'm now displaying all the Goals that were completed by a user on the profile pages in a table that contains the Goals' image and title.

Now, I'd like to explain a bit more what the user exactly achieved by adding an extra column with a description. Adding a direct description to the Goals would be a perfect solution, but as this isn't provided by the module's maintainers, I opened a feature request.

I know Drupal Answers isn't built to provide patches (although they're very welcome), so I'd like to ask whether there's perhaps another solution for my problem.

# Answer
This works by the module's design. I totally forgot that one can go to `Configuration/Goals/Goals/Manage fields` and add a text field there.
> 0 votes

# Answer
**Goals** used by the Goals module are implemented using fieldable entities. So you can customize goals by adding your own fields, such as:

* descriptions.
* images.
* links to external resources.
* etc.

Head over to its video tutorial, and have a look at what is shown starting from around 4:00 where you can see the typical tabs for Goals, such as:

* Manage Fields.
* Manage display.

For more details, refer to its Community Documentation also.

Disclosure: I'm the maintainer of this module.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to give users with role Role2 the right to edit only user accounts with role Role1
I need to make a user edit users that have a specific role. In fact we have two user roles here.

* Role1 -\> is able to edit a particular kind of node
* Role2 -\> is only able to administer users with the role "Role1".

My question: how to give users of Role2 access to edit only user accounts of Role1?

# Answer
You may want to try Administer Users by Role module.

> This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

One of the extra permissions that this module provides is

**Edit users with custom roles** \- *Allows editing of any authenticated user with the specified role.*
> 1 votes

# Answer
Have a look at the Group module which is like a "little brother" of Organic groups. It only started in D7 and with a D8 version in the pipeline. Personally I'm more and more considering/using it as a potential alternative for the Content Access module. And since it is all entity based, there are lots of ways it can be used in combination with the Rules module also.

Specific to your question here, I think what is going to help you a lot is the **Group member profiles** sub-module.

For way more details about this module, refer to its Community documentation pages, such as the Group HowTos subpage of it.

**Note**: Your question doesn't specify which version you are using, but this answer applies for both D7 and D8.
> 1 votes

---
Tags: users
---


# Question
Title: How to get archived events based on end date for a content type with a start date and end date field?
Create a content type Event with fields for Start date and End date. Validate the creation of events where Start date cannot be in the past and End date cannot be less than start date. Create a View where the Start date & End date are exposed filters and end date validated as in content creation page. The View should also filter expired events (i.e. Content with expired End date) and displayed in a similar view display named Archived Events

# Answer
> 1 votes
Archived events get based on an end date.

Go to view named `archived events`. Then click the end date exposed filter in FILTER CRITERIA. Check Filter type to expose is `single filter`. Then below operator drop down box choice `is less than`. Next drop down box choice `enter relative date`. Below now shows Relative date text box give `now`. Then click on Apply button.

---
Tags: views
---


# Question
Title: Drupal How to use regex or specific keywords as menu arguements
I have a drupal website, in which I wanted to add a new URL. This menu have two arguements which should be passed from the client side.

```
function campaign_management_menu() {
  $items = array();
  $items['campaign-management/test/%/%'] = array(
    'title' => 'Campaign Management',
    'description' => 'A section where you can manage your campaigns',
    'page callback' => 'cm_home',
    'page arguments' => array(3, 4),
    'access callback' => TRUE,
  );
  return $items
}

```

Here, for the fourth argument, there should be only two options {add/edit}. Is there any option in drupal to set these two keywords explicitely. ie,

```
$items['campaign-management/test/%/{add|edit}'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

```

# Answer
> 0 votes
There isn't such an option; you just define two route items.

```
$items['campaign-management/test/%/add'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

$items['campaign-management/test/%/edit'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

```

Alternatively, you define your route as follows.

```
$items['campaign-management/test/%/%'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

```

Your page callback then will do something when the last argument it get is `'add'` or `'edit'`; eventually, it can return a 404 error when the argument doesn't have one of the desired values.

Keep in mind that in Drupal 7, a user visiting (for example) node/1/sgsdrgdfgdfe45t63635wsg will normally see the node page (node/1, in this case). To keep that behavior, you should define the campaign-management/test/%/add and campaign-management/test/%/edit routes.

---
Tags: routes
---


# Question
Title: Unresolved dependency Invite (Version 3.x required)
I have upgraded drupal , but when i am running update.php I am getting this error . I have tried after disable invite but still no luck.

Unresolved dependency Invite (Version 3.x required) User Relationships Invites requires this module and version. Currently using Invite version 4.0-beta2

# Answer
Sorry i just found solution . I have have disabled User Relationships Invites using db from system table and it works .
> -1 votes

---
Tags: 7, upgrading
---


# Question
Title: Set data value in rules not written when using a condition
I like to create a rule that will overwrite my body field after saving new content. This is content from the same node that has been created(field\_update) and some content from referenced users form a user reference field(field\_userrefer).

I have a CUSTOM TEXT field called "field\_update". This is is were content is written.

My actionrule is :

* set data value "node-body-value" to
* \[node:field-update\] this works.

I have to create conditions to get the required fields I want to show in the data selection. This also works very nice because is can see all fields in my data selection auto complete box.

The problem is that when I add these conditions my body field isn't being populated by my custom values.

Any help appreciated.

When i have a set of rules without conditions.

# Answer
I have fixed. Seems like conditions is quite the puzzle. I fetched entity by ID with actions to fix it.

conditions: Entity has field: parameter:node, Field:field\_userref

actions: Fetch entity by id(id01) :. type: user, id:node:field-userref:uid Fetch entity by id(id02) :. type: profile, id:entity-id01:profile-main:pid wich made all profile2 fields available.
> 0 votes

---
Tags: rules
---


# Question
Title: How to move the "Main navigation" in the Bartik theme?
In Drupal 8, with the Bartik theme, I want to put the "Main navigation" tabs of the "Primary menu" region, on the top right, beside the "Site branding" block.

If I just move the "Main navigation" to the Header region, the tabs are lost. I want to preserve the tabs.

How do I do it?

# Answer
> 0 votes
First the main navigation is a block. Under Structure-\>Blocks you'll see Navigation. Move it to where it makes sense to you. Secondly Structure-\>menu is where you determine what items appear in your menu.

---
Tags: theming, 8
---


# Question
Title: Submitting a form with AJAX causes page reload but only on mobile
I am submitting the user profile edit form by hooking the user profile edit form like this:

```
$form['actions']['submit']['#ajax'] = array(
'callback' => 'user_profile_submit',
'wrapper' => $form['#attributes']['id'],
'method' => 'invoke',
'effect' => 'fade',
);

```

The callback function `user_profile_submit` invokes a simple jQuery alert notification specifying if the form was saved successfully. The setup works perfectly on the desktop i.e. the form is submitted with AJAX with no page reload whatsoever. However, saving the same form using mobile devices causes always a page reload. Any idea what might be causing this behavior? Thanks.

**Update:**

Problem can be observed in Chrome/Dolphin but not in Firefox.

# Answer
> 1 votes
**Solved:**

I have just downloaded the latest development version of jQuery Update module and the problem was solved. It has to do with this module nothing else.

---
Tags: forms, javascript, ajax
---


title: Delete a custom content type

text:
# Question
Title: Delete a custom content type
When my module is uninstalled, I want to delete the custom content type created by config files on module installation. On Drupal 7 there was a `node_type_delete(node_machine_name)`. What is the equivalent method/function, in Drupal 8?

# Answer
> 1 votes
See How to delete a content type, programmatically? for the easiest way for your use case. This works for any config entity that doesn't already explicitly depend on your module (those are uninstalled anyway).

The nice thing about that approach is that the user will be informed on the uninstall confirm age that this stuff will be deleted.

To delete using the API, node types are entities, so you delete them like all others: `NodeType::load('id')->delete()`

---
Tags: nodes, 8
---


# Question
Title: How to assign a user a title based on the number of created nodes?
I want to set up a system where a user is given a title based on how much content they have created/published. So, for instance, if the user has published:

```
0 nodes  - Noobie
1+ nodes - Poster
10+ nodes - Frequent poster
20+ nodes - Super Poster
50+ nodes - God`

```

I'm wondering if there is a way to implement this in a Drupal site. I can think of a way to do it using database queries and a computed field, but I'm wondering if there might be a more efficient way to go about doing it.

# Answer
> 7 votes
I doubt there is a module for this, but hey. Do not let that bring you down, it's actually a *great* idea for a custom module! If you have a bit of patience, Drupal is very easy to learn once you get past the initial learning curve.

If you need a start, the module developper section and the create a module page on Drupal are great place to start.

There are many, many ways you could do this, but to start I would probably create a small module. Imagine it's called `super_usernames`, for the purpose of this post. I would just create a folder in sites/all/modules called \`super\_usernames. That folder would need to contain only 2 files:

`super_usernames.info` and `super_usernames.module`. The `info` file is very easy:

```
name = Super Usernames
description = Gives special credits to usernames depending on number of posts.
core = 7.x
files[] = super_usernames.module

```

The module file would need at the minimum *just one* hook to be defined. Hooks are just plain old php functions that use a simple naming convention in order to be executed by Drupal automatically.

The hook you need here is `hook_node_view`. Basically you want to add :

```
/*
 * Implements hook_node_load
 */
function super_usernames_node_view($node, $view_mode){
  $supported_node_types = array('page', 'article', 'blog'); // Supports default content types
  if (in_array($node->type, $supported_node_types) {
    // query to get number of nodes this user has published
    $result = db_query("SELECT count(nid) as nodecount from {node} WHERE uid = %d", $node->uid);
     $row = db_fetch_object($result);
     $node_count = $row->nodecount; // Easier to read
     switch ($node_count){
       case $node_count >= 50:
           $node->super_username = "God";
         break;
       case $node_count >= 20:
          $node->super_username = "Super Poster";
         break;
       case $node_count >= 10:
          $node->super_username = " Frequent Poster";
         break;
       case  $node_count >= 1:  // same as > 0, but who cares...
           $node->super_username = "Poster";
         break;
       default:
           $node->super_username = "Noobie";
     }
  }
}

```

Now. After doing this, all your nodes should contain the dynamic value of the number of nodes posted by that node's author. This would be added on the fly on every page load from content-types articles, and pages.

You still need to have it displayed somewhere, though! This is where you would ideally create a sub-theme (so as not to hack a base theme). But for the purpose of this post, we will simply modify one file: node.tpl.php.

Check the theme you are using, by default it is bartik but the procedure is mostly the same whatever theme you are using.

Go into your themes/bartik/templates directory, open the node.tpl.php file. Locate where you want to add the super username in the html, and add this code snippet:

```
<?php if ($node->super_username): ?>
  <div class="superUsername">
    <?php print $node->super_username; ?>
  </div>
<?php endif; ?>

```

Now. One last step, you may need to clear the cache for changes to take effect. Devel module makes it easy, Drush makes it even easier. After this, you should have your super usernames dynamically shown on all the content-types defined in the `supported_node_types` array.

Hope this doesn't sound too complicated, it's actually quite trivial when you go through the process a few times. Feel free to message me or repost here if you need any help.

Happy coding, cheers!

* PS: This code has been slapped up from memory, nothing is tested but *should be pretty close to a fully working example*. Your mileage may vary, there may be typos in there.

# Answer
> 3 votes
A general-purpose module for use cases like this is User Points, which integrates with Rules. You could use rules to automatically add points when a user's content is published. You could even make some content types more valuable than others.

As for the titles, there is the User Badges module for D6, although there has been no official release for D7. In the meantime, depending on how complex your setup is, you could add a text select field to the user profile and use Field Permissions to forbid users from editing it. Then, you could use Rules to automatically set the data value at each threshold (1, 10, 20, etc.)

# Answer
> 3 votes
Another option to the already good suggestion of using the User Points \+ Rules modules, would be the Achievements module.

This is more geared towards mimicking the idea of gamification found on sites such as this, but will definitely give you full control if you're up for calling a few API functions.

# Answer
> 2 votes
The Goals module is yet another solution to answer this question.

**Goals** and **Tasks** are implemented using fieldable entities. So you can customize Goals via "Manage Fields" and/or "Manage display". E.g. to add your own fields, such as:

* descriptions.
* images.
* links to external resources.
* etc.

Head over to the Goals video which includes:

* a general introduction to the module.
* a demonstration to install, configure and use it.
* samples of how it uses the Rules modules to do its magic (i.e. to track the progress of a user to achieve the various roles.

Using the **Goals Extras** sub-module it integrates with the User Points module also.

***Measuring the number of nodes published by a user*** (as in your question here), would really be like a getting started with this module: each of the 5 examples would become "a" Goal, whereas the actual "Tasks" would consists of just "publishing a node".

Even though your question (requirements) doesn't seem to include that, you could take it a bit further. E.g. by only taking into account 1 published node per day (so a user publishing 3 nodes on the same day would only count for 1).

All this can be done with site building features only (no custom code involved), though hooks are available to integrate it in custom coding also).

For more details, refer to its Community Documentation. For some details about how it differs from the Achievements module, refer to What is the difference with the Achievements module, which states:

> The Goals module is built around using the admin interface configuration. Plus, goals and tasks within the Goals module are fieldable entities, so you have the flexibility to add additional fields and incorporate these entities into views.
>
> I can't speak definitively for the Achievements module, but my best understanding is that it relies heavily on custom coding to handle many of the functions.

Disclosure: I'm the maintainer of this module.

---
Tags: 7, nodes
---


# Question
Title: How can I add a tab to the admin/content page
I'm new to drupal, so sorry if this is a stupid question.

While developing a module, is it possible to add a tab to the /admin/content page (where by default there is content, comments, files)

Currently using 8.0.6

# Answer
Similar to Drupal 7, tabs are called "local tasks". Your module should implement a local task and a route.

The complexity in this is that `/admin/content` is a views-generated route with a system module fallback in case the view is disabled (as explained by @Berdir below), and the base route should be `system.admin_content`.

```
mymodule.mytask:
  title: 'My Task'
  route_name: 'mymodule.mytask.route'
  base_route: 'system.admin_content'
  weight: 1

```

If the view itself isn't altered, then the route is `view.ID.page_NUMBER`. I've done this latter thing working on an entity example module in my sandbox (Shift).
> 7 votes

# Answer
The tab "file" for example is configured in a view:

```
admin/structure/views/view/files:
PAGE SETTINGS
Path:/admin/content/files
Menu:Tab: Files

```

You can do the same with yml files in your module:

Providing module-defined menu links

Routing system in Drupal 8

An example from core module comment:

mymodule.links.task.yml:

```
comment.admin:
  title: Comments
  route_name: comment.admin
  base_route: system.admin_content

```

(credit: comment from Berdir)
> 5 votes

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


# Question
Title: Taxonomy terms with associated nodes: display page by page navigation in node page?
Hi i have a content type called **Product** and have fields(title,description,code,image) and also have vocabulary **categories** like below formate

```
parent term 1
 -child term 1
    --sub child term 1.1
    --sub child term 1.2
    --sub child term 1.3
    --sub child term 1.4
    --sub child term 1.5
parent term 2
  --child term 2
    --sub child term 2.1
    --sub child term 2.2
    --sub child term 2.3
    --sub child term 2.4
    --sub child term 2.5
.
.
parent term 5
  --child term 5
    --sub child term 5.1
    --sub child term 5.2
    --sub child term 5.3
    --sub child term 5.4
    --sub child term 5.5

```

so i want to display my product node page first **parent terms list** when i click parent term 1 then it's display all related child terms in next page after that when click child term 1 display all related sub child terms list in another page after that when i click sub child term 1.1 need to display related products list with above fields.Please find below flow of screen shots.

**Taxonomy Parent Terms list** Step 1

Step 2 when i clk Parent term 1 need to display all related child terms in another page like below

step 3 when i clk child term 1 need to display all related sub child terms in another page like below

step 4 when i clk sub child term 1.1 need to display all related node i.e product items list with above fields info.  Please advice Thanks.

# Answer
> 0 votes
For this you will have to use view module.

Step 1: Create a new view from Administration \> Structure \> View. Click on + Add new view.

Step 2: Give a name to your new view. From '**Show**' select Taxonomy terms and from type select appropriate taxonomy vocabulary (I assume name is 'product' here). Check either page or block and click '**Continue & edit**'.

Step 3: In First Page or Block under '**Filter Criteria**' click on Add and select **Taxonomy Vocabulary** and set it to use **product**. Click on Add again from **Filter Criteria** and select **Taxonomy term** and set it to *Parent term 1, Parent term 2, ....*. Now in preview section you will see the Parent terms.

Step 4: Under **FIELDS** click on Add and select **Taxonomy term: Term ID** and click on **Apply**. In **Configure field** page check on **Exclude from display** and click on apply. (I assume Taxonomy term: Name is already there.)

Step 5: Rearrange the order of fields by clicking on drop down icon besides **Add** under **FIELDS**. Make user the **Term ID** appears above **Term Name** and **Apply**.

Step 6: Click on **Taxonomy term: Term Name** and expand **REWRITE RESULTS**. Click the checkbox *Rewrite the output of this field* and in text area name **Text**, type in \[name\] and **Apply**.

Step 7: Create a new page in same view **+Add** \> **Page** or create a different view as in Step 1 & 2.

Step 8: In new view page set the path under **PAGE SETTINGS** to *subchild/tid* (here tid refers to parent tid or taxonomy id).

Step 9: Follow the steps 3 to 6. Instead of Parent term 1, select Child term 1.1, Child term 1.2, ... assuming Parent is 1. And set href to *child/tid* for step 6 here tid refers to child term 1.\* tid.

Step 10: Follow the same procedure as in step 8 & 9 for other child terms.

Step 11: Follow the same procedure as in Step 8 to 10. However set *path* under **Page Settings** to *subchild/tid* and href attribute for step 6 would be *product/tid*, here tid is subchild tid or taxonomy ID.

Step 12: Follow the same procedure as in Step 11 for all subchild terms.

For Displaying Products:

Step 1: Create a new View from Administration \> Structure \> View. Click on **\+ Add new view**.

Step 2: Select **Content** from Show with appropriate type. Check on page and click on **Continue & edit**.

Step 3: Set the *path* in **Page Settings** to *product/tid* and from **Filter Criteria** select the **Taxonomy term** appropriate to the product to be displayed.

---
Tags: views, taxonomy-terms, panels
---


# Question
Title: How do I render the absolute URL of a referenced entity in a simplenews newsletter?
When I send a node as a `simplenews` newsletter I use the node's `Email: HTML` display. One of the fields in this view is a `label` of a referenced entity to be rendered as a `Link to the referenced entity`. Drupal renders it as a link with a relative / site-local URL. I want it to be rendered as an absolute / external URL.

For what it's worth:
In the render array the link is stored in
`$variable['items']['0']['content']['#url']` which is a `Drupal\Core\Url` with a protected `external` property of `false`

I can't see anything in the `Url` interface that would change `external` to `true` or indeed whether this is the thing to do.

# Answer
> 5 votes
`external` and `absolute` are different:

`external` is an url without internal route. You can't change this property. This is set when you create an url.

`absolute` is an option, which you can set at any time in the url object:

```
$url->setAbsolute();

```

Or set to false:

```
$url->setAbsolute(FALSE);

```

And this will change how the url is generated absolute or relative.

# Answer
> 2 votes
looks like that's a read-only property. Most other things can be changed with setOption() or specific methods. Not sure if that's an oversight or by design.

You need to build a new Url object object from the node object and pass the option in:

```
$node->toUrl('canonical', ['external' => TRUE]);

```

---
Tags: 8, theming, emails
---


title: How to hide time from the date display?

text:
# Question
Title: How to hide time from the date display?
In a view using Articles and Blog posts sorted by recent post date, I'm using \[Content: Post date\] and I would like to display (as a column on the display) as only the date and not the time, i.e. 2016/04/08.

I merely wish to alter what data Drupal is displaying, not the data it is collecting.

How can I apply this date format to the field in the view?

In Home\>Administration\>Date and Time, I can add new date type but all 19 of the options include displays of time.

# Answer
> 1 votes
There should also be a Formats tab at the top of that page. Here you can add additional formatting (like date or time only formats). After saving the format, go back to the first page and now you can select your newly created format as an option.

# Answer
> 0 votes
Aha! Minutes after I post, I discover something else.

In the configuration of the Date Field in the Fields section of the View, I have **more** features, namely the ability to create a Custom Date format (no Custom in the Amin\>Date and Time).

Selecting custom, I used this excellent manual http://php.net/manual/en/function.date.php

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


# Question
Title: Un-promote all other nodes when one node is promoted to front page
I have an instance for a specific content type that at any given time there can only be ONE item promoted to the front page. I have a view that looks for this value and displays the item in a block on the front page if it is promoted. The problem is that it is setup to only show ONE item, so the editor has to remember to go and UN-promote any other node after they promote the one they want. I'm trying to figure out a way that when the user clicks the promote to front page check box on the node edit form and saves the node, all other nodes are auto un-promoted. I tried to hook into hook\_node\_presave, but I can't seem to get the query right to un-promote all the other nodes, because I am using revisions, so I'm not entirely sure what to update.

This is what I have right now that is not working, I think because I am using revisions:

```
function MY_MODULE_node_presave($node){
  if ($node->type == 'career' && $node->promote == 1) {
    $sql = "
    UPDATE {node} n
    SET n.promote = 0
    WHERE n.type = 'career'
    ";
    db_query($sql);
  }
}

```

# Answer
~~In the views, you can simply sort the view by updated date on filtered promoted nodes. I think this will solve the issue without any custom code.~~ This might not work in all cases. It will fail when content writer promotes a new node, then updates old promoted node.

You can use below code. For your specific case, you can use $base\_root to apply the change on a particular site only.

```
function MY_MODULE_node_presave($node){
  // if $base_root is equal to my.specific.domain.site, then perform the db_update.
  if ($node->type == 'career' && $node->promote == 1) {
    $update = db_update('node')
      ->fields(array('promote' => 0))
      ->condition('node.promote', 1, '=')
      ->condition('node.type', 'career', '=')
      ->condition('node.nid', $node->nid, '<>');
    $update.execute();
    // Do this if you still face the problem. Also please comment if node_revision update was necessary.
    // $update = db_update('node_revision')
    //   ->fields(array('promote' => 0))
    //   ->condition('node.promote', 1, '=')
    //   ->condition('node.type', 'career', '=')
    //   ->condition('node.nid', $node->nid, '<>');
    // $update.execute();
  }
}

```
> 2 votes

---
Tags: nodes, database, hooks
---


title: How to edit the sidebar form content?

text:
# Question
Title: How to edit the sidebar form content?
I recently inherited this website from a colleague of mine: http://cityrentacar.gr

It runs under Drupal 7 with the Nexus theme.

I am trying to edit the fields/select-options on the sidebar request form but as soon as i login i only see a configure button over the form?

Is there a way to manually edit the field?

Any help would be appreciated.

Thanks.

# Answer
> 0 votes
It looks like your predecessor used jotform to set this up, see this screenshot:

If I am right, then you should be able to edit these values via the related jotform account.

Hope this does it for you, it seems you need the get those jotform credentials for the linked jotform account!

---
Tags: forms
---


title: How to submit a form with javascript?

text:
# Question
Title: How to submit a form with javascript?
I have an exposed views form, am geolocating in javascript and setting the co-ordinates in the exposed form.

This form submits properly when I click on the 'apply' button but does not when I use javascript to submit the form. The page refreshes, but the values have not been changed.

The form is standard FAPI. It is not a views-ajax form although I would like to move to ajax at some point in the future when I sort out the problems with gmaps + ajax.

Both of the following fail.

```
jQuery('#edit-submit-studio-locations').click();
jQuery('#views-exposed-form-studio-locations-page').submit();

```

The full code is in github.

# Answer
> 1 votes
Add this code inside Drupal.behaviors.

```
$('.views-exposed-form APPLY_BUTTON ID/class').click(function() {
  // Submit the form
  (this).parents('form').submit();
});

```

Hope it works.

# Answer
> 1 votes
The following would do the job:

```
jQuery('#edit-submit-studio-locations').mousedown();

```

# Answer
> 0 votes
You can submit form using jquery or add some trigger action

here is example code :

```
Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {
    $("form#your-form").submit(function(e) {
     // some code here
    });
  }
}

```

# Answer
> 0 votes
Apologies, the problem was that the geocoding was being done asynchronously. Both of these submission methods work.

The solution is to trigger an event in the geocoding closure and react to this event.

I thought FAPI was somehow validating my submission.

```
geocoder.geocode({'address': address_string}, function (results, status) {
  $(window).trigger('yhive_geocoded');
});

$(window).on('yhive_geocoded', function() {
      $('#views-exposed-form-studio-locations-page').submit();
});

```

---
Tags: forms, javascript, views
---


# Question
Title: How to process field input so b52 goes into database as B-52
Situation: D7 Text field on a content type.

User enters something like: b52

I want it stored in the database as: B-52

I have a function that does the regex. I just don't know where to process the input before it goes in the database.

Don't want to install Field Validation or do any validation forcing a User to "correctly" format their own data. I just want to catch their input, modify it, and save it in the database as so.

What hook do I use and can it be done in the theme?

# Answer
OK figured it out.

hook\_node\_presave() is what I want and it can only be called from a module I think.

Found the answer here: node\_presave doesn't work

```
function nodepresave_node_presave($node){
  drupal_set_message('nodepresave DEBUG: PRESAVE Called');
  if ($node->type === 'vehicle') {
    drupal_set_message('nodepresave DEBUG: node->type === vehicle');
    drupal_set_message($node->field_id_number['und'][0]['value']);
  }}

```
> 0 votes

---
Tags: entities, database, hooks
---


# Question
Title: Remove items from a menu based on node type efficiently
I am trying to remove items from a menu based on the type of node it links to.

I'm currently achieving this using `hook_menu_link` and `menu_get_object`. I'm running into problems because the size of the menu is 500+ items, resulting in 5000+ DB queries to generate the page.

If I remove the `hook_menu_link` function and show all menu items, the DB queries drop to around 700.

Here is the current code:

```
function amoss_menu_link(&$variables) {

  // Hide book sections from the menu;.
  if (isset($variables['element']['#original_link']['link_path'])) {
    if ($variables['element']['#original_link']['menu_name'] == 'book-toc-1') {
      if (book_modifications_is_book_section($variables['element']['#original_link']['link_path'])) {
        return '';
      }
    }
  }

  // Output a menu link.
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function book_modifications_is_book_section($link_path) {

  if (book_modifications_get_type_from_link_path($link_path) == 'book_section') {
    return TRUE;
  }

  return FALSE;
}

function book_modifications_get_type_from_link_path($link_path) {
  $node = menu_get_object('node', 1, $link_path);

  if (isset($node->type)) {
    return $node->type;
  }
  else {
    return '';
  }

}

```

I tried to use `drupal_static` in the `book_modifications_get_type_from_link_path` function, that killed the conditional checks.

I tried caching the results for each item with `set_cache`, but this was not successful either.

```
function book_modifications_get_type_from_link_path( $link_path ) {

    if ($cache = cache_get('book_modifications_'. $link_path )) {
        $type = $cache->data;
    }
    else {
        // Do your expensive calculations here, and populate $my_data
        // with the correct stuff..
        $node = menu_get_object('node', 1, $link_path);
        $type = isset( $node->type ) ? $node->type : '';
        // dpm('miss');
        cache_set('book_modifications_'. $link_path, $type, 'CACHE_TEMPORARY');
    }

        // dpm($type);
    return $type;
}

```

I appreciate any suggestions for making this slow operation faster.

# Answer
Gathering node paths for the `book_section` nodes in a function cached with `drupal_static` and using removing items from the menu based on that, rather than loading node objects for each menu item removed thousands or surplus DB queries.

Refactored code

```
function amoss_menu_link(&$variables) {

  // Hide book sections from the menu;.
  if (isset($variables['element']['#original_link']['link_path'])) {
    if ($variables['element']['#original_link']['menu_name'] == 'book-toc-1') {
        $book_sections = book_modifications_get_book_section_paths();

      if ( in_array( $variables['element']['#original_link']['link_path'], $book_sections ) ) {
        return '';
      }
    }
  }

  // Output a menu link.
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function book_modifications_get_book_section_paths() {
    $book_section_paths = &drupal_static(__FUNCTION__);

    if (!isset($book_section_paths)) {
        $book_section_paths = array();
        $nids = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('type', 'book_section', '=')
        ->execute()
        ->fetchCol();

        foreach ( $nids as $id ) {
            $book_section_paths[] = 'node/'.$id;
        }

    }

    return $book_section_paths;
}

```
> 0 votes

---
Tags: 7, performance
---


title: Adding check boxes to contact form

text:
# Question
Title: Adding check boxes to contact form
I am attempting to make a contact form in Drupal 8 using "Contact forms" included in core. I'm struggling to figure out how to really customize it, like adding radio buttons or check boxes - does this have to be done through the theme\_name.theme file? If so, can someone give me an example of adding elements to the page? I'm new to Drupal so thanks for helping out.

# Answer
> 10 votes
In Drupal 8, contact forms are entities listed in admin/structure/contact. Once you created the new contact form, on that page select *Manage fields* in the *Operations* column; it's a drop-down selector, so you will need to select it to see that operation, since the default operation for contact forms you create is *Edit*.

>

On the page you will see, you can add new fields.

The tricky part is understanding how to show checkboxes: You need to select the right field type. For example, if you want to show 4 checkboxes, then you select *Text (list)* as field type.

>

Enter the 4 values you want to show, and enter 4 as *Allowed number of values*.

>

To show it as checkboxes, you go to the *Manage form display* of your contact form (in my case, admin/structure/contact/manage/test/form-display, since *test* is the machine name of the contact form I created). For the field you created, it should show the following.

>

Change it to *Check boxes / radio buttons* and save.

>

Since the allowed values are 4, the contact form will show checkboxes, not radio buttons.

---
Tags: forms, 8, emails
---


# Question
Title: How copy file field data from one file field to another using Views Bulk Operations?
For example, you want to copy the data for a file field with the machine readable name field\_pdf into field\_attachment

I been following the examples, but there is not an example for this action.

Is this possible with VBO and if so what is the code?

I would very much like to resolve this problem for myself and update the page on d.o

# Answer
> 3 votes
Here is a pure site-building approach:

1. Install File Field Rules
2. Define a new Rule Component (an "Action set"), named e.g. "Copy file"
    1. Define at least one input/parameter, e.g. node\_source
    2. Define optionally a second input/parameter, e.g. node\_target
3. Configure your Rule component to perform a "Copy file field contents" action, with the following settings:
    1. Source entity =\> e.g. 'node\_source'
    2. Destination entity =\> e.g. 'node\_target': This depends on your case, you may even want to copy a file inside the same node, between different fields. You can in that case, use 'node\_source' again as your target entity.
    3. Select the Source and Destination fields
    4. Save our component and you are done with Rules configurations.
4. Back to your View and VBO field configuration, you can now select the "Copy file" action.

I tried this and was able to copy an image file between two different article nodes, hope it works for you too.

---
Tags: 7, views
---


title: Change Menu Link Title Dynamically

text:
# Question
Title: Change Menu Link Title Dynamically
Requirements:

Change the Navigation block link "Add Listing" based on role. This is the built in Navigation block and I've renamed Add Content to Add Listing

I've tried all the solutions here. Though I admit I am probably doing it wrong.

Change menu link title dynamically? How do I modify a menu link title dynamically? How do I dynamically change the title of a menu link?

I've created a module with the following code:

```
function mymodule_menu_alter(&$items) {
  $item['options']['alter'] = TRUE;
  $items['node/add']['access callback'] = '_accesscheck';
  $items['node/add']['title callback'] = 'mymodule_title_callback';
    var_dump($items);
}

function mymodule_title_callback($arg1) {
    $title = 'New Title';
    return $title;
}

function _accesscheck(){
  global $user;
  return $user->uid;
}

```

This is a var\_dump snippet of what I'm after:

```
["node/add"]=>
  array(5) {
    ["title"]=>
    string(11) "Add content"
    ["page callback"]=>
    string(13) "node_add_page"
    ["access callback"]=>
    string(16) "_node_add_access"
    ["file"]=>
    string(14) "node.pages.inc"
    ["module"]=>
    string(4) "node"
  }

```

Before I attempt to include roles I'm just trying to get the link to change.

# Answer
> 3 votes
Just tried your code (trimmed down) and it worked without any problems. I simply overwrote the "title callback", like you did. I tried it with admin and anonymous account, see the screenshots for the end result below:

I also added, as an extra precaution, a module\_implements\_alter implementation. With that hook, you can push your menu\_alter implementation to the end of the hook\_menu\_alter list. That way you can make sure it gets executed after every other menu\_alter, in case there was some competing implementation there.

```
<?php

/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  $items['node/add']['title callback'] = 'mymodule_title_callback';
}

function mymodule_title_callback($arg1) {
  global $user;
  $title = 'New Title';
  if( $user->uid == 0 ) {
    $title = 'New Title for anonymous';
  }
  return $title;
}

/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'menu_alter') {
    return;
  }

  $module = 'mymodule';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);
  $implementations = $implementations + $group;
}

```

Hope you can get this to work!

---
Tags: 7, navigation
---


# Question
Title: How to build a reusable configurable form
How could I build a reusable form that can be reconfigured for each location in which it is used? It would have the same fields, however select list values would be different depending on what the user thinks it should contain based on its location in the site.

Locations include blocks and panels across many pages and sites, and potentially multiple locations on the same page.

# Answer
In a custom module, use the FormAPI to build your form and create variables to store your #options for example (in the case you mentioned of select lists that change). Set the variable according to the context and you should be good to go.

```
/**
 * Implements hook_form();
 */
function mymodule_form($form, &$form_state) {

  // For inspecting information about entity and id:
  kpr(arg(0));
  kpr(arg(1));

  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => $variable_according_to_context,
    '#default_value' => $category['selected'],
    '#description' => t('Varies according to context.'),
  return $form;
}

```

The `$variable_according_to_context` will hold the options of your select list. You can set this variable to different options according to the context you are in. You can use `arg(0)` or `arg(1)` to get the node or entity type the form is in. I hope that was clear enough on how I would approach this.
> 0 votes

---
Tags: 7, forms, blocks, panels
---


# Question
Title: Drupal web cluster with memcached. memcached failover?
Running Drupal 7 sites (under Aegir) and I'm investigating a method to scale out the web boxes horizontally, so that any Apache server can process a request for any Drupal site. We're currently at ~50 Drupal sites on our platform. All sites also run through Varnish.

At the moment with our single-server setup I have memcached installed locally on the Apache box.

If we add further Apache boxes *and* each has their own memcached instance, it's likely that cached content in memcached will be different on each different host.
The way around this is to run memcached on our Varnish or database instance, though on our Varnish box makes most sense.

From the `settings.php` config I can presumably specify multiple memcached servers in the `memcache_servers` array:

```
// make MemCacheDrupal the default cache class
$conf['cache_default_class'] = 'MemCacheDrupal';

// Key Prefix: edit this for multisite use.
$conf['memcache_key_prefix'] = $databases['default']['default']['username'];

$conf['memcache_servers'] = array(
    '127.0.0.1:11211' => 'default',
);
```

How does Drupal choose which memcached server to use from this array?

What I'm looking for is the ability to specify a failover memcached server. So if the primary "shared" memcached instance is down, say we take our Varnish VM down for maintenance, then it starts using another *cold* memcached instance.

Or as an alternative is there a way for Drupal to failover to using the database cache instead of memcached?

# Answer
If you might want to setup a memcache cluster, consisting of multiple servers. The idea is that you have more than one server in the cluster and if one of the servers is offline for some reason the others will be used.

This is fairly easy to setup and is documented in the memcache module as well, the config could look something like this:

```
$conf['memcache_servers'] = array(
  '10.0.0.1:11212' => 'default',
  '10.0.0.2:11212' => 'default',
  '10.0.0.3:11212' => 'default'
);
$conf['memcache_bins'] = array('cache' => 'default');

```

PHP will handle the clustering, so you wouldn't need to do anything. This means that if a server dies, that cache wont be available, but will automatically be generated on one of the other servers.

One of the ideas with memcache is that you can pool the memory of multiple servers to create a single shared pool.

In your example, you could also use your webservers as a memcache cluster, but that would require that the webservers can talk to each other. Usually when you require multiple servers, you also want to have separate memcache servers, so you can optimize the servers for their specific task.
> 1 votes

# Answer
Looks like you're wanting memcache replication. My recommendation is to use MySQL's memcache plugin to accomplish this replication. Also recommend using MySQL 5.7 if you're comfortable with using a non GA release for your caches.
> 0 votes

---
Tags: caching
---


# Question
Title: drush xmlsitemap-regenerate domain is incorrect
Whenever I run:

```
drush xmlsitemap-regenerate

```

on our live server, the domains in the sitemap all refer to:

```
http://default

```

Only when I generate the sitemap from the Drupal admin backend, do I get the correct sitemap.xml with the correct domain setup.

I need to have the drush command working correctly, as we're using it with a Capistrano deploy script.

Can I somehow pass the domain name to the drush command?

# Answer
Did you set your default base URL under the 'Advanced' fieldset. in `admin/config/search/xmlsitemap` (D7 version) ?
> 1 votes

# Answer
Add `--uri` to your command.

Example:

```
drush --uri=example.com xmlsitemap-regenerate

```
> 0 votes

---
Tags: 7, drush
---


# Question
Title: How create a role that only can create users?
I want to create a role in Drupal. I want create role assign to specific user. Specific user can create only user and not anything.

# Answer
Go to `admin/people/permissions/roles` and create your role. Then go to `admin/people/permissions` and uncheck all the permission for the new user and check the Administer users permission in the User section:

To uncheck all the permission I can sugest you the use of the Permission Select module.

> Permission Select is a module that allows for quicker editing of role permissions on /admin/user/permissions.

And as Pierre Vriens says in his comment:

> "do not grant ANY permissions to authenticated users". Because any user with permission to create users is also an authenticated user.
> 3 votes

# Answer
You can create roles in drupal 7 on admin/people/permissions/roles. Then assign the permissions that you want to that role.

There is a permission called "Administer users" but be careful because it can have security implications. Make sure that it only does what the user is supposed to do: test it!

Otherwise you could create your own permission with hook\_permission and decide exactly what permission you want to grant.
> 2 votes

---
Tags: users
---


# Question
Title: How to bulk assign existing content to a group created with the Group module?
The Group module is an alternative for Organic Groups. One of the features it offers is that you can assign nodes to a Group.

**Question**: how to bulk-assign a set of existing nodes to a specific group, using site building techniques only (not programmatically, which appears to be a possible alternative also)?

# Answer
> 1 votes
# Step 1: Create a Rules Component

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

```
{ "rules_assign_existing_content_to_a_group" : {
    "LABEL" : "Assign existing content to a group",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_to_assign" : { "label" : "Node to be assigned", "type" : "node" },
      "assigned_group" : { "label" : "Assigned group", "type" : "group" }
    },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "node-to-assign" ], "type" : "node" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node-to-assign:group" ], "value" : [ "assigned-group" ] } }
    ]
  }
}

```

This Rules Component will be used in the subsequent step.

Note that I've not added a Rules Condition here about selected content types, that's possibly an extra condition you might want to add also.

If you want, just grab (copy) the exported rule above, and simply import this Rules Component in your own environment.

After you did this, you can navigate to `admin/config/workflow/rules/components` in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Node to be assigned***. Use a similar technique to specify the **Assigned Group** and hit the ***`Execute`*** mode. The node you selected will be assigned to the group you specified.

After you're confident your rule works fine, move on to the next step below.

# Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your **nodes** to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

**Attention**: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

---
Tags: 7, group
---


# Question
Title: How do I install Drupal with a custom language?
I know I can install a new Drupal web site with:

```
drush dl drupal --drupal-project-rename=[project]
cd [project]
drush site-install standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' \
    --site-name=Example

```

But how can I install Drupal 8 with some custom language, let's say italian, using Drush?

# Answer
Seems this works fine:

```
$ drush si standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' \
    --account-name=joe --account-pass=mom \
    --site-name=Example \
    --site-mail=noreply@example.com \
    --locale=it

```
> 5 votes

---
Tags: 8, drush, i18n-l10n, installation
---


# Question
Title: How can I add processing of text blocks before outputting them on site?
I have a library, that formats text for better readability. I want to put processing of text blocks and strings before outputting them on site, Where and how to do this?

The processor a very simple:

```
require_once("EMT.php");

$typograph = new EMTypograph();

$typograph->set_text($contentof_text_block);

$contentof_text_block = $typograph->apply();

```

Drupal 8

# Answer
> 1 votes
You implement a text filter. Here is an example, FilterHtml, from core: https://api.drupal.org/api/drupal/core!modules!filter!src!Plugin!Filter!FilterHtml.php/8

Here is one that I made: http://cgit.drupalcode.org/mathjax/tree/src/Plugin/Filter/MathjaxFilter.php

---
Tags: 8
---


# Question
Title: What are the various roles supported by the Group module?
The Group module is an alternative for Organic Groups. For each group you can specify appropriate permissions, and this for various "roles" that are specific to the Group module (these roles are not the typical/global roles of a typical Drupal site).

**Question**: what are the various roles supported by the Group module?

# Answer
> 6 votes
Here is a summary of the various roles used by the Group module:

* *Configured Global Roles*: These roles can be configured via the admin interface of the Group module, they are available (to grant permissions) for all individual groups (regardless of the "Group Type"). These roles cannot have permissions that vary per group type (they are all the same). Typical examples of such roles could be "**Group Moderator**" or "**Group Administrator**".
* *Special Global Roles*: These are the special (hardcoded) roles named "**Outsider**" (= a signed in user that did not join a group) and "**Member**" (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. Unlike Configured Global Roles, these roles can have different permissions sets for each group type. Special case: the role "**Anonymous**" is related to a user that is not signed).
* *Group Specific Roles*: These roles can be configured per group type and will only be available on groups of that group type. As an example, for a group type like "Class", you could configure roles such as "**Teacher**" and "**Student**".

---
Tags: 7, group
---


# Question
Title: How to use exchange rate from Currency Api in a field?
1. I've installed Currency Api Module + Yahoo! Finance currency converter and
2. made with "Currency Filter" a new field (using Markup module) in my content named "latest\_exchange\_rate" with the value of latest USD-EUR exchange rate coming from Yahoo!Finance;
3. in the same content, there is a decimal field named "usd\_value" filled with a value during content creation;
4. additionally I created also a Computed field named "eur\_value" which is a multiplication = "latest\_exchange\_rate * usd\_value";

The problem is that the computed field seems not able to read the value of "latest\_exchange\_rate" field, and the result is always 0.00.

I am not a coder, can you please help me to solve this problem? If my approach is not correct, how can I use an exchange value from Currency API to make conversions between different currencies?

Thank you in advance for attention, Francesco in Cina

# Answer
> 0 votes
Here is a much leaner version of your setup:

In order to get your node to always display the current converted usd\_value to EUROs, you will need only one computed field (no markup field required). You just will need to place the following in the "Display Code (PHP)" textarea:

```
$conversion_factor = CurrencyYahooFinanceCurrencyExchanger::load('USD','EUR');
$node_usd_value = $entity->field_usd_value[LANGUAGE_NONE][0]['value'];
$euro_value_live = $conversion_factor * $node_usd_value;
$display_output = number_format($euro_value_live,2);

```

That should be all, just tried it and I am getting the following to display. My computed field is called "EUR Value (Live)":

Hope this does the trick for you!

---
Tags: theming, entities
---


# Question
Title: Does cron queue manage max_execution time?
I have implemented an approximately 1000 nodes update using `hook_cron_queue_info()` and `hook_cron()`. When I manually run cron job from the Drupal administration pages, I get a *maximum time execution* error; once this number is reduced by 10, it works fine.

Any suggestion?

```
function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'skip on cron' => FALSE,
  );
  return $queues;
}

function my_module_cron() {
  $contents = lade_update_nodes(); // get node list for updation
  $queue = DrupalQueue::get('my_module_batch');
  foreach ($contents as $p_file) {
    $process_data = array(
    // set values for process
    );
    $queue->createItem($process_data);
  }
}

function _my_module_process_queue($arr) {
    // code for updation
    watchdog('update node', 'Custom msg');
}

```

# Answer
To answer the question in the title, Drupal cron does check the time used to process the items in a queue, and by default it gives 15 seconds to each queue. This still doesn't avoid the total time given to all the queues doesn't exceed the limit, especially if the call to `drupal_set_time_limit(240)` (which would set the time limit to 240 seconds) doesn't have success.

Also, since the code used by Drupal is the following one (see `drupal_cron_run()`), if processing a single item in a queue requires more than the time assigned to processing a queue (for example 30 seconds instead of 15), Drupal cannot block processing a queue when the time assigned to a queue is passed.

```
  foreach ($queues as $queue_name => $info) {
    if (!empty($info['skip on cron'])) {
      // Do not run if queue wants to skip.
      continue;
    }
    $callback = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      try {
        call_user_func($callback, $item->data);
        $queue->deleteItem($item);
      }
      catch (Exception $e) {
        // In case of exception log it and leave the item in the queue
        // to be processed again later.
        watchdog_exception('cron', $e);
      }
    }
  }

```

If you get a *maximum time execution* error, you can just limit the number of processed items, or assign less time for your queue.

```
function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'time' => 3,
  );
  return $queues;
}

```

As side note, setting `'skip on cron'` to `FALSE` is useless, as Drupal assumes it is `FALSE` by default. In fact, it uses `if (!empty($info['skip on cron'])) {}` to decide if skipping a queue; `!empty($info['skip on cron'])` is `FALSE` when `$info['skip on cron']` is not set, or when it is set to `FALSE`.
> 3 votes

---
Tags: 7, cron
---


# Question
Title: Drush 8 raises an error while running 'drush runserver'
I just installed Drush (globally) as described here: http://docs.drush.org/en/master/install/, on Ubuntu 14.04 (PHP 5.5.9).

Then I created a new Drupal 8 web site and database with:

```
$ drush dl drupal --drupal-project-rename=example
$ drush si standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]'
    --site-name=Example

```

When I run the built-in server within the project directory:

```
$ drush rs 8000

```

And I try to access `http://localhost:8000`, I get this error:

> PHP Warning: Unknown: failed to open stream: phar error: invalid url or non-existent phar phar:///usr/local/bin/drush/commands/runserver/d8-rs-router.php in Unknown on line 0
> PHP Fatal error: Unknown: Failed opening required 'phar:///usr/local/bin/drush/commands/runserver/d8-rs-router.php' (include\_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0

What's wrong?

# Answer
> 5 votes
I solved installing the last version of Drush via composer:

```
$ # Remove previous drush installation file
$ sudo rm /usr/local/bin/drush

$ # Install drush globally via composer
$ composer global require drush/drush
$ ln -s ~/.composer/vendor/bin/drush ~/bin/drush

```

Now it works.

---
Tags: 8, drush
---


title: Problems upgrading to PHP 5.5

text:
# Question
Title: Problems upgrading to PHP 5.5
I upgraded my server from php 5.3 to php 5.5 based on this link. I disabled the apc.so in php.ini, disabled apc module.

Drupal 7 multi-site. /home/default/public\_html is the root folder for /home/domain\_1/public\_html, /home/domain\_2/public\_html, /home/domain\_3/public\_html, **/home/domain\_4/public\_html**

three of these domains work as usual; visitors links all work and admin can log in and administer the three websites

the fourth site reports an error: visitors cannot see the site - the WOD is really Fatal error: Call to undefined function apc\_delete() in /home/default/public\_html/sites/all/modules/apc/drupal\_apc\_cache.inc on line 289

I cleared bootstrap cache and cleared the variable but to no effect. drush cc all, drush rr, and drush cron core did not improve this situation.

What else should I look for? Any other suggestions?

# Answer
> 6 votes
What you do when you remove a PHP extension used from a module you installed is uninstalling the module and then removing the PHP extension.

In this case, you also need to do something more: Since you are using the APC module as alternative Drupal cache, you need to remove the lines added to the settings.php files. Probably you will find the following lines.

```
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';

```

Alternatively, you could find the following ones.

```
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_default_class'] = 'DrupalAPCCache'

```

In any case, you need to remove the `$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';` line, and any line in settings.php that references the `DrupalAPCCache` class.

### References

* The README file for the APC module

### Side note

This is one of few cases where disabling a module, or uninstalling it without deleting its files, doesn't stop Drupal from using it. In fact, Drupal uses the following code.

```
  // Allow specifying special cache handlers in settings.php, like
  // using memcached or files for storing cache information.
  require_once DRUPAL_ROOT . '/includes/cache.inc';
  foreach (variable_get('cache_backends', array()) as $include) {
    require_once DRUPAL_ROOT . '/' . $include;
  }

```

It doesn't check the files are for a not enabled or not installed module. As long as it finds the files, it uses them. If then the code is using a non existing function (as in your case), it will raise a runtime error.

# Answer
> 4 votes
> I disabled the apc.so in php.ini, disabled apc module.

If you did it in this order, the uninstall may have not worked. I think the correct order is: Disable and uninstall the APC module. Then disable `apc.so`. Restart Apache.

You write that you've disabled the APC module. However, as you can see from *kiamlaluno*'s answer, Drupal may still use this module if part of your configuration refers to it. So make sure you also purge your `settings.php` for any lines referencing it.

I've been there (not with this particular module, but with others), and if cleaning out your `settings.php` don't fix it, here are a few more thing to try:

First - double check that the module really is disabled on the module page.

If it is, re-enable it, clear all caches, run the `update.php` script, then disable and uninstall the APC module. Make sure that there are no error messages or warnings during this process.

If the error persist, you should try to enable `apc.so` and restart Apache. That should take care of the "undefined function apc\_delete()"-error - but I understand that you really want APC disabled for Drupal 7.

So while `apc.so` is enabled in PHP go through the same routine again (re-enable the module, run the `update.php` script, then disable and uninstall it). Then move it away from your sites directory so Drupal don't find it (don't delete it, you may want to restore it if removing it confuses Drupal even more).

Then disable `apc.so` in PHP.ini, restart Apache, and check if the error has gone away.

Hopefully it has. If it has not, you need advice from somebody else.

---
Tags: 7, caching
---


# Question
Title: How to compute and display value of some fields?
I'm facing the issue but not found the way to resolve. is there any way to help me this. The issue is that I want to display the total value (included sum and get percent, etc) of some fields depend on what value user select in list. Value in table like that

**Table locations:**

Example:

```
ID Name values

1  US   20%
2  UK   30%

```

**Table Products**

Example:

```
ID Name  Price
1  pro_A 10$
2  pro_B 20$

```

And what I want to display is to show the list locations and products to let user select as list.

Example: when user select us and pro\_A, I want display a total field and computed it (10$\*100)/20

Anyone can help me this or help me organize infomation by other ways as long as I can get the same result.

# Answer
> 1 votes
Have a look at the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...

---
Tags: views, 7, entities, users
---


# Question
Title: What is the default operator in Rules module conditions?
I have an issue on production site that I cannot reproduce.

The Rule below should trigger an email if the new content is published. But emails are being send even if content is not published.

```
{ "rules_content_new" : {
  "LABEL" : "Notify new content",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "ON" : { "node_insert--article" : { "bundle" : "article" } },
  "IF" : [
  { "data_is" : { "data" : [ "node:status" ], "value" : "1" } },
  { "data_is" : { "data" : [ "node:field-custom" ], "value" : "13" } }
  ],
  "DO" : [
  { "mail" : {
  "to" : "test@mail.com",
  "bcc" : "[site:full-mailing-list]",
  "subject" : "[node:title]",
  "message" : "new content available",
  "from" : "test@from.com",
  "language" : [ "" ]
  }
  }
  ]
  }
 }

```

# Answer
From official Rules documentation:

> By default, Rules assumes AND operators between conditions (if no OR group is explicitly used).

Syntactically there is nothing wrong with your rule.

A little tip for troubleshooting this rule *(because obviously that rule does not give you any error messages)* \- add action "Show a message on the site" and output values from your conditions in that message. If the values shown are correct but the rule still malfunctions - try deleting it and then recreate it.

Also, you can try using Rules condition "Content is published" instead of checking the value of node:status. It is basically the same thing, but maybe in your situation will give a different result.
> 1 votes

---
Tags: rules
---


# Question
Title: Pre load entity reference fields into a node
Say I have three content types: Team member, Team and Matchday.

The team content type is made up of entity reference fields, which reference team members.

The Matchday content type should load team members from the Team content type automatically each time a new piece of content is created. Then the content editor should be able to delete people on each Matchday who don't show up, and also add members from other teams who are filling in.

Anyone know how to do this in Drupal 8, even just a general idea to point me in the right direction?

# Answer
> 0 votes
1. Add an entity reference field to team members content type.
2. Using form alter:
3. Hide the above field in the add form.
4. Add an entity reference render element that points to the team content type.
5. In the submit callback load all the team members that in the selected team and add them to the entity member field.

# Answer
> 0 votes
Another option would be to use the presave hook on Matchday to auto fill up the list of associated team members.

```
hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity)

```

This hook runs before the entity is created or updated, so you should check if the entity is new before adding the members.

You can read the doc on this hook at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_entity\_presave/8

---
Tags: 8, entities
---


title: Form / Block / Template

text:
# Question
Title: Form / Block / Template
I try to theme a custom form in my block.

Here my code :

> boutique.module

```
/**
 * Implements hook_theme().
 */
function boutique_theme() {

  return array(
        'ajout_panier_form'=> array(
            'render element' => 'form',
            'variables'=> array(
                'form'=> NULL,
            )
  )
  );
}

```

> AjoutPanierForm.php

```
/**
 * Class AjoutBlockForm.
 *
 * @package Drupal\boutique\Form
 */
class AjoutPanierForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ajout_panier_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

        $form['#attributes']['oninput']='showPoids.value = poids.value';

        $form['poids'] = array(
            '#type' => 'range',
            '#title' => $this->t('Poids en gramme'),
            '#min' => 500,
            '#max' => 20000,
            '#default_value' => 500,
            '#step' => 100,
            '#attributes'=>array('id'=>array('poids')),
            '#description' => $this->t(""),
            '#required' => TRUE,
        );

        $form['showPoids']=array(
            '#type'=>'markup',
            '#markup'=>'<output id="showPoids" for="poids">500</output>'

        );

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

      );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message('ok');

  }

```

> AjoutPanierBlock.php

```
/**
 * Provides a 'AjoutPanierBlock' block.
 *
 * @Block(
 *  id = "ajout_panier_block",
 *  admin_label = @Translation("Block Ajout panier"),
 * )
 */
class AjoutPanierBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm('Drupal\boutique\Form\AjoutPanierForm');

    $build = [
        '#theme' => 'ajout_panier_form',
        '#form' => $form,
  ];
    return $build;

  }

}

```

And my template :

> ajout-panier-form.html.twig

```
<form{{ attributes }}>
    {{ form.poids }} {{ form.showPoids }}
    {{ form.form_build_id }} {# required #}
    {{ form.form_id }} {# required #}
    {{ form.ajouter }}
    {{ children }}
</form>

```

My block call my template and my form is display. But my submit doesn't call my method in my form controller where i put a

```
drupal_set_message('ok');

```

How add the actions form into template ? i have put `{{ children }}` but he doesn't work like the balise `{{ form }}` alone.

# Answer
> 1 votes
If you want to theme a form, better override the `form.html.twig` template, because you don't know what happens in the background of this template and you don't want to do this all from scratch in your own template.

So put the complete form in the block:

```
public function build() {
  return \Drupal::formBuilder()->getForm('Drupal\boutique\Form\AjoutPanierForm');
}

```

And copy the `form.html.twig` in your template and change it.

# Answer
> 1 votes
You should be overriding form.html.twig, as the form template behaves differently from other templates. Take note that form.html.twig does not print the form element - leave that to Drupal so that the right actions and attributes are set.

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


title: Running asynchronous PHP code

text:
# Question
Title: Running asynchronous PHP code
I have Drupal server with a REST API using services and rest\_server (that's just background, I don't THINK that applies to this problem at all.) I'd like particular API calls to only report back that the request was received, but then go on to do further work in PHP.

To me, this seems like a thread/fork solution, but I can't seem to find a viable solution using PHP/Drupal. The first (and from the looks of it, easiest) thing I came across was the pcntl\_fork() function. But, as it looks like that's not viable:

> It is not possible to use the function 'pcntl\_fork' when PHP is used as Apache module. You can only use pcntl\_fork in CGI mode or from command-line.
>
> Using this function will result in: 'Fatal error: Call to undefined function: pcntl\_fork()'

(And, indeed, when I try using function\_exists() through command line, it's there, but when run in PHP through Drupal it says function is undefined. I'm reading some stuff on how to install it/recompile PHP with it, but would prefer if there were a method that didn't involve changes to the server.)

Other than that, I'm coming across solutions such as creating a queue to run with cron jobs, creating convoluted menu items, or a whole background processes... thing. All I want is for some arbitrary code to be run off on its own. Does anyone have a suggestion that they feel works best with with Drupal?

(Also, I don't know what to tag this as--I tried thread or asynchronous but those don't seem to exist--so feel free to tag.)

# Answer
> 2 votes
A request to a REST API should just return required data and end. If you want to do asynchronous tasks do not reuse request threads, use cron tasks.

If you want to get independent from Durpal cron use your own drush command executed by a system cron. So, you declare a drush command that makes whatever asyncrhonous tasks and then declare a system cron that runs drush on that command.

If you need to prepare data for that command (for example, if some REST API functions generates data that must be processed asynchronously) you can use Drupal Queues. When the API is called add a new element to a certain queue that will be later processed by the drush command.

# Answer
> 0 votes
You could use the background process module or HTTPRL module to run external http requests somewhat asynchronously.

https://www.drupal.org/project/background\_process

Or you could use a nodejs backend, and the Drupal Node.js Integration module, to achieve grater decoupling and asynchronous workload management.

https://www.drupal.org/project/nodejs

---
Tags: services
---


# Question
Title: How to hand over value of field 1 to class array of field 2 programmatically in .theme
### Motivation

Context between template variable arrays is an old problem already known in D6 and 7 on theming level. What about D8 now? Any light on the horizon? Any chance to make this avaible without using *Views module* tweaks and work arounds?

### Let's use an example:

Default standart content type **Article** has 4 input fields:

* label (title)
* body (main text area)
* image
* tags (terms, entity reference)

This content type also has an alternative *Manage Fields Display* setting for the *Teaser view mode*, where the image field formatter is set up using a smaller *Image Style* and with the option to link to the file or full node page. This creates an `<a>` element with url but without title or any other attributes around the Article image markup in Teaser view mode.

### The question:

How can I hand over e.g. the first value of the tags (input terms) programmatically to a classes array of the wrapping `<a>` element?

In `node--view--frontpage.html.twig` this ...

```
`<a href="#" class="image icon fa-{{ (content.field_tags['0']['#title']) }}">{{ content.field_image }}</a>`

```

... works. Sure, because we grab it from the page variable. But `image-formatter.html.twig` is deeper nested inside the whole template system and it would be an overload to have the whole page variable array available here. Of course it is not there.

### My assumption was to use the following preprocess functions:

* `function theme_preprocess_field(&$variables) {}` and or
* `function theme_preprocess_image_formatter(&$variables) {}`

### The problem:

It seems - even if `_preprocess_image_formatter` has been suggested in the twig comments of the `image-formatter.html.twig` \- there is 1.) no place to pass a string to any kind of *attributes* array for the `<a>` element in this twig file since the array has no given place for that. 2.) The hand over. How? Global vars are mostly not the best solution.

The core template code of `image-formatter.html.twig`:

```
{% if url %}
  <a href="{{ url }}">{{ image }}</a>
{% else %}
  {{ image }}
{% endif %}

```

The drafted alternation to demonstrate the needed effect:

```
{% if url %}
  <a href="{{ url }}"{{ some defined attributes }}>{{ image }}</a>
{% else %}
  {{ image }}
{% endif %}

```

NOTE: adding values manually and directly in the twig theme file like

```
<a href="{{ url }}" class="hallo-classes">{{ image }}</a>`

```

shows that this is the right twig template. But it seems there is no way to get other values handed over (here), since `_preprocess_image_formatter` $variables array doesn't know any values of other fields of course (like of **tags** term field). And `_preprocess_field()` doesn't reach the image formatter level so that an addition to the attributes array rather affects the surrounding div but not the `<a>` element.

# Answer
> 1 votes
> Context between template variable arrays is an old problem already known in D6 and 7 on theming level. What about D8 now? Any light on the horizon?

No, there is no light on the horizon, quite the contrary. Because of the concept of nested render elements, that are rendered independently. In D8 it is getting far more complicated because of the dynamic cache. And it wouldn't work at all with the plans for the future with placeholders and lazy building.

---
Tags: nodes, 8, theming
---


# Question
Title: What is the difference between "Language: Not specified" & "Language: Not applicable"?
What is the difference between *Language: Not specified* and *Language: Not applicable*?

There was no such distinction before Drupal 8.

I haven't found any documentation about this. It would be nice to have an explanation.

# Answer
**Not applicable** means that we *know* that the very concept of Human languages doesn't apply to this textual piece of content. A relevant example for such content would be Binary code.

For more see http://www.w3.org/International/questions/qa-no-language#nonlinguistic.

**Not specified** means we don't know if the text might or might not include human-language content.

For more see http://www.w3.org/International/questions/qa-no-language#undetermined.

(Both "see more" links are taken from the code documentation in `\Drupal\Core\Language\LanguageInterface` which explains those constants quite well).

Yes, it makes no difference to how content is displayed, but you could treat it differently on your site if you wanted (for example in a view or in custom code).
> 15 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Why is 'render element' sometime 'element' and sometime 'elements'?
I notice in Drupal source code, in core modules `hook_theme()`, some places are `'render element' => 'element'` and some places are `'render element' => 'elements'` (plural). Why? Even the render element purpose is to display a single object (e.g. node canonical), not a list of objects.

The problem is it results in different key in `$variables` in `template_preprocess_hook()`. For instance, I have a custom entity and if I use `_entity_view` in entity canonical route, the `$variables` has `'elements'`. But if I manually use this entity theme in a page, the `$variables` has `'element'`. I'm so confused.

# Answer
Because it wasn't standardized.

The safe approach is to check the info array for the render element key.

There is actually an issue with the field groups module that ignores everything but form & elements.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How do I check if the current password that the user gives in the password reset form matches with the hashed password?
I'm trying to reset a user password programmatically in Drupal 8 without the email link. For this the first step would be to check if the password(which is plain) that the user enters in the password reset form is matching with the hashed password of the respective user. And then save the new password.

Each time I hash the password, its giving a different value, this is because its salted. How shall I compare the password which the user enters in the form with the hashed password from the table.

This is the code that I have in my controller for checking the current password :

```
<?php
/**
* @file
* contains \Drupal\customer_profile\Controller\ProfileUpdateController
*/

 namespace Drupal\customer_profile\Controller;

 use Drupal\Core\Controller\ControllerBase;

 use Symfony\Component\HttpFoundation\JsonResponse;
 use Drupal\Core\Password\PhpassHashedPassword;
 use Drupal\Core\Password\PasswordInterface;

 class ProfileUpdateController extends ControllerBase {

   $user =\Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   $ret = \Drupal\Core\Password\PasswordInterface::check('secret', $user);
   //$user->setPassword('secret');
   //$pass = $user->save();

   $response->password = $ret;
   return new JsonResponse($response);
  }
 }

```

After using **\Drupal\Core\Password\PasswordInterface::check()** method, for comparing the plain text password with the hash password, I get this fatal error :

**Fatal error: Non-static method Drupal\Core\Password\PasswordInterface::check() cannot be called statically, assuming $this from incompatible context in C:\xampp\htdocs\ijarah\modules\custom\customer\_profile\src\Controller\ProfileUpdateController.php on line 725**

In Drupal 7 we have **user\_check\_password** to check the password with string and **user\_hash\_password** for hashing. How can I approach the same in Drupal 8.

Please help.

# Answer
Ok, the solution would be to use the Dependency Injection as suggested by @mradcliffe above and then use the check() method. Here is the code :

```
<?php
/**
* @file
* contains \Drupal\customer_profile\Controller\ProfileUpdateController
*/
namespace Drupal\customer_profile\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Password\PasswordInterface;

 class ProfileUpdateController extends ControllerBase implements ContainerInjectionInterface {

  public function __construct(PasswordInterface $password_hasher, AccountInterface $account) {
   $this->passwordHasher = $password_hasher;
   $this->account = $account;
  }

   public static function create(ContainerInterface $container) {
     return new static(
       $container->get('password'),
       $container->get('current_user')
     );
   }

   public function updatePassword() {
     //global $user;
     $response = new \stdClass();
      //check the plain password with the hashed password from db
     $pass = $this->passwordHasher->check('secret', 'hashed_password_from_db');

     $response->password = $pass;
     // this will return true if the password matches or false vice-versa
     return new JsonResponse($response);
   }
  }
   ?>

```

After checking the password, we can save the new password using

```
  $user = User::load(1);
  $user->setPassword('new_password_secret');
  $user->save();

```

Hope this helps others :)
> 3 votes

# Answer
The hash is different every time, that's by design, because it is salted.

If you want to change the password of a user, you don't have to hash it yourself. Just load the user, set the password and save.

```
$user = User::load(1);
$user->setPassword('secret');
$user->save();

```

For the fatal error that you mentioned before, @mradcliffe already had the answer in a comment of this (now deleted) answer:

> I think MigratePassword is overriding the default password service. You can try changing the constructor argument to be PasswordInterface instead of PhpassHashedPassword if the Drupal instance is using MigratePassword. Or disable migrate module.

*Always* type hint on the interface if an interface is available. Services might be switched out, like migrate is doing that for example.

To check the password, you just have to use the other method of that interface, `\Drupal\Core\Password\PasswordInterface::check()`. Those two methods are a direct match for `user_hash_password()` and `user_check_password()`
> 2 votes

# Answer
**Note that this answer is superceded by Berdir's answer. I initially removed it because it no longer answers the question, and did not want to confuse anyone. It is undeleted to use as an example of using dependency injection on a service and the hash method.**

The password service suggests that the argument for the constructor should be `16`. Additionally the minimum value is `7` and the maximum value is `30`. Anything outside of those ranges will return `FALSE` (on failure), which your code should really be checking to be secure.

In the following example, you would not need to worry about the constructor arguments. In this way your code is more portable if password hashing changes or someone installs a module that changes the password service.

```
class ProfileUpdateController extends ControllerBase implements ContainerInjectionInterface {

   public function __construct(PasswordInterface $password_hasher, AccountProxy $account) {
     $this->passwordHasher = $password_hasher;
     $this->account = $account;
   }

   public static function create(ContainerInterface $container) {
     return new static(
       $container->get('password'),
       $container->get('current_user')
     );
   }

   public function updatePassword() {
     $response = new \stdClass();
     $pass = $this->passwordHasher->hash('1234');
     if (!$password) {
        throw new \Exception('An error occurred.');
     }
     $response->password = $pass;
     return new JsonResponse($response);
   }
 }

```

Subjective comment: Drupal core does not return passwords as part of user objects in its Restful API because it does not consider that a secure approach.
> 1 votes

---
Tags: users, 8
---


# Question
Title: What is an allternatve approach to many fields in an entity?
I have an entity bundle 'A' that has about 30 fields in it. This is probably affecting the page load performance of any view requiring to load these entities.

As an alternative, I was thinking about putting a number of the entity fields in a separate entity bundle 'B' which is connects the entities to bundle 'A' with an entity referenc field.

Would that improve performance or is there a better solution.

# Answer
Like Clive said, testing would be the definitive answer. But if you look at the mysql queries that will have to be executed behind the scenes, I'm pretty sure you'd find that your bundle A with 30 fields will be simpler and faster than the bundle B option. You can use the Views Show Query module to output your view queries in both scenarios and compare them. In bundle B option, I'm pretty sure the mysql query will have to not only look up all of A's and B's fields but also look up the relationship between A and B bundles, an expensive additional JOIN.
> 3 votes

---
Tags: entities, performance
---


# Question
Title: Page scroll issue when using dropdown menu
I am using a view in this page, and using sexy exposed module for filter criteria. The page shows the horizontal scrollbar. How can I get rid of it?

# Answer
> 0 votes
You could hide it with CSS using `body { overflow-x: hidden; }`.

It would be better to figure out why the scroll is happening, but it's hard to troubleshoot that without having access to your site.

---
Tags: views, javascript
---