# Question
Title: Group module with advanced permissions based on taxonomy (preferrably)
I have a hard time figuring out which Drupal module to use for groups. There are quite a lot of options for Drupal 8 that provide useful functionality. So far I have looked (at various points in time) at the following modules:

* Group
* Organic Groups
* Taxonomy combined with Permissions by term
* Workbench+Workbench Access

The last two are the ones I tried latest. Workbench Access only allows editing access permissions to be regulated, not viewing. While the *Permission by term* module only allows viewing content, while not really regulating editing (except that when you don't have view access you can't edit either). I can't remember the *Organic groups* module very precisely anymore, but from what I (subjectively) gather from other posts/docs, the *Group* module is meant to be a better replacement. And that pushes me too much in a format with their groups pages and stuff.

What I am really looking for is to have roles, where each role represents a department of my organization. On the other hand we have content that I want to be able to assign to a department, but also specify whether that content should be only accessible to department members only (separately for view and edit), or potentially for all authenticated users, or even anonymous users. The access permissions should be different for each individual node, not on a content type basis. And additionally users should only be able to create content for their own department.

I got there almost with permission by term and taxonomy, where the "access level" vocabulary specifies who can access the node (and taxonomy terms that a user doesn't have access to are automatically hidden), while the "department" vocabulary determines which department a node should be listed under. Views and display suite fill in the rest.

But as I said, this doesn't allow me to control edit permissions for nodes, only view permissions. I could potentially combine this with workbench access to organize the edit permissions, but somehow this feels to me like looking for trouble with combining different permission modules.

Does anyone have a recommendation for a setup that allows me to arrange editing and viewing of nodes per "department" and on a per-node basis?

# Answer
You should really give the Group module a try, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

It creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

# Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

```
Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 1            ! Class      ! 5             ! Alumni
 2            ! Customers  ! 6             ! Lead
 2            ! Customers  ! 7             ! Prospect
 2            ! Customers  ! 8             ! Licensed Customer
 2            ! Customers  ! 9             ! Sales
 2            ! Customers  ! 10            ! Support
 2            ! Customers  ! 11            ! Accounting
 2            ! Customers  ! 12            ! R&D
 3            ! Project    ! 13            ! Project Manager
 3            ! Project    ! 14            ! Developer
 3            ! Project    ! 15            ! Customer

```

### Group Types

The above example consists of 3 ***group types***:

* Class.
* Customers.
* Project.

### Group Roles

For each of the 3 group types, there are specific ***Roles*** defined, some more details about some of them:

* for the *Class* group, these are the 3 roles that are configured:
    + Instructor.
    + Student.
    + Alumni.
* for the *Project* group, these are the 3 roles that are configured:
    + Project Manager.
    + Developer.
    + Customer.

These roles can be configured per Group type and will only be available on groups of that group type. As an example, for group type "*Class*", the defined roles are **Instructor**, **Student** and **Alumni** (which are not available for the other group types).

On top of the group specific roles, there are also *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. 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.

### Groups

Each of the configured group types can have any number of ***Groups***.

Examples of groups:

* for the *Class* group type, there could be these **Groups**:
    + Getting started with Drupal.
    + Drupal for site builders.
    + Become an expert in using the Rules module.
* for the *Customers* group type, there could be these **Groups**:
    + Service Requests.
    + Order Processing.
    + Sales Orders.
    + Relationship Management.

### Permissions

For each of the configured group types, you can then also configure for each ***Content Type*** which ***Role*** has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

# Addressing your specific questions

Here is a possible recipe to get you going:

* You'd only need 1 group type, say labeled "Departments".
* Define whatever Group Roles you'd need for this Group Type and configure the desired Group permissions for each of those roles.
* Creating Groups like Department A, Department B, Etc.
* Make each user a member of the appropriate group (could be 1 or more, depends on your needs).
* Assign each node to the appropriate group.

# Further refinements using some other modules

## Additional permissions per node

Providing additional view permissions for specific nodes to "Outsiders" (not member of a group) can be provided by the Permission by terms module.

This can by achieved by creating a Taxonomy Term reference field on nodes which points to a vocabulary "Additional Permissions" with terms "public" and "intranet users". Those terms get permissions assigned to them for respectively the "Anonymous Users" and "Authenticated Users" roles. When you set the field on a node to either of those values, users of the respective roles get view permissions, irrespective of the group view permissions. Nodes that don't have a value for the term reference field just get the group permissions by default. Edit permissions are not affected by this and are just defined by the group roles/permissions.

## Changing the Group page layout

If you don't like the default way the group pages look like, you can modify them by using the page manager, together with panelizer and bootstrap\_kit for instance. Together with views (using the "Group content" and "Content from group content" relationships optionally) gives you tremendous flexibility over how the group page is displayed.

# Comparison with the Organic groups module

Have a look at my answer to "What are the features of the Group module versus Organic Group module?" for details about:

* How both modules (Group versus Organic groups) compare to each other.
* Integration with various modules that you might want to take advantage of also.

# Resources
> 4 votes

---
Tags: 8
---


# Question
Title: How to eMail a periodic summary of flagged nodes to users of some role?
I'd like to create a periodic summary email that gets sent to a specific role.

The summary email would include things such as:

1. flagged content / users
2. count new users
3. count new nodes
4. most viewed content
5. flagged content / users

Item #1 is really the main goal - instead of send an email each time a user flags a user or node, I'd like to send a daily summary of all of the flagged entities.

How would you approach this?

# Answer
Assuming you think of creating a view for such flagged content / users for (say) "current day", there is a solution to do what you're asking about. This solution uses the Rules, Views and Views Rules module, as further detailed below.

### 1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

> ... provides two types of elements in Rules, configured with a "Rules" view display:
>
> * **Views loop**: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.
> * **Collect view result rows (action)**: This action collects each variable in all view result rows into list variables for use in Rules.
>
> ***Tip***: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

### 2. Create a view of display type 'Rules'

After you enable the Views Rules module, use Views to create a view of your "\* flagged content / users\*" (as in your question). Add of view of display type ***`Rules`*** (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

### 3. Create a Rule Component using the view of display type 'Rules'

Create a Rules Component, using these guidelines:

* Add whatever Rules Conditions you might want (if any).
* Some Rules Actions you'll need to create (add) for sure:
    + **`Create a variable`**, with no initial value, say you name it "eMail Summary" (machine name `email_summary`), which will be used in subsequent Rules Actions.
    + **`Add a Views loop`** (by using the link that says `Add view loop`), and select the "Rules" display created in the previous step. Configure the parameters and variable names. And for each views result contained in your Views loop (about some "flagged content / user", as in your question), perform a Rules Action like **`Set a data value`**, for the `email_summary` variable from the previous Rules Action. The actual value to be assigned, is the previous value of `email_summary`, to which you append the desired data about the Views result being processed. For this you can use the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).
    + Add a Rules Action to **`Send an eMail to a selected role`** (as per your "periodic summary email that gets sent to a specific role"), whereas for the body of that eMail you simply use the value of the `email_summary` variable.

If you're not familiar enough with Rules to create and populate that `email_summary` variable, you may want to have a look at the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?", in which a similar variable is used.

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

### 4. Schedule the Rules Component for daily execution

Make sure you have the "Rules scheduler" enabled (a sub-module of Rules).

Improve your Rules Component from the previous step, by adding a Rules Action (as the last action to be performed) to **`Schedule a Rules Component`**, whereas the actual Rules Component to be scheduled is the Rules Component itself. You want it to be scheduled in "1 day from now" (to make it happen daily).

To execute this Rules Component the very first time, just execute your Rules Component "manually". To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

Assuming your QA-testing succeeded, and assuming your cron jobs are running also, the eMail should get created next time cron runs (after an amount of time, depending on the amount of time you configured in your Rules Component to get it rescheduled).

PS: The above addresses "Item #1" of your question, though it should be pretty forward to use a similar approach for the other items in your question.
> 1 votes

---
Tags: 7, emails, flags
---


# Question
Title: Create module My product/list of user drupal commerce
I'm trying to determine if a user have product any of them, loading all the user products related and node title and body and antoher fields... Anyone know if such a function exists, or if there's a more elegant method to get this data? My module code is here ...

```
<?php
    /**
    /**
    * Implements hook_menu().
    */
    function my_product_bijan_menu() {
    $items = array();

    $items['my_module/hello_world'] = array(
    'title' => 'List my Products',
    'page callback' => 'my_products_fnc',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );

    return $items;
    }

    function my_products_fnc() {

    $ordered = FALSE;

    $node_wrapper = entity_metadata_wrapper('node', $node);
    $product_ids = array();
    foreach ($node_wrapper->field_products as $product) {
    $product_ids[] = $product->product_id->value();
    }

    // Query order details for products
    // Note this is the line item product reference table
    $query = db_select('field_data_commerce_product', 'p');
    // Example if you want more fields, but would need to change ->fetchCol()
    // $query->fields('o', array('order_id', 'order_number', 'uid', 'mail'));
    $query->fields('o', array('uid'));
    $query->innerJoin('field_data_commerce_line_items', 'l', 'l.commerce_line_items_line_item_id = p.entity_id');
    $query->innerJoin('commerce_order', 'o', 'o.order_id = l.entity_id');
    $query->condition('p.commerce_product_product_id', $product_ids, 'IN');
    $query->groupBy('o.order_id');
    // Fetch array of uids
    $result = $query->execute()->fetchCol();

    // Check if account->uid in array of order uids
    // If so, uid has ordered product.
    if(in_array($account->uid, $result)){
    $ordered = TRUE;
    }

}

```

And error is :

```
    Notice: Undefined variable: node in my_products_fnc() (line 25 of /home/admin/domains/site.com/public_html/sites/all/modules/my_product_bijan/my_product_bijan.module).
    EntityMetadataWrapperException: Unknown data property field_products. in EntityStructureWrapper->getPropertyInfo() (line 354 of /home/admin/domains/site.com/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).

```

# Answer
> 0 votes
My query is there but i dont know why not work !

```
global $user;
$query = db_select('{node}', 'node');
$query->fields('node', array('nid', 'changed', 'created', 'title', 'status'));
$query->fields('users_node', array('uid', 'mail'));
$query->fields('commerce_node_checkout_node_node', array('line_item_id', 'changed'));
$query->fields('node_counter', array('totalcount'));
$query->leftJoin('{users}', 'users_node', 'node.uid = users_node.uid');
$query->leftJoin('{field_data_commerce_node_checkout_node}', 'field_data_commerce_node_checkout_node', 'node.nid = field_data_commerce_node_checkout_node.commerce_node_checkout_node_target_id AND (field_data_commerce_node_checkout_node.entity_type = 'commerce_line_item' AND field_data_commerce_node_checkout_node.deleted = '0')');
$query->leftJoin('{commerce_line_item}', 'commerce_node_checkout_node_node', 'field_data_commerce_node_checkout_node.entity_id = commerce_node_checkout_node_node.line_item_id');
$query->leftJoin('{node_counter}', 'node_counter', 'node.nid = node_counter.nid');
$query->innerJoin('{node_comment_statistics}', 'node_comment_statistics', 'node.nid = node_comment_statistics.nid');
$query->condition('node.uid', $user->uid);
$query->condition('node.type', array(myitem), 'IN');
$result = $query->execute();

```

---
Tags: commerce, hooks
---


title: Where is archive-dump for Drush 9?

text:
# Question
Title: Where is archive-dump for Drush 9?
I have drush 9 installed (current dev release). I can't find the archive-dump command, despite the docs suggesting it should be there.

Executing it produces:

> The Drush command 'archive-dump' could not be found. Use 'drush core-status' to verify that Drupal is found and bootstrapped successfully. Look for 'Drupal bootstrap : Successful' in its output.

I can confirm that `drush core-status` (or `status`) states that Drupal is successfully bootstrapped. The problem is present for local and remote environments, and on any machine that it's installed on (I've tried 4 so far, a mix of MacOS and Ubuntu environments).

