title: Domain override module in drupal 7

text:
# Question
Title: Domain override module in drupal 7
I have a main site with "domain access" module. It has 5 multilingual sub sites with subdomain(single database). I want to publish content from the main site to the subsites. This is already working good with send to affiliates. But I want some admins on the subdomain to edit some content and it should reflect on that subdomain only i.e It should not update content in main site.In drupal6 I found module "domain override" How I can acheive this in drupal 7

# Answer
Use Node clone module and remove the domains for which you don't want to publish the content.

This is what Node clone modules does:

> The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words **"Clone of"** are inserted into the title to remind you that you are not editing the original content.

And this is what Domain override module does:

> Provides an "Override" tab on node pages that removes the current domain from the node's domain access, **clones the node**, and publishes the clone to only the current domain.
> 0 votes

---
Tags: domain-access
---


title: Custom Migration not appearing in UI

text:
# Question
Title: Custom Migration not appearing in UI
I am trying to do a simple CSV import into a node using the Drupal Migrate module. I have created the .module and .info files and double-checked them against several examples online. I have also created a .inc file including

```
class CrfmMigration extends Migration

```

I have enabled my module from the Modules Administration panel and there are no errors. However, when I go to the Migration UI, my migration class isn't listed at all. The Beer and Wine samples show up just fine, but my custom migrate class is nowhere to be found. I'm not even sure which file the problem could lie in. I am more than happy to provide any additional information as necessary to figure this out. I prefer not to use Drush if possible, but I will if there is no other option.

# Answer
> 1 votes
This is usually an issue of needing to clear your cache. Usually if you register a migration class with migrate and then view a migrate UI page without having cleared the cache, you'll see an error about your migration class no longer existing.

# Answer
> 1 votes
This might happen for a couple of reasons. Here are some pointers:

* Make sure your module implementing the migration is enabled (I believe you must have checked that already).
* Make sure your migration classes are registered with Drupal using the `files` directive in the `.info` file.
* Make sure you clear the cache, especially the class registry.

I hope it helps! I'm currently stuck in a D8 migration.

---
Tags: migrations
---


# Question
Title: How to limit access to certain nodes to certain users only?
I am considering Drupal for a project with following features:

* I need two content types: **Supplier** and **Client**.
* I want my clients to be able to follow the progress of their **orders** (each order will be a node).
* My suppliers will have access to their **invoices**, **documents**, etc. (which are nodes as well)

Any ideas on how to achieve this?

Example:

* Client `Alpha` will have access to `node/34` and `node/46` only.
* Supplier `Beta` will have access to `node/38` and `node/50` and their attached files only.
* And so on ...

Is this possible with Drupal (6, 7) ? If so how can I do this, do I need custom coding or are there any other solutions for it?

# Answer
Depending on how much more deep you want to take the logic of your project, you might not even need custom coding.

1. Start with Drupal 7 minimal installation profile
2. Install the modules views, entity, entity reference and their dependencies.
3. Create the content type "order" and add the fields you need to it. Add other content types as well like "invoice" and document, these last you might want to add a "reference" field to the order content type if they are connected.
4. Setup the user roles "client" and "supplier" and you might want to install the "ACL" and "content access" modules as well to define who has access to what, like "only"3 the author of the node can see it, edit it and delete it.
5. To make it easier for the user to see the nodes they have access to, you can create a tab on their user account using views listing only the node where they have access or where they are the authors.

**Notes:** You might want to test the system before going live to make sure the right person can access the right content. Also if no anonymous user is meant to use the system disable content access to the anonymous users.
> 1 votes

# Answer
Seems like what you're trying to do is perfectly possible using the Content Access module. Here is a quote from its project page:

> This module allows you to manage permissions for content types by role and author. It allows you to specify custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

After you've enabled this module, you would typically configure which access rules you want to be applied automatically for your **Suppliers**, and similarly for your **Clients**. For that you could define 2 roles, named (eg) **Supplier** and **Client**. Once you have those roles in place, you simply start granting the appropriate access to your content types of **Orders**, **Invoices** and **Documents**, which IMO should be 3 separate content types also.

It also appears that, for your case, and for each of these content types, you'd want to use the special facility that this module offers, which is "*** Per content node access control settings\***". Some more details about this (from the admin page that contains this setting):

> Optionally you can enable per content node access control settings. If enabled, a new tab for the content access settings appears when viewing content. You have to configure permission to access these settings at the permissions page.

For anything that has the same access permissions (eg read access to "Terms & Conditions"), you may not have to use the above *Per content node access control settings* (which take time to maintain for each node ...). E.g. if you'd use another content type the same access rule could apply to all such nodes.

### Rebuild permissions

Sometimes you'll need to "Rebuild permissions" ... Any time the "Access" rules are changed (via admin settings), Drupal needs to ensure that these rules are applied to all impacted content (nodes). That's why Drupal then re-applies the updated access rules. A special case is the "enable" of a module, when rebuilding permissions is also required.

### Integrations with other modules

Content Access also has all sorts of integrations with the Rules module, which you may use to make all sort of custom business logic happen (only using the Admin UI, no custom code needed, unless you insist ...). For a typical example of this, refer to my answer to "How to revoke edit access to the node's author after publishing a node?".

On top of that, if you want to start using the Content Access module for an existing sites (where you need to mass grant the appropriate permissions), you can use an approach as explained in my answer to "How to create a bulk grant view form for the node access module?".
> 0 votes

---
Tags: nodes, users
---


title: How to print the best answer field?

text:
# Question
Title: How to print the best answer field?
I am use the Best Answer module. I customize the answer template, `node-answer.tpl.php` and I want to print best answer field,add

No output result, please help me.

# Answer
The Best Answer module extends the **7.x-3.x** version of the Answers module (disclosure: I'm a (co-)maintainer of it). However, this module has been integrated as a sub-module of the **7.x-4.x** release of Answers. This release also has the new theming stuff (if you enable the brand new `answers_theme` sub-module) as in this sample screenprint of it:

Note **the checkbox** in the bottom-left of it (shown to the left of the accepted answer), which I believe is the equivalent of the ***best answer field*** that your question is about.

So unless you have good reasons to continue with the **7.x-3.x**, I strongly recommend you to first upgrade to the **7.x-4.0-rc2** release of Answers, which might possibly obsolete what you're trying to achieve.

Even though the 7.x-4.x release is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. The next release that will become available, will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).

## Try the most recent 7.x-4.x release

To experience it yourself, try out a demo of it. Here are the steps to do so:

* Head over to the demo site.
* Just accept the defaults to create a sandbox demo site (make sure you're using the most recent 7.x-4.x release). Then hit the create sandbox button, and wait for the process to complete. Make sure you also enable the ***Answers Theme*** (sub-module of Answers, new as of 7.x-4.x).
* Create at least 1 question using either the "*Add content*" menu link and then selecting "Question", or just enter relative path `/node/add/question`. And complete the title and body of the question.
* After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
* If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
* Use the ***Questions*** tab (or enter relative path `/questions`, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

## Demo site

Have a look at the demo site of the Answers module. This link shows various menu options within the block with title ***Answers Menu***, i.e.:

* **Questions** (= a view):
    + **All**: of all existing questions (= default tab).
    + **Answered**: all questions which have a "best" (= accepted) answer (= sub-tab).
    + **Unanswered**: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).
* **Answers** (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
* **Rankings** (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
* **Ask Question**: to post a new question (the equivalent of `node/add/question`), which is only shown for authenticated users though.

These Views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visible in the demo site).
> 1 votes

---
Tags: 7
---


# Question
Title: How to count the number of votes for each star in fivestar?
I'm using Drupal 7, Voting API and Fivestar.

I try to count the number of votes for each star, and display the percentage, like :

It is at present possible to have only the number of total vote.

How can I achieve this? With Voting API (`hook_votingapi_results_alter`) or Views ?

For information, i'm using comments for rating nodes.

# Answer
> 0 votes
Once i tried to find some function that could do it. But i found just fivestar\_get\_votes($entity\_type, $id, $tag = 'vote', $uid = NULL). It returns full voting score.

You can get some info here or on other sites.

I think it is possible with some sql queries EG:

```
   $query = db_select('votingapi_vote', 'vote');
   $query->condition('vote.entity_type', 'node');
   $query->condition('vote.entity_id', $nid);
   $query->condition('vote.tag', 'vote');
   $query->condition('vote.value', '60');
   $query->addField('vote', 'uid');
   $three_stars = $query->countQuery()->execute()->fetchField();

```

Here $nid is your your node's nid and 60 means three stars (20 - 1 star, 40 - 2 stars etc), vote.tag is tag that you assigned for your votes.

---
Tags: 7, rating
---


# Question
Title: How to apply flags retrospectively for group subscriptions using Organic Groups?
We've a large site running Drupal 7 with OG, Flag, Rules, etc.

OG uses a subscription model where you have to confirm you want to join a group (or leave a group) so we've decided to move to a Flag system that then uses rules to add (or remove) that user from the group.

All works great, except the site is already live and we have a lot of members in groups already, which obviously Flag doesn't recognise.

Is there a way to force Flag to check if a group subscription exists already?

# Answer
I seem to understand from your question, that you're looking for a way to flag the existing members of an OG group.

If that's what you want, then a possible approach to make this work, is to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* load the VBO list of users (of an OG group) that you want to be processed.
* add a loop to perform a Rules Action, whereas you just flag each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

PS: if this is NOT what you want, by using this approach (anyway) I believe your question about "*Is there a way to force Flag to check if a group subscription exists already?*" became obsolete ...
> 1 votes

# Answer
Guess what, if for some reason (such as this one), you can't get it to work with the prior answer, then you may want to try an approach which is like "the other way around". Read on for more details on that approach ...

### Step 1

Start with creating an extremely basic Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to flag (using the Flag module) a user, whereas you specify the user to be flagged as a parameter for that Rules Component. FYI: this is really like a getting started with Rules ...

### Step 2

Create a view of your existing members of an OG group that you want to be flagged. Maybe you already have such view that you can use. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?".

In doing so, you'll then be able to use Rules Components (using the Rules module), in which you can then include the required logic to flag a single user with your flag. If you wonder how to create such Rule that would fit your VBO view (ie that you can use in it), then use this link ...

### Attention

Even though one may think "***Hm, is it really that easy?***", it happens that after you created a Rules Component and try to use it in a VBO view, that Rules Component **cannot be selected** as an operation to be enabled in your VBO view. If that happens, and you wonder what it would take to try to make it show up anyway (in the VBO view), then use this link ...
> 0 votes

---
Tags: 7, rules, organic-groups, flags
---


title: Autoload Mapping for modules

text:
# Question
Title: Autoload Mapping for modules
I'm trying to better understand how Drupal 8 autoloading for classes is automatically mapped to the *src* directory in modules.

Basically, I'd like to know how the system knows to look in the *modules/module\_name/srс* directory when searching for classes.

I can't seem to find any details on how it's done through the *composer.json* files or the *autoload\_psr4.php* files. Perhaps I'm looking in the wrong place?

# Answer
> 4 votes
Drupal 8 follows PSR 4 autoloading standard which is implemented by composer autoloader.

While some Drupal namespaces are registered statically in *composer.json* and *core/composer.json* other namespaces are processed dynamically (see *DrupalKernel::classLoaderAddMultiplePsr4*).

PSR-4 namespaces and autoloading in Drupal 8

---
Tags: 8, composer
---


# Question
Title: Need webform with list of items, price, and total
Not sure that webform can do this, BUT my client sells yachts. They want a webform on the site that lists all of the boat options (a check-list) a potential customer might like to have and creates a subtotal at the bottom of the list as the customer checks items on the list.

The way it works: A visitor is interested in buying a boat so they go through the list and check(box) the item/s they want, and as they check the items a subtotal is calculated at the bottom of the list. Then the webform is submitted to the company sales to someone that will contact the potential customer to continue the sales effort.

This should be something like a spreadsheet, but the list cannot be changed (only the checkbox next to each item). The subtotal is affected only by the items on the list that are checked.

This might better be done by something like ubercart, but seems ubercart would be overkill.

Does anyone have ideas how this could be done (or if it cannot) with webforms, OR if there is a better way, please?

cFusch

# Answer
You can try Webform Calculator, I know it has checkbox support. You can set values for fields, then calculate the total amount at the end of webform for the submission.

> Provides a formula webform component for computed values, where you can enter a mathematical calculation based on the other fields. E.g., create a formula field with value formkey1 * 0.1 * formkey2.
> 0 votes

---
Tags: webforms
---


# Question
Title: views - remove duplicates based on field value
Hi I have an order list created in views with 2 fields: order ID and order payment method. Each order can have multiple payment methods (every payment method gets own incremented id when attached to order).

Example:

```
order id1 with payment id1
order id2 with payment id2 and payment id3
order id3 with payment id4

```

This causes duplicate rows in second case.

Problem: How can I show only orders with the last payment method attached to them?

One solution would be to create one view with order id argument, showing only one row and sorted by payment id descending. Then using views field view module and create another view with order list without duplicates.

Question: is there a more simple solution without creating second view? Thank you.

# Answer
> 0 votes
I would use Views Distinct module to filter the duplicates out. The way this works is this:

* you select the displayed view field,expand 'Views Distinct Settings' and select 'Filter Repeats'

So, for your particular case, if you want to show only the last payment method, order by payment method (ID ?) DESC, and on the order\_id filter repeats. This way, only the last row for every order\_id will show.

---
Tags: 7, commerce, views
---


# Question
Title: Views exposed filter between label AND replace with -
how do I change exposed filter BETWEEN label? There is default "AND"-text and I need to change it to "-"

# Answer
You have to use a hook\_form\_alter() to edit the form programmatically. This will go in a custom module.

Here's some boilerplate code:

```
function test_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id !== 'views_exposed_form') {
    return;
  }

  if ($form_state['view']->name !== '<your_view_name>') {
    return;
  }

  $form['field_<your_field_name>']['max']['#title'] = '-';
}

```

Replace the view and field names with your particular ones. Hope it works for you.
> 0 votes

---
Tags: views
---


# Question
Title: Somehow, edit/delete has been changed to node->title/edit or node->title/delete for one of my project. Can anyone have idea what could be a reason?
Somehow, edit/delete has been changed to node-\>title/edit or node-\>title/delete for one of my project. Can anyone have idea what could be a reason?

Any lead towards the debugging would be appreciated.

# Answer
On one of my projects, for this kind of functionality I have used Sub-path URL Alises module. Maybe it's enabled on your project ?
> 0 votes

---
Tags: nodes
---


# Question
Title: How to set a placeholder to a form element in a exposed view filter?
I have an exposed view filter in a view and I need to put one element label as a placeholder in his edit form element. How can I achieve that?

# Answer
> 14 votes
You can implement the `hook_form_FORM_ID_alter()` hook, in the case of the view exposed filter form the name is `views_exposed_form`

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

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  //You need to verify the id
  switch ($form['#id']) {
    case 'views-exposed-form-nouvelles-page-1':
      //Setting placeholder
      $form['title']['#attributes']['placeholder'] = $form['#info']['filter-title']['label'];
      //Cleaning the filter labels
      unset($form['#info']['filter-title']['label']);
      break;
  }
}

```

How you can find the element name? It's easy, you can Inspect your Element:

---
Tags: 8, views
---


title: Using OCI8 Module to See OracleDB

text:
# Question
Title: Using OCI8 Module to See OracleDB
I have an external oracle db I'd like to use to show data in views. Has anyone used the OCI8 module, if so, (sorry for my ignorance) how do we see the data? Do I need to create a custom module and hook into it? I cannot find any how to on this.

The readme says: 1) Build out OCI8OracleSelectQuery class which will mimic Drupal's SelectQuery. This would include writing an oci8\_db\_select() function to create these

Where do I do this? Thanks!

# Answer
> 2 votes
That module provides a very basic API only; no UI, no methods to display/format data, and no integration with the Views module.

It currently provides developers with:

* A database connection class for Oracle
* A simple Oracle-specific version of `db_query`
* A simple Oracle-specific version of `db_query_range`

and literally nothing else.

So yes, in order to see any data using this module, you're going to need to create your own module which uses the couple of query functions it provides, and displays the results in whatever way makes sense.

For something more automated, you could try the technique mentioned here to hook into Views and force it to use a different database for certain tables (which can theoretically be in an Oracle DB). I've never tried that so I can't comment on its effectiveness, or if it's genuinely even an option. Something tells me that you'd need a PDO connection to Oracle for that to work, but I might be wrong.

As an aside, the line you quoted from the readme looks like a TODO note; the maintainer is probably saying that the functionality hasn't been implemented yet, but that developers who want to make proper use of the module will probably find it beneficial to implement that per their requirements.

---
Tags: 7, database
---


# Question
Title: Data not returned / rendered in simple module
I built a simple module to find the files in a folder and display them. However no "content" is rendered and I get warnings from a core-include file. Here is the module file:

```
<?php
function composer_example_menu() {
    $items = array();

    $items['composerExample/composer_example'] = array(
        'title' => 'Composer Demo',
        'page callback' => 'get_current_files', // 'call_back_function_name',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

/**
 * A utility function to return the array of current SplFileInfo objects
 */
function get_current_files()
{

  require __DIR__.'/../../../../../vendor/autoload.php';

    // the "files" directory
    $dir = drupal_realpath(file_default_scheme() . '://');

    $finder = new \Symfony\Component\Finder\Finder();
    $finder->in($dir)
        ->name('*.txt')
    ;
    $files = array();
    foreach ($finder as $file) {
        $files[] = $file->getFilename();
    }
  return $files;

```

The Warnings I get:

> Warning: Invalid argument supplied for foreach() in element\_children() (line 6583 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 6040 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 6050 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 6088 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc). Warning: Illegal string offset '#printed' in drupal\_render() (line 6095 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc).

# Answer
> 2 votes
The value returned from the `page callback` will be passed into the function stated in `delivery callback`.

The default value of `delivery callback` is `drupal_deliver_html_page()`.

> "delivery callback": The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal\_deliver\_html\_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal\_deliver\_html\_page() for an example.

So you cannot output the `$files` directly. You have to return a render array if you want to keep using the default delivery callback.

---
Tags: 7, theming
---


# Question
Title: How to programmatically set role based permissions on a field?
How do I programmatically set role based permissions on a field?

For example, I have field\_my\_field, for which I want the following permissions:

* Owner can view and edit
* Role X can view and edit
* Role Y can view only

Looking in the database, the role\_permissions table looks like it's what contains the data, but I'm confused about the actual permissions, as they're very close to natural language. e.g. 'access site in maintenance mode' although field ones make more sense:

* Edit own field\_my\_field (owner can edit)
* View own field\_my\_field (owner can view)
* Edit field\_my\_field (can edit any)

I guess it's something along the lines of granting the permission to a RID, and identifying the module which interprets the permission.

**Note**: I'm trying to do this in another module with PHP - not in the UI. The Field Permissions module is great, but I need to do this in my code.

# Answer
Ok, worked this one out...

I created my own function to do this, which I have called in the MY\_MODULE.install file, as I'm creating the fields there, and as I understand, you can't set permissions in the install file.

Note, this is just a custom function name, not a hook - you could call it anything.

```
function MY_MODULE_assign_field_permissions($role_name, $permission, $field_name) {
    $permissions = array($permission.' '.$field_name)
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
}

```

`$role_name` is the name of your role, `$permission` is the natural language permission, like 'view own', 'create', 'edit', etc. and finally `$field_name` is the name you gave your field.

Here's how I would call it in my MY\_MODULE.install file to allow the role type `my_role` view their own entries for `field_my_field`:

```
MY_MODULE_assign_field_permissions('my_role', 'view own', 'field_my_field');

```
> 1 votes

---
Tags: 7, users
---


# Question
Title: Lightest setup to sell only digital content with no physical products?
I'm looking for recommendations on how to setup Drupal 7 with the fewest modules so I can charge users to Buy Digital Content (Book Pages) on my site.

I will eventually have several books, and users will need to pay for each one to read (view) them. There are no files to be downloaded here, I will actually try to prevent users from copying the content; they should only have access to the Book.

I looked at the recommended Drupal Commerce, but it seems very much like overkill (many unused features like shipping, packing, inventory) for what I want to do. Not sure it can (easily) handle Digital Content.

If there is no simple solution, can this be easily done in Drupal Commerce?

# Answer
You could get by using Drupal Commerce with just the core modules, some custom Rules, and your preferred payment gateway module. The modules and features you pointed to (shipping, inventory, etc.) and the ones you didn't point out have nothing to do with Drupal Commerce itself. They're all optional contributed modules and don't have to be added if you don't need them.

It's possible you saw a demo site running Commerce Kickstart 2.x. That is a distribution of Drupal that includes Drupal Commerce and a wide variety of contributed modules to make it function more like a robust eCommerce application out of the box. At its core, Drupal Commerce is much lighter weight, and I think you'll find its compatibility with Rules combined with the Content Access / Access Control List modules to be very helpful in selling access to digital content on your site.
> 1 votes

# Answer
Have a look at the payment (API), there's fe. a paypal integration, among others - with this you can skip the shop overhead.
> 0 votes

# Answer
Below are 2 possible alternatives (options) you may want to look at.

# Option 1: A lightweight e-shop

**If** you're only looking for a simple and lightweight e-commerce solution, **Then** have a looking at the Light Shop module. Here is a quote from its project page:

> * Session-stored basket.
> * Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
> * Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
> * Orders history. For each order will be created a separate node.
> * There is no dependence on other modules.
> * Full support for working with anonymous users
> * Integration with Views.

# Option 2: A simple shopping cart

**If** you're only looking for a shopping cart (as in your title), **Then** have a looking at the Basic Cart module. Here is a quote from its project page:

> Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
>
> **Main difference from Ubercart and Commerce:**
>
> The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
>
> **Features:**
>
> * The possibility of choosing the content types that can be added to the cart.
> * The possibility of sending, or not, an email to the customer once an order is placed.
> * Custom email messages for both the site administrator and the customer, along with the order details.
> * Order registration and listing in the administration area using Views module.
> * Integration with Rules module.
> * A block with the contents of your shopping cart.

Here is a screenshot of it (note the "**Checkout**" button also ...):
> 0 votes

---
Tags: 7, nodes, commerce, files
---


# Question
Title: Split Delivery : Drupal Commerce future : 2 qty in differnt Address : Single Order in Multiple Address
I want to create split delivery functionality in Drupal 7. I want to split qty in differnt delivery address.ex Like Product A have 2 qty .I want to deliver 1 qty to my friend house and 1 to my Address.Please give some suggestion?

# Answer
There is no module offering split shipping like this out of the box. The Commerce Shipment module does support making multiple shipments out of the products on an order, but it requires custom code to tell it on what basis the order ought to be split. To date, this has only included support for line item based splits for pre-orders, so you'd need to develop a user interface for selecting products / entering their addresses and the ability to split up individual line items based on quantity.
> 1 votes

---
Tags: forms, commerce, entities, hooks
---


# Question
Title: Drush doesn't detect drupal installation under sites sub-directory
I have been using Drush 4 and 5 with no problem. Now that I have downloaded and installed new **Drush 7.0-dev** using composer, I am having problem i.e it doesn't by-default detect drupal installation when I am on sites sub-folder,

Drush running on sites-root directory,

```
drupal7/sites/example.com/modules/views$ drush status

 Drupal version                  :  7.30
 Site URI                        :  http://example.com
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database port                   :
 Database username               :  example_user
 Database name                   :  example_db
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  bartik
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php5/cli/php.ini
 PHP OS                          :  Linux
 Drush version                   :  7.0-dev
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :
 Drupal root                     :  drupal7
 Site path                       :  sites/example.com
 File directory path             :  sites/example.com/files
 Temporary file directory path   :  /tmp

```

Drush running under sites-subdirectory,

```
drupal7/sites/example.com/modules/views$ drush status

 Drupal version         :  7.30
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  drupal7

```

So, how do I configure Drush, is there anything I can do to make it work, I don't want to use `--uri` or `-l` flag or any other options everytime.

**Update**

Also when I download modules it get downloaded on `sites/all/modules` directory

```
drupal7/sites/example.com/modules$ drush dl webform
Project webform (7.x-3.20) downloaded to drupal7/sites/all/modules/webform.                                     [success]

```

But if I am on sites-root directory it works fine,

```
drupal7/sites/example.com$ drush dl webform
Project webform (7.x-3.20) downloaded to /home/sysop/project/drupal7/htdocs/sites/heisenberg.com/modules/webform.                          [success]

```

# Answer
You need to add an alias conf file named `YOUR_SITE_NAME.aliases.drushrc.php` in sites\all folder with that code.

```
// The site in sites/YOUR_SITE_NAME/
$aliases['YOUR_SITE_NAME.local'] = array(
  'uri' => 'YOUR_SITE_NAME_URI',
  'root' => '/path/to/drupal_root_folder',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);

```

Then clear cache : drush cache-clear drush.

Test your alias : `@YOUR_SITE_NAME.local status`.

To run a command, for the sake of example : `@YOUR_SITE_NAME.local mb MODULE_NAME hook1 hook2 --write`

---

**UPDATE :** **in order to create automatically Drush site aliases** for many sites, place this code in your `aliases.drushrc.php` file. Drush will look for `aliases.drushrc.php` in the ".drush" folder in your home directory (see this post to get sure where to put this file).

```
$aliases = array();
$drupal = '/var/www/drupal';

// Automatic alias for each Drupal site
$site = new DirectoryIterator($drupal . '/sites');
while ($site->valid()) {
  // Look for directories containing a 'settings.php' file
  if ($site->isDir() && !$site->isDot() && !$site->isLink()) {
    if (file_exists($site->getPathname() . '/settings.php')) {
      // Add site alias
      $basename = $site->getBasename();
      $aliases[$basename] = array(
        'uri' => $basename,
        'root' => $drupal,
      );
    }
  }
  $site->next();
}

// Get all site aliases
$all = array();
foreach ($aliases as $name => $definition) {
  $all[] = '@' . $name;
}

// 'All' alias group
$aliases['all'] = array(
  'site-list' => $all,
);

```

You can also read this : create your own drush aliases. You could even think about managing synchronization between remote and local systems (source).

**EDIT :** as per ericx comment, consider adding `bash-completion`. Drush comes with a bash-completion file, `drush.completion.sh`, which offer alias completions.
> 4 votes

# Answer
I would suggest getting the 6.x version which is the stable version for D7 (yes, the versioning is slightly confusing :). You should be able to isntall it with

```
composer global require drush/drush:6.*

```
> 2 votes

# Answer
Take a look at Drush Aliases.

They essentially let you *target* your Drupal installations to run your `drush` commands on.
> 0 votes

# Answer
This may sound silly, but make sure there is a settings.php file in drupal7/sites/example.com/ and drush/drupal has access to edit that file

--or--

try using the --uri parameter:

drush dl --uri=http://example.com webform
> 0 votes

# Answer
In my case it turned out that I needed to install mysql-client:

```
apt-get install mysql-client

```

I had the following situation: drush 4, 5 and 6 worked fine for me. drush 7, 8 don't work (different errors, including that ones you're describing). And my MySQL database was located on a separate server.

HTH, Alexander
> 0 votes

# Answer
I was not able to run drush from inside the drupal directory post reinstalling drush. It turns out there was a symlink to drush inside that directory that was causing recursion and therefore drush was failing. Removed the symlink and was able to run drush from the directory again.
> 0 votes

---
Tags: 7, drush
---


# Question
Title: How to override markup in my .theme file?
Below is markup from `SearchController.php` file. I want to change the "**Search results**" from my search page and also markup.

*File : \core\modules\search\src\Controller\SearchController.php*

```
if (count($results)) {
  $build['search_results_title'] = array(
    '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
  );
}

```

# Answer
I am afraid there is no way to fix this markup in *theme* file. In case you simply need to change spelling I suggest using string overrides as it is described in *settings.php* file.

```
$settings['locale_custom_strings_en'][''] = [
  'Search results' => 'New text',
];

```
> 0 votes

---
Tags: theming, 8, hooks
---


# Question
Title: Avoid user to multiple purchase of same product
I would like avoid a user to buy the same product twice or more, I'm not speaking about the quantity limitation during the checkout (I've already set quantity to 1 for every purchase)...for example..after a user has bought a product(He has completed the checkout process) I want that he can't buy again this product. Could you help me? Thank you in advance!

# Answer
> 0 votes
The best way to do this would be to use the method (How do I prevent a product from being added to the cart?) but implement custom logic to look for that product being purchased by the customer.

You can do this by using `EntityFieldQuery()` and loading all of the user's orders and then you can loop through the line items and look for the product...

```
$orders = commerce_order_load_multiple(array(), array('uid' => $user->uid, 'status' => 'completed'));
foreach ($orders as $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->commerce_product()->sku->value() == 'SOMESKU') {
    //user has bought it
    }
  }
}

```

# Answer
> 0 votes
This is how I have it done, it works very well!!.

Create rule, name it "avoid duplicates in cart rule; react on Event: before adding a product to the cart, save Add your conditions, in my case no conditions In Actions add Loop list: data selector: select commerce-order:commerce-line-items Variable label: List current line item Variable name: list\_current\_line\_item save changes Components-\>add new component Component plugin: rule name: "avoid duplicates in cart component of rule"

Variables: Data type: Commerce line item. Label: Commerce line item label. Machine name: commerce\_line\_item\_variable. (this is the line item from the loop in the main rule, just to explain it) Data type: Commerce product. Label: Commerce product label. Machine name: commerce\_product\_variable. (this is the product add to the cart, just to explain it) Save Add condition Entity has field Entity: commerce-line-item-label Field: commerce\_product Save (this condition give us the actual product line item in the cart, just to explain it).

Add condition Data comparison. Data to compare: commerce-line-item-variable:commerce-product Continue Operator: equals Data value: with product-added-to-cart Save

Add action to the component: Remove an item from a list. List: commerce-line-item-variable:order:commerce-line-items Item to remove: commerce-line-item-variable (This action remove the duplicated product (the old) from the cart, just to explain it).

Add another action to the component: System: Show a message on the site Message: Duplicated item has been deleted from the cart. Save

Now come on, exit from the component rule and return again to main rule, edit it again.

Add action to the loop Select action to add: Component: "avoid duplicates in cart component of rule". and set the variables. Commerce line item label: lista-current-line-item Commerce product label: commerce-product Save

And you are very happy, no more repeated products in cart. :) Enjoy

# Answer
> 0 votes
This is what I figured out based on some other answers. Modify the part around 'form\_set\_error' to customize what happens. If you need multilingual support you'll need to modify this further because I did a lousy job of that part. I might have gone overboard assuming a cart line item can contain multiple products, so I've added comments to point that out - it could probably be simplified in most cases.

This would go in a custom module (good idea to have one for each site you make), and change YOURMODULE accordingly. Don't forget to clear your cache so the hook function is found by Drupal.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOURMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  array_unshift($form['#validate'], 'YOURMODULE_cart_validate');
}

/*
 * Callback used with YOURMODULE_form_commerce_cart_add_to_cart_form_alter().
 */
function YOURMODULE_cart_validate(&$form, &$form_state) {
  // Pull up the current cart data.
  $order = commerce_cart_order_load($form_state['values']['uid']);

  // This is not a multi-lingual site so I just use 'und' as the language.
  // It seems $order contains some language info, but mine is blank so I
  // don't know how to use it properly.
  $lang = LANGUAGE_NONE;

  // This is the id of the product the user is attempting to add to cart.
  // This handles multiple products being added at once, which I've never seen
  // before but it's set up like an array so who knows...
  $attempted_product_ids = array();
  foreach ($form_state['line_item']->commerce_product[$lang] as $product) {
    $attempted_product_ids[] = $product['product_id'];
  }

  // Prepare to collect cart line items.
  $ids = array();

  // Check if cart has items.
  if (!empty($order->commerce_line_items[$lang])) {

    // Collect cart line item ids.
    foreach ($order->commerce_line_items[$lang] as $line_item) {
      $ids[] = $line_item['line_item_id'];
    }

    // Get the line items based on the line item ids.
    $line_items = commerce_line_item_load_multiple($ids);

    // Check each line item.
    foreach ($line_items as $line_item) {

      // Check the line item has products.  It should though, right?
      if (!empty($line_item->commerce_product[$lang])) {

        // Check each product.  I don't know if a line item can have multiple
        // products, but it is an array so I guess it's possible?
        foreach ($line_item->commerce_product[$lang] as $existing_product) {

          // Compare the existing product id and the attempted add to cart product.
          if (in_array($existing_product['product_id'], $attempted_product_ids)) {

            // Load the product so we can get its title and sku for the error message.
            $product = commerce_product_load($existing_product['product_id']);

            // Produce an error message and prevent submission of the 'add to cart' form.
            form_set_error('product_id', t("You've already added %product (%sku) to !cart.", array(
              '%product' => $product->title,
              '%sku'     => $product->sku,
              '!cart' => l(t('your cart'), 'cart/my'),
            )));

          }

        }

      }
    }

  }

}

```

---
Tags: commerce, rules
---


# Question
Title: Why Manage_fields and Manage_display tab are not shown in content type?
Suddenly My dev site is not showing

> Manage\_fields and Manage\_displays

in all content types. I am using contributed module admin\_menu. I clear all cache but it happens same. This is multilingual site. I can't understand why it occurs? Can anyone solve this problem? I have enabled field\_ui modules.

# Answer
> 0 votes
There is unchecked permission of field. After checked it shows the tabs. Make sure two things to solve this problem. 1. Enable Field UI (field\_ui) module 2. Make sure the field in permission is checked

> admin \> people \> permissions

---
Tags: 7, entities
---


# Question
Title: How do you set a one-off access checker on a route?
As far as we can tell, the "Simplified custom access checker" section of the handbook is outdated. The entirety of `CheckProvider` seems to be service oriented and this is the provider which has the `$route->setOption('_access_checks', $checks);` call. In turn, `AccessManager::check` has a `$checks = $route->getOption('_access_checks') ?: array();` call. There's nothing which would accommodate one-off checkers like the handbook page suggests:

```
requirements:
  _custom_access: '\Drupal\example\Controller\ExampleController::access'

```

and based on our debugging, this is indeed not working. What is the current way, if any, to do this?

# Answer
> 5 votes
The handbook is correct. The access is handled by services. The normal way to implement a custom access check is to define a service in **mymodule.services.yml**. See this example from the core book module:

```
  access_check.book.removable:
    class: Drupal\book\Access\BookNodeIsRemovableAccessCheck
    arguments: ['@book.manager']
    tags:
      - { name: access_check, applies_to: _access_book_removable }

```

And then use this in routing:

```
_access_book_removable: 'TRUE'

```

Here you can choose your own arbitrary naming schema.

As described in the handbook, if you want to simplify this, you can reuse the service `access_check.custom`, which is already defined in **core.services.yml**:

```
  access_check.custom:
    class: Drupal\Core\Access\CustomAccessCheck
    arguments: ['@controller_resolver', '@access_arguments_resolver_factory']
    tags:
      - { name: access_check, applies_to: _custom_access }

```

Then you have to use `_custom_access:` for the route. You can not use something like `_my_module_access`: as before, the key must match the tag in the service definition.

The first solution puts the complete logic of the access check in a service and makes it reusable and self-explanatory. If you only need the access code in one route and want to place the access code in the controller class the second method provides a shortcut.

---
Tags: 8, routes
---


# Question
Title: Get the before and after values of a node field
I need to compare the **before** save/update value with the **after** save/update value of a node field.

Example: There is an already existing node with the title of "Hello". I then edit the node and change the title to "World".

I need to get the before value of "Hello".

```
function mymodule_node_presave($node){

    $before = $node->title;
    drupal_set_message($before, 'error');

}

function mymodule_node_update($node){

    $after = $node->title;
    drupal_set_message($after, 'warning');

}

```

But I always keep getting the same value...

**Did I just discover a drupal bug? or what? Because I've used this method in the past with user hooks and it works as expected:**

```
function mymodule_user_presave(&$edit, $account, $category) {

     $before = $account->field_custom['und'][0]['value'];
     drupal_set_message($before, 'error');

}

function mymodule_user_update(&$edit, $account, $category) {

     $after = $account->field_custom['und'][0]['value'];
     drupal_set_message($after, 'warning');

}

```

# Answer
> 3 votes
For new created nodes in hook\_node\_update you will never get any old values for any `$node` fields. Use `node_load($node->nid)` to load the previous instance of the `$node` and do any comparisons with it. You can also use `$node->original` to view the commited values to the database.

---
Tags: 7, nodes, hooks
---


# Question
Title: How to create view of taxonomy terms and then once clicked on taxonomy term another view will be opened displaying all content having that term?
I have a taxonomy called "Destination Type". There are 4 terms in it (Historical, Leisure, Wildlife,Cultural). I have created one content type called "Destination" with taxonomy field "destination\_type". Now I want to create a view of taxonomy "destination type" which is I am able to create. Once user click on any of the term in that view say Historical, then the next view should open displaying the list of all destinations with destination type as historical.

This is how I want the result same as "Jump right in, Things to do" in http://www.gotobermuda.com/

I am stuck here. Please help me out with this

Thank you

# Answer
I get it working. It was not that hard :)

First I create the view of taxonomy term. In that view I add contextual filter "Taxonomy term : term ID".

And in the next view I add contextual filter "Content: content\_type\_name"

Thats it. Got the desired result.
> 0 votes

---
Tags: 8, views
---


# Question
Title: can i use entity id instead of node id to load node with node_load() function
can i use entity id instead of node id to load node with node\_load() function coz i don't find any difference between entity id and node id . both node id and entity id return same result

```
$e_id = node_load($entity_id);
dpm($e_id);
$n_id = node_load($node_id);
dpm($n_id);

```

both *$e\_id* and *$n\_id* return exactly same result

# Answer
The node ID *is* the entity ID for the node entity type.

As they're the same thing, the answer to your specific question can only be "yes".
> 2 votes

---
Tags: hooks
---


# Question
Title: Drupal 8 - how do I extract the URL path from node title
I can print title of my `content-type` using `{{ fields.title.content }}`. and it renders like `<a href='...'>Title of the content</a>`. I have created a `View` (view mode: field) and showing a list of available products on that page. To customize look and feel of the page I copied `views-view-fields.html.twig` file from `core/themes/stable/template/views` under my theme's template directory and customized it the following way.

```
<div class="col-md-2 col-sm-2 col-xs-12">
    <div class="box-gray-border-only border-radius-5 padd-all-5">
        {{ fields.field_product_image.content }}
    </div>
</div>
<div class="col-md-10 col-sm-10 col-xs-12">
    <h3 class="item-list-title-anchor margin-auto larger">{{ fields.title.content }}</h3>
    <p class="margin-t10 small">{{ fields.field_product_summary.content|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES') }}</p>
</div>
<div class="clearfix"></div>
<div class="row">
    <div class="col-md-12 col-sm-12 col-sx-12 text-right">
        <span>{{ fields.field_category.content }}</span> |
        <span><b class="text-red">Price: {{ fields.field_product_price.content }}</b></span>
        <a title="{{ fields.content.title }}" class="btn btn-warning" href="{{ path('entity.node.canonical', { 'node' : node.id}) }}">View »</a>
    </div>
    <div class="clearfix"></div>
</div>
<div class="margin-t20"></div>
<hr />

```

The title itself is linked to product's page. But I have an additional View button which I want to link to the product page separately as well. In order to accomplish the same I tried to extract the `URL` part from the `title` with `{{ path('entity.node.canonical', { 'node' : node.id}) }}`. But it gives me the following error message.

> Symfony\Component\Routing\Exception\InvalidParameterException: Parameter "node" for route "entity.node.canonical" must match "\d+" ("" given) to generate a corresponding URL. in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 193 of core\lib\Drupal\Core\Routing\UrlGenerator.php).