I've even gone so far as to grep drush's code for mentions of *archive* and *ard* (the alias that used to work and also should if the docs are to be believed. There doesn't seem to be anything pertinent in there.

So where's archive-dump gone?? If it's been removed, what's its successor?

# Answer
Turns out it was removed in this commit to Drush 9 following this issue and follow up.

So archiving no longer exists, or at least not until someone has time to port the logic over to the Composer workflow.
> 13 votes

---
Tags: drush
---


# Question
Title: How to find where Drush is installed to include a file in my module?
I have installed the module Drush Help to see the module's Drush commands in the module help page. But when I go to see the help page of a module that use in the drush commands drush constants like DRUSH\_BOOTSTRAP\_DRUPAL\_FULL I got a Notice because this constant is only defined in drush, and not for Drupal.

You can see this problem if you install the Drush Help and the Node Revision Delete modules (the Drupal 7 version): Visit `admin/help/node_revision_delete` and you will see this notice message.

> Notice: Use of undefined constant DRUSH\_BOOTSTRAP\_DRUPAL\_FULL - assumed 'DRUSH\_BOOTSTRAP\_DRUPAL\_FULL' in node\_revision\_delete\_drush\_command()

So the problem is that Drupal can't reach the file includes/bootstrap.inc where the constant is defined. I can include the file but the problem is that I need to know where Drush is installed.

How to find where Drush is installed to include a file in my module?

# Answer
A temporary solution that I found is define the same constants in the drush\_help.module file.

```
/**
 * Constants defined by drush in the includes/bootstrap.inc file.
 *
 * To see why we need to do this please read:
 * https://drupal.stackexchange.com/q/250786/28275
 */
define('DRUSH_BOOTSTRAP_NONE', -1);
define('DRUSH_BOOTSTRAP_MAX', -2);
define('DRUSH_BOOTSTRAP_DRUSH', 0);
define('DRUSH_BOOTSTRAP_DRUPAL_ROOT', 1);
define('DRUSH_BOOTSTRAP_DRUPAL_SITE', 2);
define('DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION', 3);
define('DRUSH_BOOTSTRAP_DRUPAL_DATABASE', 4);
define('DRUSH_BOOTSTRAP_DRUPAL_FULL', 5);
define('DRUSH_BOOTSTRAP_DRUPAL_LOGIN', 6);

```
> 1 votes

---
Tags: drush
---


# Question
Title: How do I get the mock of the current user?
I'm trying to get a mock of current user.

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

```

For this, I extend `UnitTestCase` class and load the `User` class methods.

```
$methods = get_class_methods('\Drupal\user\Entity\User');

```

Since `load()` is a `User` class method, I have created a mock of the `User` class, disabled its constructor, and set all methods of this class, including `load()` which is the method I actually need.

```
$user = $this->getMockBuilder('\Drupal\user\Entity\User')
  ->disableOriginalConstructor()
  ->setMethods($methods)
  ->getMock();

```

Since the method is set now, I'm trying to call this method once and not sure what it will return exactly.

```
$user->expects($this->once())
  ->method('load')
  ->will($this->returnValue('admin'));

```

Now, while running this test, I got an error.

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "entity.manager".

What's the need of injecting the *entity.manager* service?

Although `load()` is a method of the entity storage interface, it also exists in the `User` class.
Why does this error come up?

Can I load the current user without mocking the *entity.manager* class?

The actual method for which I'm doing unit testing is the following.

```
public static function get_ctype_field_value($field) {
  $user = user_load(\Drupal::currentUser()->id());
  $ulm = get_type_id($user);
  $local_market = \Drupal\node\Entity\Node::load($ulm);
  $llf = '';
  if ($local_market) {
    // Get the field value from the LM.
    if ($local_market->hasField($field)) {
      $localmarket_field = $local_market->$field->value;
    }
  }
  return $localmarket_field;
}

```

# Answer
> 3 votes
In Drupal, unit tests (`UnitTestCase` or `\PHPUnit_Framework_TestCase`, sometimes) are really best when you have a class that doesn't have a lot of dependencies or when you can really predict what the dependencies do so you can mock them. Typically, you mock individual methods, and not try to do everything. When you find yourself mocking too much, or with complicated mocks, it is best to rework your test as a kernel test (`KernelTestBase` or KTB for short).

A KTB will boot a minimal Drupal environment, and then you can enable modules and choose which config and schema you want installed (enabling the module doesn't automatically do this). These are still PhpUnit tests, so you can run that that way and have full access to providers and other PhpUnit features. Many modules in core also define extensions of KTB to provide setup and additional features (eg, `EntityKernelTestBase` and `ViewsKernelTestBase`).

KTB tests are not as fast as UTC tests, but still quick and not as slow as functional tests (`BrowserTestBase`). Core has tons of examples.

In your case, since it seems like you need users and nodes, you really want a KTB. Since both are entities, there is really a lot you would need to mock and you will go down the rabbit hole quickly trying to do this because of the dependencies.

See also Types of tests in Drupal 8.

A few answers to your specific questions.

Users are content entities (so are nodes), which use a lot of services. And, they aren't all properly injected (the base `Entity` class uses a lot of helper methods that access the global `\Drupal` class to get services). In addition EntityManager is deprecated and got broken up in different services; so a lot of its methods are really helper functions for the other services. To to a UTC, you would have to start mock these helper functions. I do not think there is a way around this.

Based off your test snippet, you are really best starting off with a KTB.

---
Tags: entities, testing
---


# Question
Title: How to use cron to delete nodes of a content type that does not allow deletion by anonymous users
The background for this question is here: Delete nodes using Rules and VBO

Summary: a VBO View selects various nodes of a particular content type. A Rules Action Set is instructed to load this VBO View, loop through the entity objects, and delete them. A Rule runs/is triggered on cron and has this Action Set for its action. So, when cron runs the selected nodes should be deleted.

However, the nodes are not deleted, because cron runs as the Anonymous User (uid=0), and the content type is configured such that anonymous users are not allowed to delete nodes of this content type.

How can this be solved so that the nodes are deleted on cron?

Giving anonymous users permission to delete nodes of this content type is not a good solution on this site.

Presumably, cron runs as Anonymous User (uid=0) for security reasons. Any acceptable solution should not undermine the site's security.

A programmatic solution (e.g. code in a custom module) is certainly acceptable if a "code-less" solution using Rules is not possible.

# Answer
> 3 votes
Not sure if you want to consider using it, but the Rules switch user module might be an acceptable compromise. Some details about it (from its project page):

> This module adds two new Rules actions:
>
> * Switch to another user
> * Switch back from another user
>
> These actions could be useful when you have an operation that you want an unprivileged user to use but it fails because the user doesn't have sufficient permissions.

Refer to the image on its project page to get the big picture. So if you'd add these 2 Rules Actions at the start / end of your list of existing Rules Actions, and you'd use some user id that does have the right permission, it *should* work.

As an alternative you could just reuse the relevant code (it's only 76 lines ...) to create your own custom Rules Actions. Similar to what you wrote in your question (= "\**...code in a custom module..."). If you make any useful improvements, please consider contributing your changes back to the module's issue queue.

Be aware, however, that this module only has a `DEV` version for D7 (= not covered by Drupal’s security advisory policy!). This doesn't mean that the module/code is dangerous to use/reference, but it does mean that the code has not been vetted by the Drupal security team.

# Answer
> 1 votes
Here's another way to do this.

* Create a new role and give it permission to delete the content type you want to delete.
* Create a user of this type and give it the role.
* Create a custom rules action that logs in as that user and then deletes the node.
* Call that action in VBO.

# Answer
> 0 votes
**EDIT:** You probably shouldn't use this approach, but I'm leaving it here as an example of what you might think is a good idea but actually isn't.

My memory is a little hazy, but I'm pretty sure I did something similar a few years ago.

* Give anonymous users permission to delete the node.
* Use `hook_form_alter()` to remove the "delete" button from the node form.

This approach is dangerous in that the user can modify the URL to delete the node by adding `/delete` on the end, but if your users aren't particularly sophisticated hiding the delete button may be enough.

---
Tags: 7, rules, cron, views
---


# Question
Title: How to hide Authoring information,Revision information,Publishing options tabs in create/edit node for any content type
I am trying to hide Authoring information, Revision information, Publishing options tabs in create/edit node for any content type. I tried different modules with no luck. Please give me suggestions how to achieve this. Thanks a lot

# Answer
To hide the individual options, you can use the following code in your module\_form\_alter() function:

```
$form['revision_information']['#access'] = FALSE;
$form['author']['#access'] = FALSE;
$form['options']['#access'] = FALSE;

```
> 6 votes

# Answer
I usually do this with a custom module and drupal's Form API and setting `#access = FALSE` for form elements I want to hide (and test it with 3rd party modules to assure it doesnt break anything).

Recently, I've been made aware of Override Node Options which does exactly this for Drupal 7/6.
> 5 votes

# Answer
AFAIK, Override Node Options can't disable those options, it just can enable them for users that otherwise don't have needed permissions.

There is Jammer module for removing unneeded elements from display.
> 4 votes

# Answer
I wrote this code which work for me

```
function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  dsm($form_id);
  if ( $form_id == 'FORM_ID'){
    $form['additional_settings']['#access'] = false;
  }
  return $form;
}

```
> 3 votes

# Answer
In Drupal 8, there's a core issue to make the revision fields configurable. Please help with that if possible, or use the Hide Revision Field module if not.
> 0 votes

---
Tags: nodes
---


# Question
Title: Get node in custom token to be used in Pathauto url alias pattern
I'm attempting to use a custom made token for url alias patterns. I've been able to custom tokens using node information just fine. But it just occurred to me that I don't know how I could possibly use it with url alias patterns.

```
function mymodule_plugins_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mymodule_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_nid':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->id() : 'This is a test';
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

```

It works fine if I'm using it on a node page. But what if I want to use it in a url alias pattern in the pathauto module?

```
$node = \Drupal::routeMatch()->getParameter('node');

```

I know here it gets the node based on the current page it's on. But if it's used in a url alias pattern it's not on any page at the time of url alias construction. I have a feeling this is possible since there are already tokens like \[node:title\] that work. Also is there any weird thing I can do like this?

`[mymodule_tokens:current_nid[node:nid]]`

Where I pass a token within a token? And if I can how would I access that extra parameter within my custom token. (p.s. I understand that my example is just getting the current\_nid and that there are already tokens for it. I'm just using that as an example)

Is there anyway I can get the node from my custom token to be used in a url alias pattern?

# Answer
> 1 votes
You get the node from $data:

```
  if (!empty($data['node'])) {
    /* @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
  }

```

It is the responsibility of the code which calls replace() to provide the correct context (in case of Pathauto the node for which it's building the alias).

---
Tags: 8, tokens
---


# Question
Title: How do I redirect a user on registration to a specific node?
I want to redirect a user when they log in to `node/2`. In Drupal 7, this is just `drupal_goto()`, but that was removed from 8. This is what I tried:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form_state->setRedirect('node/2');
}

```

I'm not getting an error but I'm not getting redirected, either.

EDIT: Then, based on Berdir's comments, I tried this:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'mymodule_user_register_submit_handler';
}

function mymodule_user_register_submit_handler($form, &$form_state) {
  $form_state->setRedirect('entity.node.canonical', ['node' => 2]);
}

```

However, this gives me an integrity error:

```
Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '16-0-0-ja' for key 'PRIMARY': INSERT INTO {user__field_agree} (entity_id, revision_id, bundle, delta, langcode, field_agree_value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 16 [:db_insert_placeholder_1] => 16 [:db_insert_placeholder_2] => user [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => ja [:db_insert_placeholder_5] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 757 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Drupal\Core\Database\Statement->execute(Array, Array)
Drupal\Core\Database\Connection->query('INSERT INTO {user__field_agree} (entity_id, revision_id, bundle, delta, langcode, field_agree_value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5)', Array, Array)
Drupal\Core\Database\Driver\mysql\Connection->query('INSERT INTO {user__field_agree} (entity_id, revision_id, bundle, delta, langcode, field_agree_value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5)', Array, Array)
Drupal\Core\Database\Driver\mysql\Insert->execute()
Drupal\Core\Entity\Sql\SqlContentEntityStorage->saveToDedicatedTables(Object, , Array)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->doSaveFieldItems(Object, Array)
Drupal\user\UserStorage->doSaveFieldItems(Object)
Drupal\Core\Entity\ContentEntityStorageBase->doSave(NULL, Object)
Drupal\Core\Entity\EntityStorageBase->save(Object)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object)
Drupal\Core\Entity\Entity->save()
Drupal\user\RegisterForm->save(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object)
Drupal\Core\Form\FormBuilder->processForm('user_register_form', Array, Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

```

# Answer
Redirection can be set in a submit handler.

```
function mymodule_user_register_submit_handler($form, &$form_state) {
  $form_state->setRedirect('entity.node.canonical', ['node' => 2]);
}

```

But the new submit handler should be appended to the submit button's '#submit' value, not the form's root '#submit'.

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_user_register_submit_handler';
}

```
> 3 votes

# Answer
So like you I tried Berdir's answer in about every different way possible. For some reason the using the mymodule\_form\_user\_register\_form\_alter hook did not work, but the mymodule\_form\_alter hook with a conditional did like:

```
function mymodule_user_register_custom_submit_handler($form,
FormStateInterface $form_state) {
    $form_state->setRedirect('entity.node.canonical', ['node' => 1]);
}
function mymodule_form_alter(array &$form, FormStateInterface $form_state,
$form_id) {
  if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#submit'][] = 'mymodule_user_register_custom_submit_handler';
  }
}

```
> 2 votes

# Answer
You can't use setRedirect() in form alter, that hasn't changed compared to Drupal 7. That would send the user away *while* building/displaying the form.

Just like in Drupal 7, you need to add an additional submit callback and then set the redirect *there*.

Also note that that setRedirect() expects a route name and arguments, not a path. In your case, that would be `$form_state->setRedirect('entity.node.canonical', ['node' => 2]));` or `$form_state->setRedirectUrl($node->toUrl())`.
> 1 votes

---
Tags: 8, users, redirection
---


title: Price higher that I have set

text:
# Question
Title: Price higher that I have set
I set the price of a drupal commerce product in 17 euros with "Include tax in this price" of VAT 10%. But I don't understand why when I view the display product I saw 21,39 euros.

I've looked at the "Manage display" of this product type. The Price field is formatted as "Formatted amount" and chosen "Display the calculated sell price for the current user.". If I change the format to the other option "Display the original price as loaded." when I see the display product node appears the price as 17 euros.

I don't understand where it's changing the price and how can I can configure.

Where, in the configuration, can I avoid this price change ?

# Answer
> 0 votes
This just means you have some product pricing rule or promotion enabled on the site that raises the price by that amount. It's unrelated to your tax setting. This is why you only see the high price when you use a display formatter that calculates the price prior to display.

There's no way for anyone to diagnose this for you without access to your site. You should just start by looking at **Administration \> Store \> Configuration \> Product pricing rules** to see what pricing rules are active and how they're manipulating prices.

---
Tags: commerce
---


# Question
Title: Is there a way to show Product Attributes if it only has one value?
I have products in my shop with the attribute "language". If more than one language attribute was set, the language field is displayed in the product view as it should. But if the product has only one language attribute, the field is hidden. Is there a way to always display the field, even if only one value was set?

# Answer
You didn't specify if you're using Drupal 7 or Drupal 8. In Drupal 7, our **Add to Cart form** display formatter has an option to "Show attribute widgets even if the Add to Cart form only represents one product." You can find this by clicking the configuration gear for the formatter in your **Manage Display** settings for the node type you use for product displays.
> 0 votes

---
Tags: commerce
---


title: Hide a view if there are no results

text:
# Question
Title: Hide a view if there are no results
*(Spin-off of Remove/Hide the block if the View is empty?. I find the other question a bit confusing, and want to reduce it to the essential question.)*

When rendering a view programmatically, and there are no results, there is still some HTML returned from `$view->render()`.

This can be desirable in the following cases:

* There is a "No results behavior".
* There are exposed filters, which need to be shown independent of the view result.
* The view is using AJAX, so it could happen that new content appears dynamically.
* Perhaps other reasons?

I want to write generic code that renders a view, but completely hides it if there are no results, and no other reason to show it.

So far I have this:

```
$view = \views_get_view($view_name);
if (NULL === $view) {
  return [];
}
$success = $view->set_display($display_id);
if (FALSE === $success) {
  return [];
}
$view->set_arguments($args);
// See https://www.drupal.org/node/525592#comment-1833824
$view->override_path = $_GET['q'];