I am referring to this article: https://chromatichq.com/blog/creating-links-within-twig-templates-using-path-and-url

What I did wrong?

This is what I want to achieve:

I used `{{ dump(fields.title.content) }}` to see if I the `URL` could be accessible, but there was nothing like it.

# Answer
> 4 votes
Try `{{ path('entity.node.canonical', { 'node' : row.nid}) }}`. Also it is better to use `kint` or `devel_dump` for twig debug.

---
Tags: theming
---


# Question
Title: Views contextual filters programmatically alter add to or
I have 2 fields in my contextual filters. Obviously, the default join is AND but I'd like to filter on one or the other field depending on which one of two arguments is provided.

I tried the following approach:

```
function mymodule_views_query_alter(&$view, &$query){

    if($view->name == 'my_links'){
        switch ($view->current_display) {
            case 'page_2':
                // dsm($query, 'Query');
                $query->where[0]['type'] = 'OR';
            break;

            default:
                # code...
            break;
        }
    }
}

```

However, using the devel module to inspect the Views data, the type field in the where section of my View still outputs **AND** instead of **OR**.

Which means my attempts to alter my View is not working.

Can anyone help me get this working?

# Answer
If you have a way of knowing both filter values (like NULL and 12), then I would use hook\_views\_pre\_build and unset the NULL field.