$view->pre_execute();
$view->execute();

if (empty($view->result) && empty($view->empty)) {
  // @todo Also check for exposed filters!
  return [];
}

$markup = $view->render();

$view->post_execute();

if (FALSE === $markup) {
  return [];
}
return ['#markup' => $markup];

```

So the question is: Which other checks should I add when looking if the view is empty? (the place with the @todo).

How do I check if there are exposed filters? Which other criteria are relevant?

# Answer
Considering how many criteria might have to be considered to determine if a view can be hidden, I decided to make this a configuration option instead.

I see two ways to do this:

* The component where the view is embedded can have a configuration option "Hide view if no results". This is what I went with.
* One could make a symbolic views plugin for "no results behavior", named "Hide view if no results". Then one could implement e.g. `hook_preprocess_views_view()`, or possibly another hook, to hide the view if the new no results behavior is present.

I could write a lot more details, but for now I want to share the ideas behind these options, maybe this already helps.

I am marking this as the accepted answer. But if someone can come up with something more convincing, I will change it.
> 0 votes

# Answer
You can try to use such construction

```
if (count(views_get_view_result('view_name', 'display_name'))){
  $markup = views_embed_view('view_name', 'display_name');
}else{
  $markup = "";
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Drupal 8.4 Bartik theme on internet explorer 11
I have finished my site on localhost and it displays fine, on all browsers. When launching to server it shows fine in firefox, chrome, etc.

In Internet Explorer 11 however there are render issues. it just shows it all down one side.( left hand side).

I have tried the compatability method as described for the 7xcore and Microsoft. IE: I have added the site to the compatability list. Cleared all the history and the drupal cache but it has made no difference.

Site still shows as if no CSS is being invoked.

Many thanks Allen

# Answer
SORTED IT. in configuration. UNCHECK:- Aggregate CSS files UNCHECK:- Aggregate JavaScript files Now displays correctly.
> 0 votes

---
Tags: theming
---


# Question
Title: How do I increase the number of characters accepted by MySQL?
This is how I've defined the `content_body` in my `FieldWidget`:

```
$widget['content_body'] = array(
  '#title' => $this->t('Body text'),
  '#type' => 'textarea',
  '#default_value' => isset($items[$delta]) ? $items[$delta]->content_body : '',
);

```

which allows me to enter more than 255 characters when editing/creating the content. However, I get an error when more than 255 characters are entered and the content is created/updated.

This is the schema in my `FieldType` class:

```
$schema['columns']['content_body'] = array(
  'type' => 'text',
  'size' => 'tiny',
  'not null' => FALSE,
);

```

# Answer
Use field type as `Text (formatted, long) or Text (formatted, long, with summary)`
> 2 votes

---
Tags: 8, database
---


# Question
Title: How do I invoke JavaScript in AjaxResponse?
I'm submitting a form via AJAX.

```
$response = new AjaxResponse();

```

It's not using the Drupal default dialog, so I can't use `$response->addCommand(new CloseModalDialogCommand());` after all validation is done. It's using jQuery Modal.

Validation is working fine. After all things done I want to execute Javascript in `submitForm` function.

Which function should I use? I need to check for example `alert(1)`.

I have to close window using Javascript & Alert message as well. I tried `AlertCommand` but not working.

Following this example: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21InvokeCommand.php/class/InvokeCommand/8.2.x But not working

I have below code

**modules/demo\_test/src/Form/DemoTestForm.php**

```
namespace Drupal\demo_test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;

class DemoTestForm extends FormBase {

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

    $form['#prefix'] = '<div id="demo-test--modal-form">';
    $form['#suffix'] = '</div>';

    $form['firstname'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First name'),
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#name' =>'submit',
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        'callback' => '::ajaxSubmitForm',
        'event' => 'click',
      ],
    ];

    $form['#attached']['library'][] = 'demo_test/demo';

    return $form;
  }

  public function ajaxSubmitForm(array &$form, FormStateInterface $form_state) {
    drupal_get_messages();

    $response = new AjaxResponse();
    if ($form_state->getErrors()) {
      unset($form['#prefix']);
      unset($form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response->addCommand(new HtmlCommand('#demo-test-modal-form', $form));
    }
    return $response;
  }

  public function getFormId() {
    return 'demo_test_form';
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new InvokeCommand('html', 'trigger', array(
      'triggerName',
      array(
        'foo' => 'bar',
      ),
    )));
    return $response;
  }
}

```

**modules/demo\_test/js/demo.js**

```
(function ($, Drupal) {

  'use strict';

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

      $(document).on('triggerName', function(e, data) {
        alert('data.foo'); // alerts string 'bar'
      });
    }
  };

})(jQuery, Drupal);

jQuery(document).on('triggerName', function(e, data) {
    alert(1);
    alert('data.foo'); // alerts string 'bar'
});

```

It's not going in JS file & alert. JS file is loading fine.

# Answer
> 4 votes
Best way is probably to add your own custom command :

```
<?php
namespace Drupal\demo_test\Ajax;
use Drupal\Core\Ajax\CommandInterface;
class DemoTestJsCommand implements CommandInterface
{
    public function render(){
        return [
            'command' => 'demoTestJsCommand',
        ];
    }

}

```

And JS :

```
Drupal.AjaxCommands.prototype.demoTestJsCommand = function (ajax, response) {
    alert(1);
};

```

Then, you just have to add

```
$response->addCommand(new DemoTestJsCommand());

```

in you form's response.

---
Tags: 8
---


# Question
Title: Include php file as contents of field #markup?
I've got a form with a `#markup` element and I'm trying to use a php file as the contents of the markup. The following is printing a 1 where the markup should goes, and printing the contents of the file as the first elements in my page's body tag.

```
$path = drupal_get_path('theme', 'my_subtheme');
$template = "$path/templates/myfile.php";
$form['membership_info'] = array(
  '#markup' => include $template,
  '#weight' => 0,
);

```

I understand that the include line is probably including the file at the top of the page, and the markup is rendering as 1 because `include $template` is returning true, I'm just not sure how to get my desired outcome. Any ideas as to how I can get it to render how I'm expecting it to?

I was using a custom template for the entire form but that was stopping it from submitting. As such I'm instead trying to work my way around it by using this markup element to contain all of the non-form-field logic at the top of my form.

# Answer
Considering myfile.php contains html :

```
$template = file_get_contents("$path/templates/myfile.php");
$form['membership_info'] = array(
  '#markup' => $template,
  '#weight' => 0,
);

```

If you are using variables in myfiles.php, use ob\_start() & ob\_end\_flush() to get its content.

Read this, what you are trying to do is not really in agrement with drupal philosophy (probably reason of someone's downvote). It looks quiet strange to do includes while drupal 7 offers many ways to do this differently.
> 0 votes

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


# Question
Title: How do I query for content that has not been updated (no revisions)?
I am creating an API endpoint that serves as a content Feed that pulls in content according to some rules.

One group of content that I want to pull is articles that have been updated *and* that have been approved to be included in the feed. My approach for this was to include a boolean field for including it in the feed, and query for the number of revisions.

```
$firstGroup = $query->andConditionGroup()
    ->condition('type', ['article', 'video_game'], 'IN')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('field_include_in_feed', 1)
    ->condition('revision_uid', '1', '>=');

$nids = $query->condition($firstGroup)->condition($secondGroup)->execute();

```

Based on this page from the documentation, I thought `revision_uid` would be a valid field, but I get an error that it is not. Likewise I get an error, if I use `revision` as well.

The error is a Drupal `QueryException` with the message `'revision_uid' not found`.

What is the best way to query for content (with `entityQuery`) that has been updated if I can't use the `revision` fields?

# Answer
Content that has not been updated would only have one revision, so you could count the number of revisions and use a having condition.

First you'll have to join the `node_revision` table to the `node` table

```
$query->leftJoin('node_revision', 'r', 'n.nid = r.nid');

```

Count the number of revisions

```
$query->addExpression('COUNT(n.nid)', 'revision_count');

```

Filter rows with a revision\_count higher than 1

```
$query->havingCondition('revision_count', 1, '<=');

```
> 1 votes

# Answer
Every entity stores a timestamp for when the node was created, as well as another for when the node was last updated. So, ideally, you could add a condition to your EntityQuery checking to see if the `created` value matches the `updated` value.

Unfortunately, the standard `condition()` syntax can't handle this. Drupal 7 gave us the `where()` syntax to execute arbitrary SQL that the Entity Query system couldn't handle, but this is not available in Drupal 8. Therefore, you have a couple of options as I see it:

1. Use a subquery to pull the `created` value, then use that returned value as the comparison value against `updated` in the main query.
2. Abandon (unfortunately) EntityQuery and use a dynamic or static query instead.

EntityQuery has some restrictions that are hard to get around, and field-to-field comparison is definitely one of them. Unfortunately, I don't know any other way to know definitively that an entity has been modified without revision info.
> 0 votes

---
Tags: 8, entities, database
---


# Question
Title: Exposed filter shs (simple hierarchical select) in a custom template
I don't see anywhere how to print this exposed filter in a custom template.

# Answer
> 1 votes
The problem was I did't add `filter-` in front of the filter name. Now it works with:

```
print $widgets['filter-{filter_name}']->widget;

```

---
Tags: 7, views
---


# Question
Title: hook_mail is not sending rendered HTML email
I'm rendering HTML template for email

**demo\_test.module**

```
use Drupal\Component\Utility\SafeMarkup;

function demo_test_theme() {   return [
    'contact_mail' => [
      'variables' => ['params' => NULL],
    ]
  ];
}

function demo_test_mail($key, &$message, $params) {

  $render_email = [
    '#theme' => 'contact_email',
    '#params' => $params,   ];

  $mail = drupal_render($render_email);

  $message['body'][] = $mail;
  break;
}

```

**contact\_mail.html.twig**

```
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test</title>
    <style>
      body {
        font-size: 20px;
        color: #ff0000;
        background-color: #FAFAFA;
      }
    </style>
  </head>
  <body>
    <p>test</p>
  </body>
</html>

```

Tried:

```
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

```

But still not working.

# Answer
I have done the same what you done above. Using `hook_mail_alter` function will not work for this case either.

Better is to use Mime Mail module to achieve this HTML Format.

> It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
> 0 votes

# Answer
You can try with Swift Mailer module.

One of the feature includes sending HTML (MIME) e-mails.

> The module also lets you theme e-mails so that they reflect the general look and feel of your site and at the same time appear correctly in various e-mail clients. Images required by the theme can be attached to the e-mail and displayed inline.
> 0 votes

---
Tags: 8
---


# Question
Title: Using sender name and removing HTML entity encoding in Swiftmailer
I have swiftmailer installed on a Drupal 8 installation. I am using a `hook_mail()` function to edit the message params as follows:

```
function mymodule_mail($key, &$message, $params) {
    $options = array(
        'langcode' => $message['langcode'],
    );
    switch ($key) {
        case 'support_form':
            $message['files'] = $params['files'];
        case 'submit_to_admin':
        case 'submit_to_user':
            $message['from'] = array(\Drupal::config('system.site')->get('mail') => 'site admin name');
            $message['subject'] = t('@title', array('@title' => $params['title']), $options);
            $message['body'][] = Html::escape($params['message']);
            break;
    }
}

```

I am sending the e-mail like this:

```
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'mymodule';
$key = 'support_form';
$params['message'] = $message; //defined elsewhere
$params['files'] = $attachments; //defined elsewhere
$params['title'] = $title; //defined elsewhere
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

```

The e-mail is sending fine, including attachments (so I know Swiftmailer must be working), but when I receive the e-mail the sender is listed as just the e-mail address and not as "site admin name".

Additionally, any `&` symbol in the body is showing up as `&amp;`

My swiftmailer install is configured according to this guide.

Is there a setting or code piece I am missing that is making this happen?

# Answer
I had the same issue and did the following to solve the issue with the entities.

```
$text = $message['body'];
$message['body'] = array_map(function ($text) {
  return Markup::create($text);
}, $text);

```

This will convert the body and will not display any entites anymore.
> 1 votes

---
Tags: 8
---


# Question
Title: How to perform a redirect based on the value entered in a Webform component?
How to perform a redirect after a Webform submission, i.e. to different pages for different answers?

The scenario is like so:

* If user enters "`foo`" for some Webform component, then page must be redirected to `/foo`.
* If user enters "`anything else but foo`", then page must be redirected to `/bar`.

# Answer
You can achieve by altering the Webform.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'YOURFORMID') {
    $form['#submit'][] = 'ctm_redirect';
  }
}

function ctm_redirect(&$form, &$form_state) {
  if (CONDITIONS) {
    $form_state['redirect'] = 'foo';
   }
   else{
     $form_state['redirect'] = 'bar';
   }
}

```

You can also check Webform Rules module.

This module adds rules integration on webforms.

> Did you ever want to react on webform submission using rules but couldn't find the proper event? Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).
> 3 votes

# Answer
As an alternative to the previous answer, you can also get this to work with the Rules module (cfr. the tag in your question), as further explained below (and assuming this question is about D7) ...

At a minimum, make sure you have the Webform Rules module enabled. Some details about it (from its project page):

> This module adds rules integration on webforms.
>
> Did you ever want to react on webform submission using rules but couldn't find the proper event?
>
> Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

However, you should also have a look at feature request "Expose submission data to Rules". Here is a summary of it:

> Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue.

# Time for a work around ...

The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

> You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words, checkout the screenprint included in that comment.

# ... and a demo

Consider this rule (in Rules export format):

```
{ "rules_redirect_based_on_a_component_value_of_a_submitted_webform" : {
    "LABEL" : "Redirect based on a component value of a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "form-id" ], "value" : "5" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:contact_us_target-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "submitted-form-component-value" ], "value" : "foo" } },
            "DO" : [ { "redirect" : { "url" : "foo" } } ]
          },
          { "ELSE" : [ { "redirect" : { "url" : "bar" } } ] }
        ]
      }
    ]
  }
}

```

Some details about the above rule:

* Rules Event: After a webform has been submitted
* Rules Condition: Form-id has value "`5`" (change to whatever form-id to fit your case).
* Rules Actions:

+ Add a variable (this is the clue of it all ...), named `submitted_form_component_value` and with label "Submitted form component value", and with value `[data:contact_us_target-value-raw]` (the form component we want to use in subsequent Rules Actions).
    + Use the Conditional Rules module to perform a data comparison. In this case it checks if it is `foo`. If so, then perform Rules Action "Page redirect to `foo`", otherwise perform Rules Action "Page redirect to `bar`".

PS: In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".
> 0 votes

---
Tags: rules, webforms
---


# Question
Title: Anonymous users can't access to image style field
## Entity

* Type : block
* Field : 'Reference to entity : image style' *(field\_image\_style)*
* Manage display : I display the Entity ID

## Twig

In my twig template, I get the *field\_image\_style* data from `content.field_image_style`.

## Issue

**Works great on admin user, but not when browsing the website as an anonymous user.**

This is not a image style generation error, or a wrong permission to files folders : you can access to both original image and generated styled image on anonymous.

And this is where it gets weird. It's working when you give the "Administer image styles" permission to anonymous users.

## Dump

Just to show you what result I have, here's a dump of `content.field_image_style` with an admin user :

And with an anonymous user :

# Answer
> 1 votes
The purpose of a field configured in a view mode is to render the output.

To process field values in code use the entity object. You'll find this in a block template in this variable:

```
$variables['elements']['content']['#block_content']

```

So in TWIG you can try to access the field value like this:

```
{%
  set style = elements.content['#block_content'].field_image_style.target_id
%}

```

---
Tags: 8, users, media, files
---


# Question
Title: Server showing 89% occupied after installation
I have a server of 250MB disk space and MYSQL of 115 MB. And I have just installed basic Drupal 8 site and it's showing me 208 MB and 75 MB(MYSQL) occupied. What can I do? I don't want to upgrade my server at this point in time.

# Answer
~200MB is about the size of Drupal 8 with the composer dependencies installed (which cannot be removed without breaking the site).

If you want to try Drupal 8 without paying for a more expensive server, you can use a preconfigured local development environment like Acquia Dev Desktop or lando. This puts the server on your computer for testing purposes, which should run pretty well but may be a bit slow on a low-powered laptop.

You could also sign up for a free dev account with Pantheon, which allows you to do development on their server instead of setting up a server on your own machine, but it may be a little tricky to move your site to another host later because Pantheon uses nginx and many other hosts are using apache for Drupal.
> 1 votes

---
Tags: installation
---


# Question
Title: Render a menu differently based on region
I use Drupal 7 and I’d like to have two menus rendered different: one in the nav bar showing dropdowns links for child pages, and another that simply lays out all links in the sidebar. While I can get this sidebar functionality by targeting a specific menu name, I’d like to apply these rules more generally by targeting any menu that gets placed into the region. Is it possible to select regions in theme\_menu\_link? Also open to the idea that I’m totally off on my approach for this.

# Answer
> 4 votes
You can add template suggestions. Because menus don't know their region, you first have to add a helper variable in block preprocessing:

```
function YOURTHEME_preprocess_block(array &$variables) {
  if (!empty($variables['elements']['#id'])) {
    $variables['content']['#attributes']['data-block-id'] = $variables['elements']['#id'];
  }
}

```

After that you can alter the menu template suggestions

```
function YOURTHEME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (isset($variables['attributes']['data-block-id'])) {
    $block = \Drupal\block\Entity\Block::load($variables['attributes']['data-block-id']);
    if ($block) {
      array_unshift($suggestions, 'menu__' . str_replace('-', '_', $block->getRegion()));
    }
  }
}

```

Now you can use twig templates like `menu__REGIONNAME.html.twig` for all menus in a given region.

# Answer
> 1 votes
You should be able to do that completely with CSS. The different regions should have a wrapping div with a class of "region-name" so you should be able to create some styles that take advantage of this fact:

```
.regionA .menuname ul {
  ...
}

```

and then similarly

```
.regionB .menuname ul {
  ...
}