```
function test_views_pre_build(&$view) {
  // Do some checks for view name and current_display
  unset($view->display_handler->handlers['argument']['null_field']);
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: linking multiple node types to each other
I have 2 node types, complaints and solutions. Every node type has multiple fields.

How can I link multiple solutions to a complaint?
And the other way around, how can I link a solution to multiple complaints?

-Complaint1 -\> Solution1, Solution2, Solution3

-Solution 1 is linked to Complaint1, Complaint2, Complaint3

With entity reference I can only link one on one relations. The relations module seemed promising, but it seems it's only for admin users.

# Answer
Okay, I haven't test this out, but I think this should work:

1. You first need a way to generate a taxonomy term for each Complaint node. I think that the NAT could help with that or through Rules.
2. Next, add a term reference field for Solutions, enable multiple selections but disable the ability to create terms.
3. Override the term reference view for that particular vocabulary through a custom url using Pathauto, this would be the "Complaint1 -\> Solution1, Solution2, Solution3" part
4. For "Solution 1 is linked to Complaint1, Complaint2, Complaint3", you already have links to the taxonomy term simply by displaying the field in your node. You could also do this through views.

Done! Hope it works!
> 0 votes

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


# Question
Title: Delaying form submission via Javascript doesn't work in IE
I have a form built for creating an instance of a custom entity. Upon submitting the form, I have a jquery script completing some actions on the page that need to execute before the form submits, so I attempt to stop the default event, perform those actions, and then resume the event as follows:

```
$('#submit').on('click', function(event){
    if (valid === true) {
        valid = false;
        return;
    }
    event.preventDefault();
    valid = true;
    //do some stuff
    $(this).trigger('click');
});