```

Depending on how fancy you are making the user interaction you can use the same selectors in your javascript.

# Answer
> 1 votes
For Drop-Down menus in navbar I use Superfish module, which also plays nice on mobile devices. It will give you a block for each menu you want to render with it.

Also very handy is the Menu block module, which helps for example to provide:

> additional configuration so you can choose to expand all menu links with children or to root the menu tree to a specific menu item.

Using these modules you may not only be able to render menus differently (which might be done just by using css) but you may also get most work done without styling everything your self.

# Answer
> 0 votes
When you edit a block menu, you can change the theme hook in the *HTML and style options* panel.

For example, if it's your main menu, your theme hook should be something like `menu_main`. If you apply the same theme hook for all the menus in your sidebar, like `menu_custom_sidebar`, you'd be able to use the same template for all of these menus : `menu--custom-sidebar.html.twig`.

---
Tags: theming
---


# Question
Title: How do I integrate the Color module in my theme?
I have installed drupal 8.4.2 and created a subtheme with base theme bootstrap. I want to customize settings adding the color module, but really I do not know what steps I am missing.

* I have enabled color module (it's in core)
* I have copied (from bartik) the color directory and files
* I have edited color.inc to have my custom color schemes
* I have edited THEME.theme adding this:

```
function MYTHEME_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);
  }
}
function MYTHEME_preprocess_page(&$variables, $hook) {
    // Hook into color.module
    if (module_exists('color')) {
        _color_page_alter($variables);
    }
}
```

As a result I have white page with no rendering. (It's not cache issue) and I guess my problem is with **.theme** file I'd like to know where to find the instructions (drupal.org has not much). Thanks

# Answer
> 1 votes
There's actually a video on YouTube about how to do this in Bootstrap. There's also a more general video for other themes by the same person.

You'll need to use a LESS or SASS subtheme; the most basic subtheme that just uses regular CSS will not work because the Color module will change the values of the variables.

You will also need a way to compile the LESS/SASS on the server that you use the Color module on, so if you plan to make adjustments on your production server, you will need something like the LESS module, which does not yet have an official release for Drupal 8 (might still work, needs testing).

You can also find a feature request on drupal.org for putting this directly into Bootstrap, but it hasn't made any progress in the past couple years.

---
Tags: theming
---


# Question
Title: Module installation in D8.3.6 was possible, using D8.3.7 the same module couldn't be installed
I have installed the "Serial field" module with the file serial-7.x-1.8.zip in D8.3.6 I have tried to install with the same zip file in D8.3.7 and it is coming wih the error message "serial-7.x-1.8.zip does not contain any .info.yml files. "

I've found general info that ..yml file is required in D8, but is this requirement raised in D8.3.7 first and in D8.3.6 still was possible w/o ..yml?

# Answer
> is this requirement raised in D8.3.7 first and in D8.3.6 still was possible w/o ..yml?

No, YAML has been the format for Drupal 8 info files right from early dev versions, way before even the 8.0 release.

> I have installed the "Serial field" module with the file serial-7.x-1.8.zip in D8.3.6

Unless the naming of the archive is an error, and despite being labelled as containing 7.x code, it actually contained 8.x code, I’m afraid you’re mistaken.
> 2 votes

---
Tags: 8
---


title: How to serve retina images?

text:
# Question
Title: How to serve retina images?
How to serve images for retina displays? It seams that there is no modules for drupal 8 in stable release. How can we properly set up to serve hi-res for retina displays?

# Answer
> 2 votes
You also have the chance **to deliver double size low-quality images** always. It is a valid and very popular technique.

You can do it with CSS or use the following module:https://www.drupal.org/project/hires\_images

# Answer
> -1 votes
You can use https://www.drupal.org/project/retina\_images for drupal 8 as hires\_images is still not available.

After installing most core effects will include a `retinify` checkbox that will do the job.

only downside is that it does not work with most effects provided by other modules (i.e. focal point) but there is certainly workarounds

---
Tags: 8, media
---


title: Views Global: PHP can't get variable

text:
# Question
Title: Views Global: PHP can't get variable
I need to get **field\_ip\_serwera** from node in table views using global PHP. For now it doesn't work :-(

```
if(function_exists('fsockopen')){
$language = array(
    'serveronline' => '<img alt="" height="16" src="/sites/default/files/user-online.png" width="16" />.',
    'serveroffline' => '<img alt="" height="16" src="/sites/default/files/user-offline.png" width="16" />.',
);
$timeout = 1;

$adres = $row->field_ip_serwera;
$pport = "27015";

$server = array(
    'check' => true,
    'ip' => "$adres",
    'port' => "$pport",
);

$output = "";

if ($server['check']) {
    if ($fp = @fsockopen($server['ip'], $server['port'], $errno, $errstr, $timeout)) {
        fclose($fp);
        $serveronline = true;
        $output .= "<p>\n";
        $output .= "  ".$language['serveronline']."\n";
        $output .= "</p>\n";
    } else {
        $serveronline = false;
        $output .= "<p>\n";
        $output .= "  ".$language['serveroffline']."\n";
        $output .= "</p>\n";
    }
}
return $output;
}
else { echo'Funkcja <b>fsockopen</b> nie jest dostępna na Twoim serwerze...'; }

```

My english is poor, examples plx

# Answer
> 0 votes
You can use `var_dump` to check the content inside the variable `$row`

But maybe you can use this variable to get what you need:

```
$row->_field_data['nid']['entity']->field_ip_serwera['und'][0]['value'];

```

As long as that field belongs to the node you're using in that View

---
Tags: views, entities
---


title: Redirect from one module to another

text:
# Question
Title: Redirect from one module to another
I have form in one module.

```
  public static function validateForm(array &$form, FormStateInterface $form_state) {
      $url = \Drupal\Core\Url::fromRoute('test.route');
      $form_state->setRedirectUrl($url);
      $form_state->setRedirect('test.route');
  }

```

Trying to redirect the route of another module.

It's not redirecting from one module to another.

# Answer
An example

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

```

Its not working in Form validate.

Its working un submitform

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('route.path');
        $form_state->setRedirectUrl($url);
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: How can I enable download link in the Media browser library tab
My media browser has a list of powerpoint and visio files:

**How can I add a download link or preview it next to each file?** The idea is to make it easier for user to choose which file they want before saving the content. I am using media module 7x-2.8.

# Answer
> 0 votes
I ended up using this to resolve the query.

* Copied the entire function `theme_media_thumbnail` from `sites/all/modules/media/includes/media.theme.inc` into `sites/all/themes/mytheme/template.php`
* Renamed the function to `mytheme_media_thumbnail`
* Added these lines before this line `return $output`:

`if ($element['#file']->type=='document') {
 // add download link below the file
 $url = file_create_url($element['#file']->uri);
 $output .= '<br />'.l('Download', $url);
}`

These sites were useful during my research:

# Answer
> 0 votes
1 Create your view, add the fields you'd like displayed.

2 On the "Content: Video" field settings, choose the "preview" option under formatter - this displays the thumbnail.

3 Add the "Content: Path" field to your view

4 Uncheck the settings for label, check the box for "exclude from display"

5 Click on rewrite results and select "Use Absolute Link"

6 Next you'll need to reorder your fields so that "Content: Path" is above "Content: Video".

7 Edit your Content: Video settings.

8 Go to rewrite results and check "Output This Field as a Link".

9 Put \[path\] as the link path.

10 Save it.

You are done.

---
Tags: 7, media
---


# Question
Title: How to add a hierarchical taxonomy to a content type
I have a hierarchical taxonomy like below

In Drupal 7 there was a module name hierarchical select to achieve this. But it is no longer support for Drupal 8. Is there another way to add this to a content type, so a user can select an element from this taxonomy. I need that to be hierarchical.

# Answer
> 3 votes
You can take a look on Simple hierarchical select and Client-side hierarchical select module.

**Simple hierarchical select**

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.
>
> This module has been inspired by Hierarchical select but is much simpler (hence the name ;) ).

**Client-side hierarchical select**

> A simple client-side hierarchical select widget for taxonomy terms.
>
> The widget provides three settings:
>
> > Force selection of deepest level (If checked the user will be forced to select terms from the deepest level.)
> >
> > Parent (Allows to select a parent term to use only a subtree of a vocabulary for this field.)
> >
> > Labels per hierarchy-level

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


# Question
Title: WebformHandler form submit Compile error cannot declare class
I am trying to create a WebformHandler, when adding the handler to a webform via the Webform GUI the error below is what is being displayed. I have search the build and the namespace is only been used once.

Can someone tell me why this is happening?

```
    FatalErrorException in PncWebformHandler.php line 0:Compile Error:
Cannot declare class
Drupal\pnc_webform_handler\Plugin\WebformHandler\PncWebformHandler,
    because the name is already in use

```

The plugin has the following file structure

info.yml has following,

```
name: PNC Webform Handler
description: Handles form submits, does something with them.
package: Custom
type: module
version: 1.0
core: 8.x

```

The plugin class has the following,

```
<?php

namespace Drupal\pnc_webform_handler\Plugin\WebformHandler;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Download a webform handler.
 *
 * @WebformHandler(
 *   id = "pnc_webform_handler",
 *   label = @Translation(" "),
 *   category = @Translation(" "),
 *   description = @Translation(" "),
 *   cardinality = \Drupal\webform\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class PncWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    $post_url = $this->configuration['submission_url'];
    \Drupal::logger('pnc_webform_handler')->error('Web form url: @error', ['@error' => print_r($values, 1)]);
    //$client = new \Drupal::httpClient();
    // $response = $client->request('GET', 'https://<your_third_party_service_here>',
    //   'form_params' => [
    //      'first_name' => $webform_submission->getData('first_name')
    //   ]
    // );
    // $code = $response->getStatusCode();
    //if ($code >= 400 || $code === 0) {
    // Handle the error
    // }

    return true;
  }

}

```

I am using a vagrant box https://github.com/beetboxvm/beetbox with php 7

Here is a link to my latest attempt

# Answer
I've downloaded the archived source code you attached and it doesn't reflect what you've presented here. The code from your question is correct.

However, you wrongly defined the namespace (in the attached archive). Change:

```
namespace Drupal\pnc_webform_handler\src\Plugin\WebformHandler;

```

to

```
namespace Drupal\purencool_webform_access\Plugin\WebformHandler;

```
> 3 votes

---
Tags: webforms, plugins
---


# Question
Title: Third party library added via composer.json but how can I load it in a module now?
I have set up a module in my Drupal 8 project to handle some tasks I need doing using AWS.

I added the awssdk (for PHP) to my composer.json and ran the composer update command successfully. the AWS SDK is now sitting nicely in my `/vendor` directory under the folder `aws`.

Composer entry

```
'aws/aws-sdk-php': '^3.0'

```

I cannot seem to get this to load within my custom module. I have tried referencing the SDK as follows at the top of my one Controllers (*After the `use` keyword but before the `class` keyword*)

```
require_once (\Drupal::root() . '/vendor/autoload.php');

```

The result of trying this gives me a blank white page with this error in the apache log:

> PHP message: PHP Fatal error: require\_once(): Failed opening required '/home/dash/public\_html/docroot/vendor/autoload.php' (include\_path='.:/usr/share/php') in /home/dash/public\_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 9

**Also tried using an absolute path as**

```
require '/home/dash/public_html/vendor/autoload.php';

```

Result: Page loads no watchdog error but I get an apache php error as soon as I try reference one of the SDK classes:

> PHP message: PHP Fatal error: Class 'Drupal\awsintegration\Controller\Aws\Sdk' not found in /home/dash/public\_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 27

**UPDATE**

After Clive's suggestion in comments I removed the require calls. I then added some simple code that used AWS to try create a credentials provider, I simply get errors in the apache log about missing Class as per:

> PHP Fatal error: Class 'Drupal\awsintegration\Controller\Aws\S3\S3Client' not found in /home/dash/public\_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 21

My code is as follows:

```
namespace Drupal\awsintegration\Controller;

use Drupal\awsintegration\AwsInstances;
use Drupal\Core\Controller\ControllerBase;

use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

class AwsiInstanceListController extends ControllerBase {

    public function content() {

        $s3 = new Aws\S3\S3Client([
            'version'     => 'latest',
            'region'      => 'eu-west-2a',
            'credentials' => [
                'key'    => 'AbAbAbAbDcDcDc',
                'secret' => 'QwertyQweRty'
            ]
        ]);

        return array(
            '#type' => 'markup',
            '#markup' => $this->t('Hello, World!'),
        );
    }

}

```

# Answer
> 1 votes
You don't need to use require\_once for autoload. It handles by the composer automatically. You should create a `use` statement in your php file.

As an example if you want to use a class s3 module of aws;

```
use Aws\S3\SomeClassName;

```

---
Tags: composer, 8
---


# Question
Title: Modify existing block programmatically by block id
I have a block with the id 'block-block-8'. In my template.php I would like to have a function that changes that block's content so I am able to add a dynamic "back to category link" (category needs to come frome the url) on my products page back to the category page.

Something like this:

```
function ga2012_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'block-block-8':
      $block = array(
        'content' => '<a href="/order/4/workshops">Back to $_GET["category"]</a>',
      );
      break;
  }

  return $block;
}

```

Does someone has a working implementation of this code? Please ask me questions if I haven't been clear enough, thanks!

# Answer
> 3 votes
You might try with hook\_block\_view\_MODULE\_DELTA\_alter which:

> Performs alterations to a specific block

# Answer
> 1 votes
In your case, the best solution is to use hook\_block\_view\_MODULE\_DELTA\_alter as @Artur explained. But there is another way to to customize a custom bloc programmatically using an update function (inside a .install file) in drupal 7 by using:

```
$content = 'your new content';

$num_update = db_update('block_custom')
                ->fields(['body' => $content,])
                ->condition('bid', your_block_id, '=')
                ->execute();

```

---
Tags: blocks
---


# Question
Title: Request header field X-CSRF-Token is not allowed by Access-Control-Allow-Headers in preflight response for Drupal 7 REST API
I have few APIs created in Drupal 7 which uses session authentication. Now when I get the CSRF token and try to use it in my API call, I get following error: **Request header field X-CSRF-Token is not allowed by Access-Control-Allow-Headers in preflight response.**

Here is my javascript code:

```
var url = "http://dev/api/v1/macc/*";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(xhttp.responseText);
    }
};
xhttp.open("GET", url, true);
// xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.setRequestHeader('X-CSRF-Token', 'xxxxxxxxxxxxxxxxx');
// xhttp.setRequestHeader('cookie', cookie);

xhttp.send();

```

If I run the same API from Advanced Rest Client, I get the correct response.

Any help will be appreciated.

# Answer
> 2 votes
Have a look at cors module You'll be able to add necessary Access-Control-Allow-Headers

Otherwise, you can do this by changing your apache (or nginx or whatever) conf.

In drupal 8, you define this in services.yml, as explain here.

---
Tags: 7, services, csrf
---


# Question
Title: Webform Drupal 8, node and form, how to pass node field info to form?
I don't understand how node integration with webform works. How do I pass data from a node with a webform field to an instance of that form? I created a form with email and location. Then I created a content type with location, description, date, and a webform field and then I added some content to it. How do I associate the location from the content type to an instance of a form? How does the "Default submission data (YAML)" work? I put "\[current-page:title\]" in there expecting it to populate the form, but I don't understand how to specify what form field it goes to or if I'm using the right syntax or what??

# Answer
The location node is considered the 'source entity' and is automatically tracked.

You can use the \[webform\_submission:node\] to pull information from the location node into the 'Default webform submission data (YAML)'. For example, to get the location's title you should use the \[webform\_submission:node:title\] token.
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Can I test code contained in module files?
Generally a module file contains hooks and doesn't have any class nor namespaces. What I have studied so far is that PHP Unit testing is possible only when the code is contained in classes.

Can I write unit tests for module files?

# Answer
# Unit-testing procedural code

In principle, you can unit test procedural code just as easily as code that is in a class, but you can't really *mock* it. Therefore, whether your tested code is in a class doesn't matter so much as whether its dependencies are.

Even though procedural code cannot use dependency injection and has to access services via `\Drupal::service()`, you can put your mocks into a custom container and call `\Drupal::setContainer()`:

```
$container = new ContainerBuilder();
// ... insert mocked services
\Drupal::setContainer($container);

```

That means if you call only class code like `\Drupal::logger()` or `\Drupal\user\Entity\User::load()` or even `\Drupal::database()`, you should be able to mock everything, load your `.module` file, then call all of the hooks and check that they return the correct values.

But if your code references procedural core constants or functions (eg `REQUEST_TIME`, `db_query()`, `drupal_set_message()`, `watchdog_exception()`, `file_*()`, `user_load()`) then those `.inc`/`.module` files must be included as well, along with any files used by *that* code. You'll quickly run into problems that way, as that code will assume it's running in a full Drupal instance. To test such code, a kernel test or functional (ie browser) test will likely be required.

# Unit-testing Hooks

With hooks, there is an extra caveat for unit-testing: You are declaring a function that you expect to be called from elsewhere, and which often doesn't do much other than altering and returning arrays.

You can test that as a unit, but because the contract of that code is so vaguely defined, it generally won't tell you much. Most of the errors in such code will only be revealed by testing the results in a functional test.
> 5 votes

---
Tags: 8, testing
---


title: Webform Rules - Create a Drupal User

text:
# Question
Title: Webform Rules - Create a Drupal User
I'm using Webforms (*via the Webform module*) and using Rules (with the *Rules module* and the *Webform Rules module*)... as a side note, I'm also using CiviCRM although I don't think that is has an impact of the issue I am having...

When using Rules I can specify an action to take place on a given event - in my case when a particular webform is submitted. **When webform 'a' is submitted I want a Drupal user to be created...**

If I use the action 'create entity' and specify that the entity to be created is of type 'User' then **if I statically enter the value** for the username and the e-mail address the Drupal **account is created**.

However, if I try to tell the action creation process to **use the value entered in the webform** as the username and the e-mail address ( e.g. \[data:{component}-value\] where {component} is substituted for the machine name of the field in question ) for the intended Drupal account, **no Drupal account is created**. Does anyone know why this is the case and what the solution for this is?

**Side note:** I know the value used in \[data:{component}-value\] is correct as I added an action saying output a message and added the data field to the message and it shows the correct details (e.g those entered in the webform)

# Answer
> 1 votes
You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your `[data:ComponentFieldName-value-raw]` (and with a data type which equals the data type of your Webform component). Looks like you need 2 variables though: 1 for the username, one for the eMail ID.
* In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

---
Tags: 7, users, civicrm, webforms
---


# Question
Title: How to pass a custom Form to a Twig template
my problem is that my drupal 8 form is not getting rendered in twig template.