```

This works perfectly in Chrome, but unsurprisingly does not work in IE11. Through console logging I see that the re-click is fired, but the `return` line simply does nothing, so the button click does not submit the form at all. I have tried some alternatives to `$(this).trigger('click');` explained in a stackoverflow thread, but nothing is getting it to work.

The reason I'm creating a Drupal-specific thread about it is that I also tried to skip re-firing entirely and just do a form submission like this:

```
$('#submit').on('click', function(event){
    event.preventDefault();
    //do some stuff
    $('form[data-drupal-selector="my-form-id"]').submit();
});

```

But this, for whatever reason, clears all of the data in any field collection items contained within the form.

Is there any feasible way to do what I'm trying to accomplish in Drupal that works in all modern browsers?

# Answer
> 3 votes
Try doing something like:

```
 $("form").submit( function () {
   //do something
   return true;
 }

```

Source

---
Tags: 8, forms
---


# Question
Title: Execute custom JavaScript code after Webform has been submited with Webform Ajax Module
I have an Webform that uses Webform Ajax modules, Steps module and few others.

I would like to execute some custom JavaScript code after the WebForm has been validted and submited.

I know I could execute custom PHP code by modyfing `function _webform_ajax_callback_completed($form, $form_state) {...}` inside of `webform_ajax.module`:

```
elseif ($form['#node']->webform['webform_ajax'] == WEBFORM_AJAX_CONFIRM){
...
//my custom code
...

```

**But I don't want to mess with this module's code.** And I want to execute JavaScript not PHP code.

Is there an way to do so, e.g. via some hook? Or maybe I can detect that form has been submited in JavaScript?

# Answer
Okay, try this. After the ajax request is completed on "#myform", it runs the function.

```
$("#myform").bind('ajax:complete', function() {

     // tasks to do

});

```

Source | API Documentation
> 1 votes

---
Tags: 7, ajax, webforms
---


# Question
Title: Views bulk operations interrupted due to insufficient rights
I created a view to replace the default view of the members page of the "Group" module. When I am a site administrator the mass operation works.

When I am an authenticated user (No administrator of the site) and I select members to block them with mass operation, members are still active and the following error appears in the log (see screenshot).

When I disable my view and use the module's default view. Everything works fine.

Here is the export of my view :

```
$view = new view();
$view->name = 'group_members';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'group_membership';
$view->human_name = 'Membres';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Liste des membres';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
  9 => '9',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
/* Entête: Global : Texte non filtré */
$handler->display->display_options['header']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['table'] = 'views';
$handler->display->display_options['header']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['empty'] = TRUE;
$handler->display->display_options['header']['area_text_custom']['content'] = '<strong>Légende :</strong></br>
Actif = fait partie du groupe et a accès aux offres groupées.</br>
Bloqué = fait partie du groupe mais n\'a plus accès aux offres groupées.</br>
Invité = a été invité dans le groupe mais n\'a pas encore accepté l\'invitation.';
/* Pied de page: Global : Texte non filtré */
$handler->display->display_options['footer']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['footer']['area_text_custom']['table'] = 'views';
$handler->display->display_options['footer']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['footer']['area_text_custom']['empty'] = TRUE;
$handler->display->display_options['footer']['area_text_custom']['content'] = '<strong>Instructions :</strong></br>
<u>Pour démarrer une commande groupée :</u></br>
Étape 1 : mettre à jour la liste des membres.</br>
Étape 2 : aller sur la page du groupe et cliquer sur "Démarrer la vente".</br>
Étape 3 : compléter les dates et confirmer "Démarrer la vente".</br>
<u>Pour arrêter une commande groupée :</u></br>
Étape 1 : aller sur la page du groupe et cliquer sur "Arrêter la vente".</br>
Étape 2 : confirmer "Arrêter la vente".</br>
</br>
<i>Pour plus de détails, veuillez consulter la question suivante :</br>
lien</i>';
/* Comportement en l'absence de résultats: Global : Zone de texte */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'Vous n\'avez aucun membre dans votre groupe.';
$handler->display->display_options['empty']['area']['format'] = 'plain_text';
/* Relation: Adhésion au groupe : Groupe gid */
$handler->display->display_options['relationships']['group']['id'] = 'group';
$handler->display->display_options['relationships']['group']['table'] = 'group_membership';
$handler->display->display_options['relationships']['group']['field'] = 'group';
/* Relation: Adhésion au groupe : Utilisateur uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'group_membership';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Champ: Opérations en masse : Adhésion au groupe */
$handler->display->display_options['fields']['views_bulk_operations_1']['id'] = 'views_bulk_operations_1';
$handler->display->display_options['fields']['views_bulk_operations_1']['table'] = 'group_membership';
$handler->display->display_options['fields']['views_bulk_operations_1']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations_1']['label'] = '';
$handler->display->display_options['fields']['views_bulk_operations_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['views_bulk_operations_1']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations_1']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations_1']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations_1']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations_1']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations_1']['vbo_operations'] = array(
  'rules_component::rules_block_a_group_membership' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 1,
    'label' => 'Bloquer les membres sélectionnés',
  ),
  'rules_component::rules_unblock_a_group_membership' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 1,
    'label' => 'Débloquer les membres sélectionnés',
  ),
);
/* Champ: Groupe : ID du groupe */
$handler->display->display_options['fields']['gid']['id'] = 'gid';
$handler->display->display_options['fields']['gid']['table'] = 'groups';
$handler->display->display_options['fields']['gid']['field'] = 'gid';
$handler->display->display_options['fields']['gid']['relationship'] = 'group';
$handler->display->display_options['fields']['gid']['exclude'] = TRUE;
/* Champ: Utilisateur : Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'user';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Champ: Utilisateur : Nom */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_3']['id'] = 'nothing_3';
$handler->display->display_options['fields']['nothing_3']['table'] = 'views';
$handler->display->display_options['fields']['nothing_3']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_3']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['nothing_3']['alter']['text'] = '[name]';
$handler->display->display_options['fields']['nothing_3']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_3']['alter']['path'] = 'group/[gid]/member/[uid]';
/* Champ: Utilisateur : Courriel */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'user';
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Champ: Adhésion au groupe : Statut de membre */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'group_membership';
$handler->display->display_options['fields']['status']['field'] = 'status';
$handler->display->display_options['fields']['status']['label'] = 'Statut';
/* Champ: Adhésion au groupe : Group role */
$handler->display->display_options['fields']['role']['id'] = 'role';
$handler->display->display_options['fields']['role']['table'] = 'group_membership';
$handler->display->display_options['fields']['role']['field'] = 'role';
$handler->display->display_options['fields']['role']['label'] = 'Rôles';
$handler->display->display_options['fields']['role']['separator'] = '';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_2']['id'] = 'nothing_2';
$handler->display->display_options['fields']['nothing_2']['table'] = 'views';
$handler->display->display_options['fields']['nothing_2']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_2']['label'] = 'Metadata';
$handler->display->display_options['fields']['nothing_2']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['text'] = 'metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['path'] = 'group/[gid]/member/[uid]/metadata';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'Modifier';
$handler->display->display_options['fields']['nothing']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'modifier';
$handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['path'] = 'group/[gid]/member/[uid]/edit?destination=group/[gid]/member';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'Supprimer';
$handler->display->display_options['fields']['nothing_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = 'supprimer';
$handler->display->display_options['fields']['nothing_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['path'] = 'group/[gid]/member/[uid]/cancel?destination=group/[gid]/member';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_4']['id'] = 'nothing_4';
$handler->display->display_options['fields']['nothing_4']['table'] = 'views';
$handler->display->display_options['fields']['nothing_4']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_4']['label'] = 'Actions';
$handler->display->display_options['fields']['nothing_4']['alter']['text'] = '[nothing_2]   [nothing]   [nothing_1]';
/* Filtre contextuel: Adhésion au groupe : Groupe gid */
$handler->display->display_options['arguments']['group']['id'] = 'group';
$handler->display->display_options['arguments']['group']['table'] = 'group_membership';
$handler->display->display_options['arguments']['group']['field'] = 'group';
$handler->display->display_options['arguments']['group']['default_action'] = 'default';
$handler->display->display_options['arguments']['group']['exception']['title'] = 'Tout';
$handler->display->display_options['arguments']['group']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['group']['default_argument_options']['index'] = '1';
$handler->display->display_options['arguments']['group']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['group']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['group']['summary_options']['items_per_page'] = '25';
/* Critère de filtrage: Adhésion au groupe : Statut de membre */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'group_membership';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = array(
  'active' => 'active',
  'blocked' => 'blocked',
  'invited' => 'invited',
);
$handler->display->display_options['filters']['status']['exposed'] = TRUE;
$handler->display->display_options['filters']['status']['expose']['operator_id'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['label'] = 'Filtrer les membres';
$handler->display->display_options['filters']['status']['expose']['operator'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['identifier'] = 'status';
$handler->display->display_options['filters']['status']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  5 => 0,
  8 => 0,
  4 => 0,
  9 => 0,
  7 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['status']['expose']['reduce'] = TRUE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'group/%/member';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Membres';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['weight'] = '0';
$translatables['group_members'] = array(
  t('Master'),
  t('Liste des membres'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('<strong>Légende :</strong></br>
Actif = fait partie du groupe et a accès aux offres groupées.</br>
Bloqué = fait partie du groupe mais n\'a plus accès aux offres groupées.</br>
Invité = a été invité dans le groupe mais n\'a pas encore accepté l\'invitation.'),
  t('<strong>Instructions :</strong></br>
<u>Pour démarrer une commande groupée :</u></br>
Étape 1 : mettre à jour la liste des membres.</br>
Étape 2 : aller sur la page du groupe et cliquer sur "Démarrer la vente".</br>
Étape 3 : compléter les dates et confirmer "Démarrer la vente".</br>
<u>Pour arrêter une commande groupée :</u></br>
Étape 1 : aller sur la page du groupe et cliquer sur "Arrêter la vente".</br>
Étape 2 : confirmer "Arrêter la vente".</br>
</br>
<i>Pour plus de détails, veuillez consulter la question suivante :</br>
lien</i>'),
  t('Vous n\'avez aucun membre dans votre groupe.'),
  t('Groupe'),
  t('Utilisateur'),
  t('- Choisir une opération -'),
  t('Bloquer les membres sélectionnés'),
  t('Débloquer les membres sélectionnés'),
  t('ID du groupe'),
  t('.'),
  t(','),
  t('Uid'),
  t('Nom d\'utilisateur'),
  t('[name]'),
  t('Courriel'),
  t('Statut'),
  t('Rôles'),
  t('Metadata'),
  t('metadata'),
  t('Modifier'),
  t('modifier'),
  t('Supprimer'),
  t('supprimer'),
  t('Actions'),
  t('[nothing_2]   [nothing]   [nothing_1]'),
  t('Tout'),
  t('Filtrer les membres'),
  t('Page'),
);

```

Here is the Rules debug log :

# Answer
I was able to create a similar scenario. Long story short:

* for my admin user (`user/1`) everything works as desired (as in your case).
* for an authenticated user which is not an admin, I also get a similar message in the log, which looks like so:

> Skipped ***Block a group membership*** on group\_membership Member Demo.User in Drupal for Sitebuilders ***due to insufficient permissions***.

Additionally, after I enable the Rules log for the admin user, I get a log that looks like so:

* Reacting on Event *Drupal is initializing*.
* Executing action rule: *Block a group membership*.
* Reacting on Event *Drupal is initializing*.

If however I perform the same scenario with the non-admin user, a similar Rules log does NOT include that "Executing action rule: *Block a group membership*.". That explains why your "members are still active" (as in your question), simply because the actual Rules Component related to that VBO action was not executed.

As a potential remedy, have a look at the VBO issue "Custom Action Stopped Working", which appears to be similar, and includes some possible work around (such as going back to a prior VBO release, if that's what you want to do ...). But this issue also appears to be related to "Default action behaviors in getAccessMask()". And that issue contains a patch attached to comment nr 29, which in subsequent comments seems to confirm that it does solve the issue (I've not QA-tested that patch ...).

I'm afraid that the above is "as good as it gets" for now ...

**Update**: even though I've not QA-tested it (yet), it seems that the patch mentioned in https://www.drupal.org/node/1334088#comment-11870650 is a fix for it (credits: Mathieu)
> 0 votes

---
Tags: 7, rules, views, group
---


# Question
Title: Enroll user on course module error due to permissions
I want that a role called "Profesor" can enroll users on a course created using the course module, using the course-enrollments/search-add view but I'm getting the following error:

Type: views bulk operation User: profesor1 Message: Skipped Enroll user on user alumno2 due to insufficient permissions.

Here is my permissions configuration:

Administrator can enroll users, any help?

EDIT:

The course permissions are configured as follows:

# Answer
> 0 votes
I haven't used the course module in quite a while but aren't there other permissions specific to the module itself?

# Answer
> 0 votes
Your issue appears to be similar to the VBO issue "Custom Action Stopped Working", which includes some possible work around (such as going back to a prior VBO release, if that's what you want to consider ...).

But this issue also appears to be related to "Default action behaviors in getAccessMask()". And that issue contains a patch attached to comment nr 29, which in subsequent comments seems to confirm that it does solve the issue (I've not QA-tested that patch ...).

---
Tags: users, views
---


# Question
Title: Multiple relationships in Views Contextual Filters
I use Views in every project, and its not that often that I run into a use case like this any more.

In the set up below, I have a Content type with two field collection fields (day guest and evening guest). I want to display the results of both field collection fields on the node, in the same view.

Both field collections share an "E-mail" field, and when a user enters their e-mail field, I want them to see their results, whether they have been added as a day guest, or an evening guest.

Here's the setup...

When I remove one of the two Contextual filters, the results show for the remaining field, and vice versa. But when both Contextual filters are added, I get no results.

Is there a way to do an AND or OR for Contextual filters?

Or in the Contextual filter options, a way to add multiple relationships like below?

While I know this is not possible in the default behaviour, it is a good example of what i'm trying to achieve, perhaps someone knows a decent workaround to the issue?

# Answer
> 0 votes
Use this module: https://www.drupal.org/project/views\_contextual\_filters\_or it gives you posibility to achive your needs

---
Tags: 7, views
---


# Question
Title: Adding an information icon to a form element
I currently have a number of form elements that I have added an image icon to, which users can click on or hover over for more information... which looks like this:

*(The blue image icon is the one users hover over for more information)*

When defining the component via render arrays like so:

```
$component[$this->componentName] = array(
  '#type' => 'textfield',
  '#title' => t('Project Name'),
  '#description' => t('Enter the name of the project'),
  '#description_display' => 'before',
  '#required' => 'True',
);

```

Is there away to get the image icon to sit along side the element (either the title or the description or the textfield), for example like this:

I am aware that there is the potential to use something like the #attributes tag to add tooltips too (as outlined below), but wondered whether there is scope to add the image icon as I am attempting?

```
'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  '#attributes' => array(
    'title' => t("Item's name, no longer than 45 characters."),
  )
),

```

# Answer
JS/jQuery Solution:

Use after(): the sibling right after selector;

```
var moveEl = ".INFO-ICON";
var moveElementAfter = ".PROJECT-LABEL";

$(moveElementAfter).after( $(moveEl) );

```
> 0 votes

# Answer
You can use `'#prefix' => 'Some title <img src="/some/image/source">'` instead of `'#title' => t('Name')`

```
$component[$this->componentName] =  array(
                  '#prefix' => t('Some title*') .' <img src="/some/image/source">',
                  '#type' => 'textfield',
                  '#size' => 30,
                  '#maxlength' => 45,
                  '#default_value' => $item->Name,
                  '#attributes' => array(

                  );

```

You can add any markup to '#prefix' element of this array.

Or you can add markup even directly to title `'#title' => t('Some title*') .'<img src="/sdfsf">'`, but i think there can be some issues with asterisk when a field is required.
> 0 votes

# Answer
A few options come to mind:

1. Simplest would be css pseudo class ':after', and I'm sure with a 'title' attribute and little `js` would be an easy hack.
2. A twig suggestion can get you access to that form element template. To start make sure you have `parameters.twig.config: { debug: true
...` in your service.yml, in order to see template suggestions in your html.

Then you need to add it and `cache:rebuild`:

```
function MODULE_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {

$type = isset($variables['element']['#type']) ?
 $variables['element']['#type'] : '';
$type = preg_replace("/[^A-Za-z0-9?! ]/", '_', $type);
$suggestions[] = 'form_element__' . $type;
...
 }

```

You will get a template to theme like `form-element--textfield.html.twig` and you can add you variable to that template, or you can add more suggestions based on your $variables, and you can also get between your form code and this template with `MODULE_preprocess_field(..`

3. A FieldWidget would let you select a different option in your form manager ui. You would need to copy and specify your own annotation of the plugin for the widget in core `/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/StringTextfieldWidget.php`
> 0 votes

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


# Question
Title: How could I allow content editors to send email to a selected bunch of users?
I have a content editor that wants to be able to send emails on a regular basis to a selected bunch of users. Could I create a view of all site users and use Views Bulk Operations for this?

# Answer
If your content editors need to be able to select the group they are contacting you can use Views Send. You can also use Rules (and probably Views Rules to ease the process of writing the rule some) particullarly if the editors are not going to be editing the message (if they are sending a notice about content updates or something similar).
> 2 votes

# Answer
Maybe the Views Send module.

It sends an email for each row and you can use tokens for the body and subject. I think it'll work.
> 2 votes

# Answer
Just install the Forena module and use the delivered sample **Active Users Email**, locáted in relative path `/reports/drupaladmin.sample_active_users_letter`.

Adapt the template for the actual eMail body to fit your needs.
> 1 votes

---
Tags: emails, views
---


# Question
Title: How to create a rule that grants user points after a user passed a quiz?
I'm using Drupal 7 and the Quiz module (version 7.x.5.x).

I'd like to grant User Points to a user whenever a user answers correctly. I have to use the Rules module and I wonder how I can create a Rule for it, like what's the Rules Event, the Rules Condition(s), etc...).

Note that I have set the percentage of passing at 75%.

I prefer not to code anything or use the Quiz userpoints module because I had some troubles in the past with this Quiz userpoints module.

**Update**: I tried the 2nd rule included in revision 2 of the answer below. But it only grants the points whenever users take a test, no matter whether they passed it or failed it.

# Answer
# If using Quiz 7.x-5.x

Assuming you're using the 7.x-5.x version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.

To do so, you can start from the delivered rule, which looks like so:

```
{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and apply these changes:

* Add these extra Rules Conditions:
    + entity is of type (to make the data about the Quiz node available, such as pass rate).
    + verify if the user taking the Quiz actually passed.
* Add another Rules Action to grant an amount of User Points that you may want to be related to `[quiz-result:score]` (note that this token is also shown in the Rules example above, within the Rules Action), e.g. an amount that equals the score of the Quiz. If you're not familiar with how to use Rules to grant user points, then have a look at the answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?" (which also includes a Rules example to make that happen).

After you added this extra Rules Condition and Rules Action, your rule should look similar to this rule:

```
{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "userpoints_rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "Congratulations, you passed this quiz with a score of [quiz-result:score] % ..." } },
      { "userpoints_action_grant_points" : {
          "user" : [ "quiz-result:uid" ],
          "points" : [ "quiz-result:score" ],
          "tid" : "0",
          "entity" : [ "quiz-result" ],
          "description" : "Points earned because of your results in the quiz.",
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

Just use the Rules UI to import the above rule and you should (more or less) be ready to go. Possibly the only remaining tuning you want to do in this rule is like so:

* Review the various settings of the Rules Action to grant User Points (eg the amount (= `quiz-result:score` in the rule above), the description and the category for the points.
* Optionally also review the messages being shown when a user passes a quiz. Using the above rule, you'll get a messages similar to this example:

> Congratulations, you passed this quiz with a score of 80 % ...

That message is also followed by a related message produced by the User Points module, which looks like in this example:

> You just earned 80 points and now have 29.512 points in the General category.

**Attention**: be aware that the above rule will grant user points over and over again, since there is no validation (Rules Condition) if the user taking the quiz already passed the quiz before. If you also want to get that resolve (= only grant such points once), then refer to my answer to "How to check if user has passed the quiz already before granting user points?".

# If using Quiz 7.x-4.x

For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

> ... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.
>
> Patch works for me.
> 0 votes

---
Tags: 7, rules, userpoints, quiz
---


title: Using variables in Drupal

text:
# Question
Title: Using variables in Drupal
Would appreciate any assistance of how to handle configurable URLs for each environment.

The links need to take the user to a different URL depending on the environment the site is installed in. In test environment, they would go to the test site, in beta test environment, beta site. And in production, production.

Currently I am calling the test url by h ref in the body text. However, when the site is moved to beta, I would have to manually change the url to the beta url and so forth. I have about 50 of these type of URLs throughout my site so I am looking for a automated way.

I have thought about using

https://www.drupal.org/project/scanner https://www.drupal.org/node/257026#example-use-cases

But open to any suggestions or experience.

Many thanks in advance!

Mike

# Answer
If I understand your use-case properly, as far as I know everybody uses Pathalogic for this.
> 0 votes

---
Tags: navigation, configuration
---


title: change the language of my main page

text:
# Question
Title: change the language of my main page
I have a website http://www.apisnatura.com with the modulle MULTILINGUAL - INTERNATIONALIZATION.

I manage to create the pages of each language and when i click any language icon the main menu changes and the rest of the pages also change.

My question is... how do i change the main page content after clicking the different language icons with the relevant language.

I been looking around and i am getting crazy looking for a solution.

Any help will be great to carry on changing the content for this web.

Cheers

# Answer
> 0 votes
Check if you have activated these modules.
Views translation and Block languages (i18n\_block).

Then You need to change those blocks language settings in configuration. follow this: https://www.drupal.org/taxonomy/term/39286

tick "make this block translatable" and select the languages. it will allow you to translate a block in to a language you want. you might need to create separate blocks for each language.

In a View check if "Field Language" selected as "Current user's language" in Advanced area.

also use a filter for the view "Content: Language (= Current user's language)"

This will populate the content by detecting the users selected language. "

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


title: Can't access date field in fieldset

text:
# Question
Title: Can't access date field in fieldset
I am using rules and I'm trying to retrieve a field inside a field collection for my scheduled component.

I have the conditions "Entity has field" and have selected my field, but I still can't access it in the data selection for my component.

I am using Drupal 7.52, Rules 7-2.9, & Rules Scheduler 7-2.9.

**Update** I have discovered that I can access other fields in the fieldset, but I just can't access the date fields.

# Answer
Okay, solved it.

I wasn't suppose to add the action under Components, rather I was suppose to add the action under Rules Scheduler \> Schedule component evaluation.
> 1 votes

---
Tags: rules, entities
---


# Question
Title: How to delete a content type field without deleting the whole view?
I was trying to delete a field from a content type . But it's deleting all the views which have that field in it.

I have some pages inside that view. I even checked in all the pages that this field is present , but not found.

**`Any idea to delete a field without deleting the whole view`** ??

# Answer
As per the following issue registered on Drupal.org, that is what happening with D8 views hence you are observing that phenomenon. While in drupal 7 the view gets automatically updated. You can find the registered issue with drupal 8 core on drupal.org at following link.

When deleting a content type field, users do not realize the related View also is deleted

That issue is in review phase, hence probably significant work would have been done on that issue. You need to refer that.

If you read the entire discussion there, currently they are working on the idea of Comment #59. suggested by @dawehner which is stated/pasted below,

> Here is alternative approach:
>
> * Don't delete existing views
> * Disable existing views and tell people which ones got disabled
> * Then the user can go back to this view, fix missing fields and call it a day
> 4 votes

# Answer
You must remove references to the field in the Views before deleting the field.
> 1 votes

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


# Question
Title: Override a node template and its associated translation
I'm trying to understand how to override a node template in order to "catch" also all the associated node translations.

Let's say I have a `node/12` in English and its translation is `node/13`. To override in the same way both nodes I have to create `templates/node--12.tpl.php` and `templates/node--13.tpl.php` inside my theme folder.

Is there a way to avoid this, since the customisations I plan to implement on the node and its translation are the same?

# Answer
You can create a content type for the translations and use that content-type node template. `node--CONTENTTYPENAME.tpl.php`. so you don't need to update it one by one with the node ID.
> 0 votes

---
Tags: 7, theming, i18n-l10n
---


title: How to hide a view programmatically?

text:
# Question
Title: How to hide a view programmatically?
I need hide a view when some GET param exists. It should be hidden like if you insert 'Global: Null' in contextual filter(It hides view if no results). This view placed in panel\*

I tried to find the solution but failed. How to do this?

# Answer
I am guessing you are adding it as a block to a specific path. If yes, follow the steps below:

1. Go to the block configuration
2. Scroll down to the Visibility Settings
3. Click on "Pages" tab
4. Select the option "Pages on which this PHP code returns TRUE (experts only)"
5. Write your PHP logic to read the GET parameters and return true only if the specific parameter you are looking for is not found.
> 1 votes

# Answer
You just have to specify a validation criteria in a contextual filter, could be Global:null as you said. Then choose the action you want to take when validation fails. You can implement your validation logic in PHP, preferably inside a function in your code and you just call it from the view. Hope that helps.
> 1 votes

# Answer
Maybe if you override the views template and add a if statement, something like `if (function == true) { //do something }` (Sorry, really horrible in PHP...)
> 1 votes

---
Tags: 7, views
---


title: XML sitemap in Multilingual site

text:
# Question
Title: XML sitemap in Multilingual site
How to configure xml sitemap for multi language site.For translation I am using i18n module and for xml sitemap. Now there are only one link show in NL site map and 26 in default language.

# Answer
> 0 votes
Run the cron manually it will update this.If you have more translations for NL it will get update there.

cheers!

---
Tags: 7, i18n-l10n, xml-sitemap
---