I created a form with build form method in drupal 8 when i tried it to pass in twig template it is not getting passed.for example my code is

modulenameconfig.php

```
class modulenameConfigForm extends ConfigFormBase {

  /**

   * {@inheritdoc}

   */

  public function getFormId() {

    return 'modulename';

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

    $form = parent::buildForm($form, $form_state);
    $config = $this->config('modulename.settings');

    $form['first_name'] = array(

      '#type' => 'textfield',

      '#title' => $this->t('First Name'),

      '#default_value' => $config->get('modulename.first_name'),

      '#required' => TRUE,

    );

    $form['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
      '#default_value' => $config->get('modulename.last_name'),
      '#required' => TRUE,
    );
    return $form;

  }
 protected function getEditableConfigNames() {

    return [

      'modulename.settings',

    ];

  }
}

```

modulename.module

```
<?php

namespace Drupal\modulename\Form;

use Drupal\Core\Form\ConfigFormBase;

use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_menu()
*/

function modulename_theme() {
  return array(
    'modulename_form' => array(
      'render element' => 'form',
      'template' => 'modulename-form',
      'base hook' => 'form'
    ),
  );
}

```

my twig file in templates folder

modluename-form.html.twig

```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
  ]
%}

                           <h2>Personal Information</h2>
                                    <form method="post">
                                        <div class="form-group">
                                            <label for="name">First Name</label>
                                            <div class="input-group">
                                              {{form.first_name}}

                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="name">Last Name</label>

                                            <div class="input-group">

                                                <input type="text" class="form-control" name="lname" id="lastname" placeholder="Last Name" required>

                                                <span class="input-group-addon danger"><span class="glyphicon icon-remove"></span></span>
                                            </div>
                                        </div>

```

any help will be greatly appriciated help asap

# Answer
This structure will not work with the autoloader right now - your namespaces and directory structure needs to follow these PSR-4 standards. (In particular, setting a namespace in your `.module` will cause Drupal to not find your hooks, which must be in the global namespace.)

I'm not sure I understand your use case fully, but it sounds like you want to:

1. Create a form.
2. Create a route that serves this form.
3. Render the form with a custom template.

For the first, your form class should be something like this (and must be saved in a file matching the class name under `modulename/src/Form/{ClassName}.php`):

```
namespace Drupal\modulename\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MyModuleConfigForm extends ConfigFormBase {

  public function getFormId() {
    return 'modulename_settings';
  }

  public function getEditableConfigNames() {
    return ['modulename.settings'];
  }

  public function buildForm(array $form, FormStateInterface $formState) {
    // build the form
    $form['...'] = [
      //...
    ];

    parent::buildForm();
    return $form;
  }

  public function submitForm(array $form, FormStateInterface $formState) {
    $this->config('modulename.settings')
      // set the values from the form
      ->set('...', $formState->getValue('...'))
      ->save();

    parent::submitForm($form, $formState);
  }

}

```

For the second part, you need a `modulename.routing.yml` file that looks something like this:

```
modulename.settings:
  path: '/admin/config/mymodule'
  defaults:
    _form: '\Drupal\modulename\Form\MyModuleConfigForm'
  requirements:
    _permission: 'administer site configuration'

```

(This is for admin configuration forms, since you mentioned `ConfigFormBase`. If you want a more general form and open it to anonymous users, extend `FormBase` instead and put `_access: 'TRUE'` in the route requirements.)

Finally, for the third part, you need to create your theme hook in `modulename_theme()`. (Your code already works, although the `template` key is superfluous as it matches the default.)

Then, modify the `buildForm()` as follows:

```
  public function buildForm(array $form, FormStateInterface $formState) {
    // build the form
    $form['...'] = [
      //...
    ];

    parent::buildForm();

    // *After* parent call.
    $form['#theme'] = 'modulename_form';

    return $form;
  }

```
> 3 votes

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


# Question
Title: How to split and link date field to view (imdb style)
I have created content type call person (list of persons) added a date field to content type (birth\_date)

1. how to split date to year/month (or should it be two date fields)
2. how to link year to all the people born on that year and month/day to all people born on that day. I know how to create view, but how to make date output as link to it?

Pretty match like imdb does it, not display calendar but text in one line. birthday: year\[link\]/ month day\[link\]

# Answer
> 0 votes
Use module and code in your theme:

```
/**
 * Override theme_date_display_single().
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function theme_date_display_single($variables) {
  if($variables['dates']['format'] == "d F Y"){
    // In this case i keep only start date. For keep end date use value2.
    $date = $variables['dates']['value']['formatted_iso'];
    $timezone = $variables['timezone'];
    $attributes = $variables['attributes'];

    $day = format_date(strtotime($date), 'custom', 'd');
    $month = format_date(strtotime($date), 'custom', 'F');
    $year = format_date(strtotime($date), 'custom', 'Y');

    // Wrap the result with the attributes.
    return '<span class="date-display-single"' . drupal_attributes($attributes) . '>' . '<span class="d">' . $day . '</span>' . '<span class="M">' . $month . '</span>' . '<span class="Y">' . $year . '</span>' . $timezone . '</span>';
  }
}

```

---
Tags: views, entities, datetime
---


# Question
Title: date field missing when use date popup with date & time
in my custom module, I have used the following code:

```
$form['event_date'] = array(
    '#type' => 'date_popup',
    '#title' => 'Set Date & Time :',
    '#date_format' => 'd-m-y H:i',
    '#default_value' => date('d-m-y H:i'),
    '#date_year_range' => '-3:+3',
    );

```

but after submitting it only show time field value. also work fine when only use date('d-m-y').

# Answer
Yep, I found it in `$form_state['input']`.

I am actually using this with Ajax. so In callback function you can get the form values from `$form_state` array. All form values are present in `$form_state['values']` and input type values are also can be found in `$form_state['input']`.
> 0 votes

# Answer
In my custom form, add your code:

```
function donation_form($form, &$form_state) {

$form['event_date'] = array(
    '#type' => 'date_popup',
    '#title' => 'Set Date & Time :',
    '#date_format' => 'd-m-y H:i',
    '#default_value' => date('d-m-y H:i'),
    '#date_year_range' => '-3:+3',
    );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('donation_ok'),

  );

  return $form;
}
 function donation_ok($form, &$form_state) {
   dpm($form['event_date']['#value']);
   dpm($form_state['values']['event_date']);
   dpm($form_state['input']['event_date']);
 }

```

you can use:

```
dpm($form['event_date']['#value']);
dpm($form_state['values']['event_date']);
dpm($form_state['input']['event_date']);

```

result:
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Drupal 7 Custom Theme - Administration menu missing or not showing
This should be an easy query for those that have been using Drupal 7 for some time and have created their own custom themes. I have created a custom theme which appears to be working, but it does not show the administration menu which is normally located at the top of the screen does anyone know what needs to be done to get it too show - e.g. what line needs to be added to the html.tpl.php file ...

one source suggested

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

```

But this might have been more geared towards Drupal 6 ... I'm working with Drupal 7... another source suggested adding:

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

```

But that doesn't appear to help either.

Anyone got any ideas on how to added the administration menu which normally shows at the top of the page?

**Side Note:** Are other themes making use of template.php files and hooks to get the administration menu to show?

# Answer
You need to print the `$page_bottom` just before the `</body>` tag in html.tpl.php.

You do need `$page_top` too, and `$page`, so taking the default html.tpl.php as an example:

```
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>

```
> 1 votes

---
Tags: 7, theming, navigation
---


# Question
Title: Commerce 2: Can Cash and Check payments be implemented?
My client's business and website is primarily online purchases. However, there are instances when special customers or referrals come into their office and buy the product by cash or check.

My client wants those purchases to be recorded in the same database as online orders, along with the same captured contact information.

Is there a way to implement the checkout process so that certain employees with designated privileges can enter orders through the online store, but no request for payment information is required. Or for those and only those privileged people an additional cash / check option is shown? (And the check option may also ask for additional info, such as the bank name and check number.)

# Answer
You can do this by adding an additional payment gateway.

1. Add a role, **Pay with Cash** or whatever you want to call it.
2. Add a new payment gateway (at `/admin/commerce/config/payment-gateways/add`).

* Name: Cash or Check
    * Plugin: Manual
    * Customer: Limit by Role: Pay with Cash role

The "Manual" gateway does not ask for any payment information, so orders with the manual payment selected (which only users with the **Pay with Cash** role will be able to select) will automatically be processed as completed when this payment method is selected.

If you want to record bank info for checks, you can make two separate gateways, one cash and one checks, and then customize the check gateway with additional fields.
> 2 votes

---
Tags: commerce
---


# Question
Title: Node Clone operation/tab missing for webform
```
Node Clone 7.x-1.0+2-dev
Webform: 7.x-4.13
Drupal 7

```

I only see the clone operation available on 1 custom content type, and NOT on my webform content type.

I tried installing the node clone tab module, and the tab does not appear either.

Clone any node, clone own node permissions enabled for my role 'Administrator'.

Any suggestions for moving forward?

# Answer
> 1 votes
Besides simply enabling the Node Clone module and checking the permissions associated with it, you'll need to select which content types can be cloned.

To do so, go to /admin/config/content/clone

After enabling for the "webform" content type, you should see the clone link available near the contextual link / action tabs at the top of a webform page when signed in as an admin and viewing the page.

---
Tags: nodes, webforms
---