# Question
Title: How to disallow users to edit their content after it was submitted for review?
I'm looking for a solution that does not allow a user to edit content after being submitted for review.

I'm working with two roles: **Content Creator** and **Reviewer**.

If the Reviewer rejects the content, then it will be enabled for the Content Creator to apply changes again.

I've tried using the Workbench module, it is very practical, but when the Content Creator submits a new content for review, the user still has access to edit this content, even if it is with status "*Under review*".

# Answer
> 0 votes
You can look to the workflow module to implement a suitable workflow and permissions.

# Answer
> 0 votes
You could use the Rules module for this (the only module you'd need ...), using an approach that is mostly similar to what I described in my answer to "How to prevent edit or delete of some content by its author depending on an approval status field?".

It would also take care of a variation of your question (if you'd want that), which is to take care of the situation that while the review is ongoing, you may not want to have it deleted either ...

---
Tags: workflows, nodes, workbench
---


# Question
Title: Where to include javascript instances in drupal
I've added my.js using js injector module and updated .info file. Where do I have to create those instances? Sorry, I'm new with technology.

# Answer
> -1 votes
To Add any `js` file to your Drupal site , a good way is to create a custom module and add your `js` file there.Following points may help you.

* Create one custom module of yours. Useful Link. https://www.drupal.org/developing/modules/7
* In your module , create one folder name `js`.
* Add your js file here.You can copy paste your js file also here.
* Now in your`module file` the following code to tell drupal about your js file.

```
function YOURMODULENAME_init(){

 drupal_add_js(drupal_get_path('module', 'YOURMODULENAME') . '/js/yourjs.js');

}

```
* At the end enable your custom module.You are ready to go.

---
Tags: javascript
---


# Question
Title: How can I access the main menu in template_preprocess_page?
I would like to assign the main menu of my site to a variable using template\_preprocess\_page() so that I can just use something like `{{main_menu}}` in the page template. Any ideas on how I would go about doing this, without having to assign the Menu to a Region?

# Answer
Remember your menu can be a block, and to render it, you just have to load and get its view in a preprocess function.

**THEME.theme file**

```
use Drupal\block\Entity\Block;
function THEME_preprocess_page(&$variables) {
  $menu = Block::load('id_main_menu');
  $variables['main_menu'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($menu);
}

```

**page.html.twig**

```
...
{{main_menu}}
...

```

**Attention**
You must create your block 'main\_menu' in somewhere, (module install, block structure page...)
> 8 votes

# Answer
I do not recommend hard coding a bunch of stuff in the theme because it increases the difficulty of understanding what is going on in the site for new developers, but this is possible in a couple of different ways. It would be better to use the block and region system.

### Using the menu.link\_tree service to build from scratch

It is important to realize that this is getting raw data, and without transforming the menu tree, no access check will be done. This may be okay because a main menu should be public, but that is not necessarily the case.

```
$menu_name = "main_menu"; // I think
$menu_tree = \Drupal::service('menu.link_tree');
$parameters = new \Drupal\Core\Menu\MenuTreeParameters();
$parameters
  ->setMaxDepth(1) // Or however far down the tree you want to go.
  ->onlyEnabledLinks()
  ->excludeRoot();
$tree = $menu_tree->load($menu_name, $parameters);
// $manipulators = [['callable' => 'menu.default_tree_manipulators::checkAccess']];
// $tree = $menu_tree->transform($tree, $manipulators);
foreach ($tree as $item) {
  /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
  $link = $item->link;
}

```

### Using a known block instance programmatically

See @Berdir's answer here: https://drupal.stackexchange.com/a/153195/42650
> 6 votes

---
Tags: 8, theming
---


# Question
Title: Use a CURL to work with sites without api?
I have this problem. I need to programmatically submit forms on multiple sites and receive data The sites do not use API This task perfectly solves the CURL. Is there a solution to this issue Drupal way? Maybe https://www.drupal.org/project/services?

# Answer
The Services module provides API endpoints, it doesn't help to make HTTP requests.

All Drupal has natively for making HTTP requests is `drupal_http_request()`. Personally I'd recommend using a library like Guzzle instead, it's much more pleasing to work with, and has support for submitting forms. Plus it's in core for Drupal 8 so you know it's got the seal of approval.

PHP's DOMDocument should be more than enough to help with processing the response.
> 1 votes

---
Tags: services
---


# Question
Title: How to add “Quote Request” button on some products?
I'm using Drupal Commerce and I want a quote button on some product (node) page so that a potential buyer can enter some brief information and click to send a `Quote Request` for the item that they are viewing.

I have a product type called **"Premium products"**, and I want this `Quote Request` button instead of price to be on some page.

On clicking the `Quote Request` button and asking a quote to the seller, the seller may respond to the query and tell the proposal amount for the product which user can accept or reject. Once accepted by user, the product should be added to the user's cart with the purposed price.

# Answer
Have a look at the feature request "Let customers build a 'quote' cart and request a quote instead of checkout". Even though it has status "postponed", it has some interesting comments, such as the very first one, which includes this (I added the bold markup):

> You probably don't need any specific module to do a majority of this. **All you'd have to do is add $0.00 prices to all your products and then just don't display those prices anywhere**. You don't have to show product price fields in your display nodes, and you can edit your cart Views so they don't include prices any more. The only thing you'd really have to change is the text pertaining to the shopping cart. You could do this with a module like String Overrides or just alter the various places directly with a hook in a site customizations module.
>
> When it comes time to submit the quote, I suppose you may want a custom button on the Cart form that changes the status of the order to "Needs quote" or something - if that's true, then that's all your custom module should really be responsible for ...

Also, the comment #7 in that same issue seems worth considering, this is part of what it says (I added the bold markup):

> I got this working quite easily! As Ryan said, make all product prices $0. Use **String Override** module and override a couple of the basic syntaxes. **Edit a couple of Views where certain terms/words still creeped through**. When you see syntax that needs to be changed on a view and you've already used String Override for it but it's not overriding it, just click on the right corner of the view on the gear to edit view. Then change the wording on there. I also had to remove or change some of the text that were on some views but under the "FOOTER" section (middle section of view). I had to do this a lot for the cart and checkout views.
>
> I added another checkout rule under Store\>Configuration\>Checkout Settings under "Send Request"-section to email me when the person places a request.

Maybe not a complete solution / answer to your question, but at least a partial answer to think about ...
> 2 votes

# Answer
You could use hook\_form\_alter to change the button text and submit function. This would allow you to, perhaps, create a checkbox called "Request a Quote" and replace the "Add to Cart" button with a link to a webform.

```
<?php

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['default_product'];
  $product_wrapper = entity_metadata_wrapper("commerce_product",$product);
  if ($product_wrapper->__isset('field_request_quote') &&
      $product_wrapper->field_request_quote->value() == true) {
    // Hide "add to cart"
    $form['submit']['#access'] = false;

    // Add a link instead
    // could be a separate field as well
    $form['quote'] = array(
      '#weight' => 999,
      '#markup' => l('Request Quote','node/4'),
    );
  }
}

?>

```
> 0 votes

---
Tags: 7, commerce
---


title: hook_update a rule configuration?

text:
# Question
Title: hook_update a rule configuration?
I would like to update a payment method settings. As I understand, the settings are inside a RulesReactionRule.

Is it possible to modify the configuration of a RulesReactionRule using a hook\_update ?

Thanks.

# Answer
> 0 votes
I've finally found how to export the Drupal commerce payment method settings using commerce\_features and the patch: https://www.drupal.org/node/1973098#comment-10559856

---
Tags: 7, commerce, rules, updating
---


# Question
Title: "COPY_ERROR: Unable to copy" while using drush make with download type "copy"
Here is my module structure:

```
.
|-- mymodule.make
|-- mymodule.info
|-- mymodule.module
|-- mymodule.install
`-- sub1
    |-- sub1.make
    |-- sub1.info
    |-- sub1.module
    `-- sub1.install

```

I would like that when using `drush make` the sub-module `sub1` is also made (so I would like that `sub1.make` is called too).

In `mymodule.make` I declare:

```
api = "2"
core = "7.x"

projects[drupal][version] = "7.39"

; Modules
projects[sub1][type] = module
projects[sub1][download][type] = copy
projects[sub1][download][url] = "./sub1"

```

And here is the error that I have:

```
Found makefile: mymodule.make                                [ok]
COPY_ERROR: Unable to copy sub1 from ./sub1. -- build forced [warning]

```

However, the documentation tells

> `download[type] = copy` Copies a project from a local folder.

so I think I'm using the correct `[download][type]`...

I've also tried with `projects[sub1][download][url] = "file://./sub1"` and have the same error.

# Answer
As a workaround, I used the `includes[]` directive instead.

Here is my working `mymodule.make`:

```
api = "2"
core = "7.x"

projects[drupal][version] = "7.39"

; Modules
includes[] = ./sub1/sub1.make

```
> 0 votes

---
Tags: 7, drush
---


# Question
Title: I am looking for a responsive slider that can take text instead of images
Do you know of a responsive slider that can take text instead of images?

I have been using Nivo Slider and have had great experiences with its responsive design. I am using one on the front page. I wanted another, so I used Views Nivo Slider. My client decided to have another with text instead of pictures, but Views Nivo Slider didn't seem to want to do this. I don't think I can hack the Nivo Slider code because it would effect my other sliders on my webpage.

Here are some pictures. With images, the slider behaves normally.

When I add the body content and change the slider to show the body as so,

I get this:

Nothing shows up.

The same thing happens if I try to put the body into the title instead of the image.

# Answer
Try jCarousel uses the jCarousel jQuery plugin which can do text too
> 0 votes

# Answer
There is a smaller group out there Theme Boutique who built a really remarkable slideshow tool called the Revolution Slider. It's currently out ther and available on their Dawn Responsive theme (I have used their BigWig theme in the past with the same slideshow). It worked really well and didn't require alot of the gymnastics that I've seen with other solutions.

Here's a demo video of it in action. https://www.youtube.com/watch?v=zZL2renvh5o
> 1 votes

---
Tags: 7, javascript
---


title: Ajax callback function is un-callable

text:
# Question
Title: Ajax callback function is un-callable
I’ve built a Drupal 8 Form example using code found here: http://www.drupalcontrib.org/api/drupal/contributions%21examples%21ajax\_example%21ajax\_example.module/function/ajax\_example\_dependent\_dropdown/8

The code, when run, dispalys 2 selects. When a change is made to the first Select an Ajax call is made and is supposed to set a new set of options in the second Select. However when changed I get a “Uncaught PHP Exception” - "The specified #ajax callback is empty or not callable." I’ve tried multiple adjustment but am unable to get the code to run as desired.

Any answers or ideas would be greatly appreciated.

```
<?php
namespace Drupal\dependent_selects\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;

include 'dependent_selects.config';

class DependentSelectsForm extends FormBase
{
public function getFormId()
{
    return 'dependent_selects';
}

public function buildForm(array $form, FormStateInterface $form_state)
{
    $options_first = $this->_ajax_example_get_first_dropdown_options();
    $formValues = $form_state->getValues();
    $selected = (isset($formValues['dropdown_first'])) ? $formValues['dropdown_first'] : key($options_first);

    $form['dropdown_first'] = array(
      '#type' => 'select',
      '#title' => 'Instrument Type',
      '#options' => $options_first,
      '#default_value' => $selected,
      '#ajax' => array(
        'callback' => 'ajax_example_dependent_dropdown_callback',
        'wrapper' => 'dropdown-second-replace',
      ),
    );

    $form['dropdown_second'] = array(
      '#type' => 'select',
      '#title' => $options_first[$selected] . ' ' . t('Instruments'),
      '#prefix' => '<div id="dropdown-second-replace">',
      '#suffix' => '</div>',
      '#options' => $this->_ajax_example_get_second_dropdown_options($selected),
      '#default_value' => isset($formValues['dropdown_second']) ? $formValues['dropdown_second'] : '',
    );
    return $form;
}

public function ajax_example_dependent_dropdown_callback($form,  &$form_state)
{
    return $form['dropdown_second'];
}

public function _ajax_example_get_first_dropdown_options()
{
    $instType = array(
      'String' => 'String',
      'Woodwind' => 'Woodwind',
    );
    return $instType;
}

function _ajax_example_get_second_dropdown_options($key = '')
{
    $options = array(
      'String' =>
      array(
        'Violin' => 'Violin',
        'Viola' => 'Viola',
      ),
      'Woodwind' =>
      array(
        'Flute' => 'Flute',
        'Clarinet' => 'Clarinet',
      ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

public function validateForm(array &$form, FormStateInterface $form_state)
{
    $a = 1;
}
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $a = 1;
}

```

}

# Answer
> 6 votes
They way you specify your callback means that it is a function. You define it in your class, which means, it is not.

Prefix it with ::, that's a shortcut that tells Drupal that it's a method on the form class. You should also use camel case for the method's names. So, something like `::ajaxExampleDependentDropdownCallback` (to be clear, you also have to rename your method, not just the callback string).

I also don't understand what you're trying to do with `include 'dependent_selects.config';`?

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


title: Creation and display of song setlists

text:
# Question
Title: Creation and display of song setlists
I am using Drupal version 7.42 and a content type used for information regarding **Concert setlists**. It includes labels for:

* Date.
* Venue.
* Location.
* Setlist.
* Description.
* Lineup.

I will give you an idea of what I am looking to achieve in the end regarding its display. I also have a content type for the **Songs**.

Each **performance listing** will be different. I will have some listings that show **Songs** known to be performed yet the **Setlist** isn't complete. I will have some listings that show songs known to be performed in:

* Set 1.
* Set 2.
* Encore.
* etc.

Also, some performances may have more than one encore, so I also will have performances noted with Encore 1, Encore 2, etc. if the listing requires it.

***How do I manage to get the display of the setlist to show a label above the songs indicating the song placement?***

I thought having multiple fields in the content type (Set 1, Encore, Encore 1, Encore 2, etc) does the trick. But with time mulling over this one I am thinking is it possible to be achieved by just having one setlist field (Setlist) instead of multiple setlist fields in the content section?

Below is an example of the display I am describing for site viewers to see when visiting a performance page. Each song listed in a performance page at the moment uses Entity Reference to link to its unique song within the Songs content type.

* Set:

+ Song 1
    + Song 2
    + Song 3
* Encore 1:

+ Song 4
    + Song 5
* Encore 2:

+ Song 6

Any suggestions?

# Answer
> 0 votes
Below is a possible approach you may want to consider. It's using "State" names (like Florida, Illinois, etc.) instead of "Set 1, Set 2, etc" and "Cities" instead of "Songs".

If I was to implement this in a Drupal site, I'd use either of these "displays":

* **Option 1 - Master detail with nested blocks**

Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".
* **Option 2 - Report that filters based on some lookup**

Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "**How did you do that?!?!**" ... then this is the answer: that's really a piece of cake using the Forena module. Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead, but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).

**Disclosure**: I'm a co-maintainer of Forena.

# Answer
> 0 votes
## Views tree

> This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
>
> It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.
>
> ### Compatibility
>
> This module has been tested and used with the following relationship-oriented modules:
>
> * Taxonomy (in core) - parent/child relationships References - node and user references Relation
> * references between any entities (D7 only)
> * Entity reference - references between any entities (D7 only)
> * Organic Groups (D7 only)
>
> Example:

---
Tags: nodes, entities, theming
---


# Question
Title: How to get the type of Paragraphs entity in the parent node field?
I have a "page" node with a paragraphs field `field-ref-para-multi` and the corresponding template `field--node--field-ref-para-multi--page.html.twig`.

And I have some paragraphs types that can be used in this field:

para\_a

para\_b

para\_c

I have to place a surrounding html structure in the field depending of the paragraphs types that are used inside.

```
{# type a #}
<div class="js-para_a">
{% if multiple %}
    {% for item in items %}
        {{item.content}}
     {% endfor %}
{% else %}
    {% for item in items %}
        {{item.content}}
    {% endfor %}
{% endif %}
</div>

{# type b #}
<ul class="js-para_b">
{% if multiple %}
    {% for item in items %}
        <li>{{item.content}}</li>
     {% endfor %}
{% else %}
    {% for item in items %}
        <li>{{item.content}}</li>
    {% endfor %}
{% endif %}
</ul>

```

But how to get the type of the used paragraphs in the field template?

# Answer
I think you can wrap each paragraphs field in any html wrapper of your choice, but you have to edit **each** field by modifying the appropriate `field.html.twig`  template file.

In the field template suggested name, for example:

`FILE NAME SUGGESTIONS:
 * field--paragraph--field-text-half--text-svg.html.twig
**x field--paragraph--field-text-half.html.twig**
 * field--paragraph--text-svg.html.twig
 * field--field-text-half.html.twig
 * field--text-long.html.twig
 * field.html.twig`

You will then use the template suggested name to edit the `html` wrapper of your choice.

Like this :

```
{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes }}>
      {% for item in items %}
        <div{{ item.attributes }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}
    {% for item in items %}
      <div{{ attributes }}>{{ item.content }}</div> --> change div to preferred  html
    {% endfor %}
  {% endif %}
{% else %}
  <div{{ attributes }}>
    <div{{ title_attributes }}>{{ label }}</div>
    {% if multiple %}
      <div>
    {% endif %}
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
    {% if multiple %}
      </div>
    {% endif %}
  </div>
{% endif %}

```

Hope this helps :)
> 2 votes

---
Tags: 8, theming
---


title: reverse output of list in the view

text:
# Question
Title: reverse output of list in the view
Is there a way to reverse order of the outputed list:

These items were being added as Global:Contextual links in the View, but order is wrong. Instead of going and replacing in each view (lets say that there are 100 views), what would be the quickest way of reversing order and making it like :

* Manage display
* Clone
* Access Control
* Delete
* Edit

Thanks

# Answer
You have to implement the hook\_menu\_alter and adjust the links `weight` property to your will. Here is a sample code that changes the node's default contextual links by placing the delete link over the edit link:

```
/**
 * Implements hook_menu_alter().
 */
function foo_menu_alter(&$items) {
  $items['node/%node/delete']['weight'] = 0;
  $items['node/%node/edit']['weight'] = 1;
}

```

Keep in mind that the smallest the `weight` of a link the more will flow on top, negative numbers may also be used.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Adding “Unblock the user” option in Views Bulk Operations field
I have created a user based view and I used the Views Bulk Operations module, but I don't see *Unblock user* or something like that. I also want to show tree-based roles in the bulk operation options list.

How can I achieve this?

# Answer
> 2 votes
Below is the code to add 'Unblock the user' option in Views Bulk Operations field.

```
/**
* Implements hook_action_info().
*/
function mymodule_action_info() {
return array(
'mymodule_unblock_user_action' => array(
'label' => t('Unblock the user'),
'type' => 'user',
'configurable' => FALSE,
'triggers' => array('any'),
 ),
 );
}

/**
 * Unblocks a user, defaulting to the current user.
  *
 * @ingroup actions
 */
 function mymodule_unblock_user_action($entity, $context = array()) {
 // First priority: If there is a $entity->uid, unblock that user.
 // This is most likely a user object or the author if a node or comment.
 if (isset($entity->uid)) {
 $uid = $entity->uid;
    }
   // Otherwise get user ID from the context.
 elseif (isset($context['uid'])) {
  $uid = $context['uid'];
  }
 $account = user_load($uid);
  $account = user_save($account, array('status' => 1));
 watchdog('action', 'Unblocked user %name.', array('%name' => $account->name));
    }

```

Taken answer from This Link.

# Answer
> 3 votes
In drupal 7-

We need a **Rules module**, after enable Rules module and Rules UI go to

1- **Configuration -\> Workflow-\> Rules-\> Component-\> Add Component**

In **Component plugin** dropdown-\> select **Action Set** then add next page Fill the mandatory field Name as (Ex: Unblock user)

2- Select **Data type** from list **User** ---Label **Unblock user** ---machine name **unblock\_user** -- usage **parameter**

3- In **setting** option you can set **Permission** roles wise.

then click on **continue** button then click on **Add Action Link**

4- then Select the action to add **User -\>Unblock User**

5- Select **Data Selector** -\> **unblock-user** and Save

6- Now go to- **Views** Page add field **Bulk operations** there will be present **Unblock user** option

for reference - Add Unblock user option by rules in views and set permission

---
Tags: views
---


# Question
Title: How to fire multiple Rules Actions in a single rule?
I have a real estate website using the drealty module. In the real estate RETS feed, there is a numeric field called "Area". That numeric value refers to a specific area... for example, "22" might be "Miami Beach", and "32" might be "Miami Beach" and "South Beach".

When new real estate listings are created (via a command line in drush), I need for the corresponding "verbose" name of the area(s) to be selected from a specific taxonomy. For example, if the RETS feed returns "22" for the area value, then "Miami Beach" should be checked in that taxonomy field on the listings entities. Likewise, if the RETS feed returns "48", then both "Miami Beach" and "South Beach" should be checked.

I created a Rules Component for each area numerical value. The Miami Beach Rules Component is below:

```
 { "rules_set_area_miami_miami_beach" : {
 "LABEL" : "Set Area - Miami - Miami Beach",
 "PLUGIN" : "rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules" ],
 "USES VARIABLES" : { "drealtylisting" : { "label" : "drealtylisting", "type" : "drealty_listing" } },
 "IF" : [
   { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area" } },
   { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area_taxonomy_" } },
   { "data_is" : {
       "data" : [ "drealtylisting:field-area" ],
       "op" : "IN",
       "value" : { "value" : [ "22", "32" ] }
     }
   }
 ],
 "DO" : [
   { "data_set" : {
       "data" : [ "drealtylisting:field-area-taxonomy-" ],
       "value" : { "value" : { "35" : "35" } }
     }
   }
  ]
 }
}

```

The same type of Rules Component exists for South Beach:

```
  { "rules_set_area_miami_south_beach" : {
  "LABEL" : "Set Area - Miami - South Beach",
  "PLUGIN" : "rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "USES VARIABLES" : { "drealtylisting" : { "label" : "drealtylisting", "type" : "drealty_listing" } },
  "IF" : [
    { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area" } },
    { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area_taxonomy_" } },
    { "data_is" : {
        "data" : [ "drealtylisting:field-area" ],
        "op" : "IN",
        "value" : { "value" : [ "32" ] }
      }
    }
  ],
  "DO" : [
    { "data_set" : {
        "data" : [ "drealtylisting:field-area-taxonomy-" ],
        "value" : { "value" : { "23" : "23" } }
      }
    }
  ]
 }
}

```

I then created a Rule with Event "After saving a new drealty listing" and Actions: "rule: Set Area - Miami - Miami Beach" and "rule: Set Area - Miami - South Beach".

```
    { "rules_set_area_on_drealty_listing_cloned_" : {
    "LABEL" : "Set Area on Drealty Listing (cloned)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "drealty" ],
    "ON" : { "drealty_listing_insert" : [] },
    "DO" : [
      { "component_rules_set_area_miami_miami_beach" : { "drealtylisting" : [ "drealty-listing" ] } },
      { "component_rules_set_area_miami_south_beach" : { "drealtylisting" : [ "drealty-listing" ] } }
    ]
  }
}

```

When I run a RETS import and the website creates the new listings, I expected it to evaluate each of those Rule actions in succession and check the taxonomy boxes when necessary, but instead it appears that only the South Beach Rule Action is taking effect, and thus only South Beach is checked in that field. Is this because it is listed last in the Rule action list? Is there a better way for me to set this up so that I can get the desired end result?

# Answer
> 2 votes
I see "data set" which I'm 99% sure means your field is either set to one value.. Or in taxonomy, it could mean that setting data overwrites previous values. So your rules might simply overwriting each other.

I can't remember much about taxonomy but change your field to infinite values if not already and use the rules action, " Add an item to list" if possible.

On a separate note, you should avail of the action "fetch entity by property" and only have maybe one rule for everything. So you'd add an integer field to your taxonomy terms and use the rules action to fetch it using the integer provided. Let me know if you want to try it.

# Answer
> 1 votes
Below is a possible alternative to achieve the same result (as per your "***Is there a better way for me to set this up so that I can get the desired end result?***") ...

You might want to try to consolidate those 2 (similar) rules in a single rule, by using the Conditional Rules module: the condition for each rule would be replaced by a similar "if condition" (contained in the Rules Action), and the Rules action for each group would only be executed if the "if condition" would be true. For a sample using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Instead of using ***Conditional*** (if/else) logic within the Rules Action, you can also use ***Switch*** logic.

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

---
Tags: 7, taxonomy-terms, rules, entities, drush
---


# Question
Title: Why does my code for checking field permissions allow users to register with the same email address?
Based on the Examples module, I tried to set up permissions on some user account fields so that only admins can read them.

However, **the code below somehow allows users to register with the same email address multiple times.** I can't figure out why it is doing this because I am only changing the access permissions; however, when I comment out the following code and clear cache, I cannot register the same email address twice, but when the code is active, I can.

I assume I must be doing something very incorrect to introduce such a problem; I would much appreciate any insight into what I'm doing wrong.

I defined two permissions, one for restricting view + edit access to admins, and another for allowing the user to view but not edit data.

First, I added the permissions to `mymodule.permissions.yml`:

```
'administer admin fields':
  title: Administer settings for admin fields.
'view any viewonly fields':
  title: View any viewonly fields.

```

Then I added this function to `mymodule.module`:

```
// Use statements to support hook_entity_field_access.
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Implements hook_entity_field_access().
 */
function mymodule_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL)
{
  {
    // Start of part I changed from examples module
    // Fields that only admins should be able to see and edit.
    $admin_fields = array(
      'user.user.field_ip',
      'user.user.field_nicknamehistory',
      'user.user.field_useragent',
      // Fields users can view but not edit.
      'user.user.field_age',
    );
    $view_not_edit_fields = array(
      'user.user.field_age',
    );

    if (method_exists($field_definition, 'getOriginalId') && !(in_array($field_definition->getOriginalId(), $admin_fields))) {
      return AccessResult::neutral();
    }
    // End of part I changed from examples module

    // First we'll check if the user has the 'superuser'
    // permissions that node provides. This way administrators
    // will be able to administer the content types.
    if ($account->hasPermission('bypass node access')) {
      return AccessResult::allowed();
    }
    if ($account->hasPermission('administer content types', $account)) {
      return AccessResult::allowed();
    }
    if ($account->hasPermission('administer admin fields', $account)) {
      return AccessResult::allowed();
    }

    // For anyone else, it depends on the desired operation.
    // Start of part I changed from examples module
    if (method_exists($field_definition, 'getOriginalId') && in_array($field_definition->getOriginalId(), $view_not_edit_fields)) {
      if ($operation == 'view' and $account->hasPermission('view any viewonly fields')) {
        return AccessResult::allowed();
      }
    }
    // End of part I changed from examples module

    // Anything else on this field is forbidden.
    return AccessResult::forbidden();
  }
}

```

And for reference, here is the code from the Examples module:

```
// Use statements to support hook_entity_field_access.
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Access\AccessResult;

// Interfaces used by entities to declare "ownership".
use Drupal\user\EntityOwnerInterface;
use Drupal\user\UserInterface;

// Use statements for hook_entity_test_access.
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_field_access().
 *
 * We want to make sure that fields aren't being seen or edited
 * by those who shouldn't.
 */
function field_permission_example_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  // Find out what field we're looking at.  If it isn't
  // our sticky note widget, tell Drupal we don't care about its access.
  if ($field_definition->getType() != 'field_permission_example_fieldnote') {
    return AccessResult::neutral();
  }

  // First we'll check if the user has the 'superuser'
  // permissions that node provides. This way administrators
  // will be able to administer the content types.
  if ($account->hasPermission('bypass node access')) {
    drupal_set_message(t('User can bypass node access.'));
    return AccessResult::allowed();
  }
  if ($account->hasPermission('administer content types', $account)) {
    drupal_set_message(t('User can administer content types.'));
    return AccessResult::allowed();
  }
  if ($account->hasPermission('administer the fieldnote field', $account)) {
    drupal_set_message(t('User can administer this field.'));
    return AccessResult::allowed();
  }

  // For anyone else, it depends on the desired operation.
  if ($operation == 'view' and $account->hasPermission('view any fieldnote')) {
    drupal_set_message(t('User can view any field note.'));
    return AccessResult::allowed();
  }

  if ($operation == 'edit' and $account->hasPermission('edit any fieldnote')) {
    drupal_set_message(t('User can edit any field note.'));
    return AccessResult::allowed();
  }

  // At this point, we need to know if the user "owns" the entity we're attached
  // to. If it's a user, we'll use the account name to test. Otherwise rely on
  // the entity implementing the EntityOwnerInterface. Anything else can't be
  // owned, and we'll refuse access.
  if ($items) {
    $entity = $items->getEntity();
    if ((($entity instanceof EntityOwnerInterface) and
         $entity->getOwner()->getAccountName() == $account->getAccountName()) or
        (($entity instanceof UserInterface) and
         $entity->name->value == $account->getAccountName())
        ) {
      if ($operation == 'view' and $account->hasPermission('view own fieldnote')) {
        drupal_set_message(t('User can view their own field note.'));
        return AccessResult::allowed();
      }
      if ($operation == 'edit' and $account->hasPermission('edit own fieldnote')) {
        drupal_set_message(t('User can edit their own field note.'));
        return AccessResult::allowed();
      }
    }
  }
  // Anything else on this field is forbidden.
  return AccessResult::forbidden();
}

/**
 * Implements hook_ENTITY_TYPE_access().
 *
 * Note: this routine is added so we can more easily test our access code. Core
 * defines an entity_test entity that is used for testing fields in core. We add
 * this routine to make the entity_test entity editable by our tests.
 */
function field_permission_example_entity_test_access(EntityInterface $entity, $operation, AccountInterface $account, $langcode) {
  if ($operation == 'edit') {
    $perms = [
      'administer the fieldnote field',
      'edit any fieldnote',
      'edit own fieldnote',
    ];
    foreach ($perms as $perm) {
      if ($account->hasPermission($perm)) {
        return AccessResult::allowed();
      }
    }
  }
  return AccessResult::neutral();
}
/**
 * @} End of "defgroup field_permission_example".
 */

```

# Answer
I'm not sure why that happens, so just a few notes. You did ask for any insight. It will certainly help to simplify your code if nothing else. Might check again in more depth later and update the answer.

* Note that permission names are global, you might want to use something a bit more specific.
* getOriginalId() is *not* a method on FieldDefinitionInterface, you should not use that. Use getTargetEntityTypeId() == 'user' and -\>getFieldName() then you can also drop the repeating 'user.user.' prefixes for your names. You should always work with the interfaces that you get, method\_exists() is bad in 99% of the cases. That's what interfaces are for.
* Do not implement entity level access checks. Just check access to fields, you can safely assume that the user has access to view/edit the entity, the calling code is responsible for checking that first if necessary.
* Make sure that you add any cache contexts (e.g. user.permissions) and other cacheable metadata if applicable with allowed()-\>addCacheContexts(\['user.permissions'\]). The entity view output for example will be cached based on that. And while user.permissions by default is always included, it's good practice to include that.
* Your view own should however probably check if the user is really looking at his own user, and then you need the user cache context.
> 1 votes

# Answer
Here's the working version, based on Berdir's comments:

```
/**
 * Implements hook_entity_field_access().
 *
 * We want to make sure that fields aren't being seen or edited
 * by those who shouldn't.
 */
function mymodule_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL)
{
  // Fields that only admins should be able to see and edit.
  $admin_fields = array(
    'field_age',
    'field_nicknamehistory',
    'field_useragent',
  );
  $view_not_edit_fields = array(
    'field_age',
  );

  if ($field_definition->getTargetEntityTypeId() && in_array($field_definition->getName(), $admin_fields)) {
    if ($account->hasPermission('administer admin fields', $account)) {
      return AccessResult::allowed();
    }
    else if (in_array($field_definition->getName(), $view_not_edit_fields)) && ($operation == 'view' and $account->hasPermission('view any viewonly fields'))) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }
  else {
    return AccessResult::neutral();
  }
}

```
> 0 votes

---
Tags: hooks, 8, users, debugging
---


title: How to let users use my module?

text:
# Question
Title: How to let users use my module?
I've just created a module that concerns books (add book, edit books, etc). Of course the administrator can use it, but I want to allow users that are connected to use it as well. But with condition on uid like so:

* User1: add book 1, book 5, book 7
* User2: add book 3
* ...

The administrator can see all books (1,3,5,7) (that's done). But user1 (which is not superuser `user/1` ...) has to only see his/her books (1,5,7), and similar for user2.

I'm sure I have to add a condition on my current module like:

```
if (uid = current user id) then show only user1's books)

```

But how to do that?

I know that the table "node" contains both informations of user id and nid (all books).

Note: I want to do that without using the Views module.

# Answer
> 1 votes
Have a look at the Node access user reference modules (with about 4,3K reported installs ...), available for both D6 and D7.

Some details from its project page:

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

The above details seem to me like a perfect solution to answer your question. So either just use this contributed module in combination with your own module, or use it a inspiration about how you should enhance your own module in combination with User reference or Entity reference.

---
Tags: users
---


# Question
Title: Where to start for implementing user roles/levels?
I have three types of user roles in my site:

* department heads.
* department managers.
* employees.

There are several department heads. Each Department Head manages multiple department managers. And each Department manager manages multiple employees.

What I want is:

* Department managers should be able to see details of THEIR employees.
* Department heads should be able see THEIR managers and the employees working under each of these managers.

There are lots of techniques/solutions on roles and permissions. Such as those provided by specific contributed modules (including Organic groups). But I am confused which one to start with.

Anybody can shed some light about this?

# Answer
> 1 votes
Have a look at the **Group** module (a new module as of D7). It should address most (if not all) of your requirements. And it offers a potential alternative to the **Organic groups** module. Here is a quote from its project page:

> **Organic groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
>
> **Group** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Some major differences between these 2 modules are:

* **Group** started in D7 only, taking full advantage of entities introduced in D7.
* **Organic Groups** is commonly perceived as a huge module, which carries a lot of "legacy" from pre-D7 releases.
* A D8 version of **Group** is in the pipeline and actively being worked on these days (expectation is "only a few months from now").

# Additional Group sub-modules

Extra features can be enabled via these sub-modules:

* **Group Add**: Add members to a group without their consent.
* **Subgroup**: Make group to belong to another group.
* **Group Invite**: Allow group members to invite people into their group.
* **Group Node**: Enables Group functionality for the Node module.
* **Group member profiles**: Create multiple fieldable member profiles, which can be attached to a member.

Have a look at my answer to "How to create basic Organic Groups functionality with flags and references?" for way more details about it, such as available integration with other (commonly used) modules.

---
Tags: users, organic-groups
---


# Question
Title: How can I remove the asterisk for required fields programatically?
How can I remove the asterisk Drupal inserts for required fields programatically (not hiding with CSS)?

In Drupal 7, there was theme\_form\_required\_marker(), but that's gone from Drupal 8.

# Answer
> 1 votes
This can be removed from the theme. I'm using a Bootstrap subtheme, so in my case I copied `form-element-label-html.twig` from the bootstrap **templates** directory into my subtheme's **templates** directory, then changed the following line:

```
  {%- if required -%}
    <span class="form-required">*</span>
  {%- endif -%}

```

To:

```
  {%- if required -%}
    {# <span class="form-required">*</span> #}
  {%- endif -%}

```

Clear caches and it's done.

# Answer
> 0 votes
**IMPORTANT**
Considering that '\*' came on placeholder attribute, follows...

First, check if your contact form has a placeholder with '\*', cause is lot easier if you can just remove it.

If you really need remove on code, you can do this via preprocess functions.

**THEME.theme**

```
function THEME_preprocess_input(&$variables) {
  //Alter the placeholder for inputs
  $variables['attributes']['placeholder'] = $variables['element']['#title'];
}

function THEME_preprocess_textarea(&$variables) {
  //Alter the placeholder for textarea
  $variables['attributes']['placeholder'] = $variables['element']['#title'];
}

```

---
Tags: theming, 8
---


title: module error in drush

text:
# Question
Title: module error in drush
My task is to update all modules of a site and commit. Everything goes well except when I ran the command `drush pm-update projects drupal-6.28`

> PHP Fatal error: Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc\_post\_affiliate\_pro/uc\_post\_affiliate\_pro.module on line 926 Drush command terminated abnormally due to an unrecoverable error. \[error\] Error: Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc\_post\_affiliate\_pro/uc\_post\_affiliate\_pro.module, line 926
>
> Fatal error: Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc\_post\_affiliate\_pro/uc\_post\_affiliate\_pro.module on line 926 Scotts-MacBook-Pro-2:c2d-deals2 scottnassery$ drush up uc\_post\_affiliate\_pro --security-only --no-core PHP Fatal error: Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc\_post\_affiliate\_pro/uc\_post\_affiliate\_pro.module on line 926 Drush command terminated abnormally due to an unrecoverable error. \[error\] Error: Call-time pass-by-reference has been removed in /Users/scottnassery/c2d-deals2/sites/all/modules/contrib/uc\_post\_affiliate\_pro/uc\_post\_affiliate\_pro.module,

My question is how can I fix that error and how can I restore the module to a old version should I redownload it and replace it?

# Answer
> 2 votes
Recently, Drush changed the default setting for recoverable errors to abort rather than continue when they are discovered. If this is causing problems, e.g. in an old module, then you can turn it off.

Create a file called `drushrc.php`, and place it in `$HOME/.drush`. Add the following contents:

```
<?php
$options['halt-on-error'] = FALSE;

```

You should then be able to continue without needing to fix the error in the non-compliant module.

# Answer
> 0 votes
This is actually a bug in Post Affiliate Pro module, which is trying to pass a variable by reference to a function on call time. You can simply fix this bug by updating `uc_post_affiliate_pro.module` file on the line 926:

```
uc_post_affiliate_pro_register_affiliate($edit, &$account);

```

into

```
uc_post_affiliate_pro_register_affiliate($edit, $account);

```

---
Tags: drush
---


# Question
Title: Rules: Event user has logged in won't trigger rule
I'm a newbie and using the Rules module, but Rules Event "user has logged in" won't trigger my rule.

I can set any event to trigger a rule (for example, user has logged out), but if I change it to "User has logged in", the rule is never triggered, even if conditions and actions remains the same.

This doesn't work:

* Event: User has logged in
* Conditions: None
* Actions:

+ Set a data value
    + Parameter: Data: \[account:field-point\], Value: 1

But if event is: "user has logged out", there is no problem, the value changes to 1.

I had used "user has logged in" as an event in another site and it works, but in this particular case it won't.

Any idea why?

**UPDATE**:

I found the problem... maybe.

At a user's first log in I have a (first) rule to remove one role "new" and add a new one "active", I also set the date of first log in in a field and a second date that has a 1 year offset. The condition to this rule is if the user account has the role "new".

A user can also set some fields of his profile to be private or public by changing a field text list, I did this by setting a (second) rule that after updating a user account changes a set of cloned fields to blank when the value of a field is "private" and a (third) rule that copies the data from the original fields to the cloned ones when user selects "public". Both rules are triggered after updating a user account.

In this case, the first rule to change user roles never triggers; if I disable the third rule triggered after the user account is updated, then the first rule runs as expected.

So, it looks like I can't have two rules triggered by the same action, in this case, two rules triggered after the user account is updated.

The problem is solved by setting the third rule to trigger *before* saving a user account, but I still don't know what caused the problem.

# Answer
> 1 votes
Challenging Rules question ... also because there seem to be some things in it that don't match with Rules terminology or functionality. Read on for more details ...

# Part 1: Refinements of your question

> Rules: Event user has logged in won't trigger rule

This is a pretty confusing title: Rules Event "User has logged in" should always be triggered ... when a user logged in. If that's not happening, then that seems ike a Rules-bug. Therefor I think a better title is "***Why is my Rules Action not executed when using Rules Event 'User has logged in'?***". If you agree, please edit your title like so.

> I can **set** any **event** to **trigger** a rule ... the rule is never triggered.

Rules Events are triggered by Rules, "you" cannot "set" them. Using custom code you may enhance Rules to trigger "custom" events to be triggered by Rules. Since this question is not about custom code, I assume you wanted to say "No matter which Rules Event I try to use ... the rule is never triggered".

> ... two rules **triggered** by the same **action**

Rules are NOT triggered by an **action**, they are trigger by a Rules **Event**.

**Advice**: Rules is all about **Events**, **Conditions** and **Actions** (**ECA** for short). You really need to think with those 3 crucial terms when using Rules ... And rephrase your question accordingly.

# Part 2: Attempt to answer your question

### What might explain what's happening

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so *that* can't be the reason anymore then why things don't work as expected).

### Rules debugging

You clearly have a combination of rules that need some debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my **K**eep-**I**t-**Super**-**S**imple technique I often use is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Obviously, if you have more then 1 rule (like 3?), you may want to make it like Bingo1, Bingo2, Bingo3. Depending on the order they are shown, you also know the order of execution. Stupid, but simple and efficient (I think).

For more suggestions about Rules debugging, refer to "How can I display the value of a variable inside a condition?"

### Use Conditional Rules

In your case there are 2 rules involved that are triggered by the same Rules Event (= after user acount is updated). But how do you know in which "order" (which Rule gets executed first)? There might be some logic in rules somewhere to find the answer to that question.

But instead of searching for that answer (or hope the order matches with what you'd hope), I simply use the Conditional Rules module in such cases. Not only does it allow me to merge multiple rules together in a single rule (= much easier to maintain, etc), but "I" am in full control about the actual Rules Conditions (within a Rules Action!), and I can set the order of them in the way "I" want/expect them to be. You can use ***Conditional*** (if/else) logic within the Rules Action, or you can also use ***Switch*** logic.

For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

# Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework.

---
Tags: users, rules
---


# Question
Title: How do I specify the debug_mail_directory for the devel maillog?
In `settings.local.php`, I have set my local dev environment to use the Devel module's mail logging function:

```
 $config['system.mail']['interface']['default'] = 'devel_mail_log';
 $config['devel']['settings']['debug_mail_directory'] = "???";

```

The DevelMailLog documentation says that:

> Filename pattern controlled by 'debug\_mail\_file\_format' config setting.

What do I put for the filename pattern? I have tried several patterns:

* public://devel\_mail
* private://emails
* sites/default/files/devel

But none of these work. I checked watchdog, but apparently devel mail doesn't leave any logs.

NOTE 1: There is a note in the docs that config settings are broken, but the linked issue is already fixed.

NOTE 2: By default, when I enable devel and export the config, the value for `debug_mail_directory` is `temporary://devel-mails`, but I don't want to store them in the temporary directory; I want to store them in the Drupal files directory if possible.

# Answer
> 2 votes
You should use

```
$config['devel.settings']['debug_mail_directory'] = 'private://mydirectory';
$config['devel.settings']['debug_mail_file_format'] = 'mypattern-%to-%subject-%datetime.mail.txt';

```

---
Tags: 8, debugging
---


# Question
Title: How to duplicate a display (which is not the master) as a different display type?
Assume you used Views to build a ***page*** display (in Drupal 7). So you have the typical "master", and an additional display called (let's say) "MyPageDisplay". And assume that in this "MyPageDisplay" you "overwritten" various settings (fields, sorting, whatever) from your "master".

And then you want to create a ***block*** display that's exactly the same (same filters, etc) as the "MyPageDisplay". There doesn't seem to be any facility to *copy* or *clone* such "MyPageDisplay"-display.

How can you **duplicate** a Views display like "MyPageDisplay" as a **different display type** in D7? And is there any type of improvement in Drupal 8 about this?

# Answer
# Drupal 7 solution

There is no **out-of-the-Views-box** solution for this in Drupal 7 ... Except if you get really creative (or via "***ugly ways***" as @MPD wrote in a comment below the question) with exporting / editing / reimporting such view. But that's not out-of-the-Views-box of course, and to my knowledge not included somewhere within the Views UI. Comment #1 in the issue about "Clone a Page view into a block view" seems to confirm this.

# Drupal 8 solution

In Drupal 8, for an existing display of a view, assuming it's a page display, you can say "***duplicate this display as another display type***". This will copy all of that view definition to the new display.

As an example, in a standard (core only) Drupal 8 site, you can now duplicate a page display as:

* another page.
* a block.
* an attachment.
* an embed **(1)**.
* an entity reference **(2)**.
* a feed.

This appears to be **one of the most exciting new features of Views in Drupal 8** ... Apart from Views in Drupal Core (= VDC) ... of course.

***Notes***:

* **(1)**: In the Views settings, if you select “Allow embedded displays”, then they can be used in code via `views_embed_view()`.
* **(2)**: In the Entity Reference field settings, select “Filter by an entity reference view” and use a view with this display type to define what can be referenced.

---

---

*Credits*: "*Babou*", who made me discover it while listening to "Talking Drupal (episode 111)".

---

---
> 4 votes

# Answer
> Assume you used Views to build a page display (in Drupal 7). And you want to create a Block display that's exactly the same (same filters, etc). There doesn't seem to be any facility to copy or clone such display.

Actually there is, you can clone it by clicking on +Add, then select Block.

**Caveat:** When you add a block, page, attachment etc.. it will always clone your original (master) view. (so you can't clone the clone)

Although, if you want to clone the clone, you could export the view, and copy the export code from the other block and modify the machine name. Then you just import the code.

**Bonus:**

If you then want to make changes to your block, so it's not an identical clone, you then need to select this page override when you click on fields, or other stuff, so it doesn't affect your page or any other view.
> 2 votes

---
Tags: views
---


# Question
Title: How do I show a link to the user registration page only to anonymous users?
I want to show anonymous users a "Register" link.

So, in `mymodule.menu.yml`:

```
mymodule.userregister:
  title: 'Register an Account'
  url: 'internal:/user/register'
  weight: 10
  menu_name: account

```

This adds a register link to the account menu next to the login/logout link-- great! Except it also shows up for authenticated users, who get an "access denied" error if they click it.

I looked in `user.links.menu.yml` in `code/modules/user` to try to find something I could use:

```
user.page:
  title: 'My account'
  weight: -10
  route_name: user.page
  menu_name: account
user.logout:
  weight: 10
  menu_name: account
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

```

I also checked `user.routing.yml`:

```
user.register:
  path: '/user/register'
  defaults:
    _entity_form: 'user.register'
    _title: 'Create new account'
  requirements:
    _access_user_register: 'TRUE'

user.logout:
  path: '/user/logout'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::logout'
  requirements:
    _user_is_logged_in: 'TRUE'

```

I'm stumped. **How can I make my menu link only show up for anonymous users?**

# Answer
> 4 votes
According to Structure of routes

> **\_role**: A specific Drupal role, eg. 'administrator'. You can specify multiple ones via "," for AND and "+" for OR logic. Note that, since the roles available may differ between sites, it's recommended to use permission based access restriction when possible.

so try

```
requirements:
  _role: anonymous

```

---
Tags: routes, 8
---


# Question
Title: add content reference to product in drupal commerce
how can I add content reference to commerce product? consider your product is mobile phone, and you don't want to enter add specifications of the phone, just make content type of phone, make phone contents and reference them in product. is there a better way? because I couldn't reference content in product.

# Answer
> 0 votes
I found the solution anyway:

Using EntityReference module this can be done!! you just add an entityreference field to your product and then in settings you choose your bundle.

# Answer
> 0 votes
The most usual is adding a field of type *Product reference* on your content type.

In fact it's a entity reference but drupal commerce manage all the dependencies and definitions.

---
Tags: commerce, nodes, entities
---


title: Add a style (CSS) to a custom block

text:
# Question
Title: Add a style (CSS) to a custom block
I've created a custom Block in Drupal 8 from the UI.

Is there a way to add a custom CSS style to this custom block?
Is it possible, like in Views, to click on CSS and type it in?

# Answer
> 3 votes
Easiest way to add a custom class to a block would be to override the default **block.twig.html** twig template within your theme.

You'll need to copy the above file from **/core/themes/stable/templates/block** **into your custom theme using the same directory structure**.

\** **NB** don't edit the file found in core directly!! This is bad practice and you'll lose any changes when you upgrade Drupal core. \**

Clear the cache and you should now be able to edit the block template file and customize it.

Then, to load CSS, you must define an asset library. You can then load that asset library using `{{ attach_library('mytheme/special-block') }}` in your Twig template (assuming the theme is called mytheme and the asset library special-block).

**Helpful links:**

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


# Question
Title: Home page only page accessible, no login with clean urls
I'm trying to copy a live site to my windows development machine for some module testing and updates. I have a copy of the complete live site's codebase (entire drupal root from live server) and the the sql dump file for the live site.

I'm using Acquia's Dev Desktop, and I use the import local site option, point the installer to the correct files and sql dump. The issue is that the installation seems to fail, in that navigating to the site triggers the installation script, and my database name and settings are imported but the database itself is empty. I then imported the correct database manually and ran the update.php script, but then only my home page shows up. Any page that isn't the home page gives me a 404 error, and I can't use clean urls to login, `?q=user/login` also gets me a 404.

I've checked the .htaccess file and it exists.

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

I don't think it would have to with my Apache settings because, that should all be taken care of by Acquia installer.

Where on the computer should the codebase folder be placed?

Is there anything special to how I should be copying the files?

# Answer
If the Acquia Dev Desktop configured Apache correctly, then you're most likely missing your .htaccess file in the ***root*** of your Drupal install.

I know sometimes on Windows machines **.htaccess** is hidden within FTP clients, and you need to change a setting so that you can see the file in directory listings.

The content of your .htaccess file you posted is from the Drupal **files directory**, which is usually located within **/sites/default/files**

Double check that you **.htaccess** exists in the route, and that it has the correct contents. I'd recommend grabbing an original copy from Drupal core.
> 1 votes

---
Tags: migrations, .htaccess, acquia-dev-desktop
---


# Question
Title: Where do I add a new cache context for an entity?
I have not been able to get adding a cache context to work for entities in drupal 8. Specifically I'm going for headers:User-Agent. I tried many variations on the following in a module.

```
 use Drupal\node\NodeInterface;
 use Drupal\Core\Entity\EntityInterface;
 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

 function hook_entity_view_alter(&$build, EntityInterface $entity, EntityViewDisplayInterface $display){
   if($entity->getType() == 'relevant_type'){
    $build['#cache']['contexts'][] = 'headers:User-Agent';
   }

 }

```

I'm trying to get node access to be checked when that context changes. I have also tried it in the `hook_entity_build_defaults_alter()` function.

# Answer
> 8 votes
You should indeed use `hook_entity_build_defaults_alter()`. Its documentation even explicitly states this:

> Alter entity renderable values before cache checking in drupal\_render().
>
> The values in the `#cache` key of the renderable array are used to determine if a cache entry exists for the entity's rendered output. Ideally only values that pertain to caching should be altered in this hook.

It probably didn't work for you because you forgot to clear the render cache after implementing that hook.

That hook is invoked in https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityViewBuilder.php/class/EntityViewBuilder/8

Also see https://www.drupal.org/developing/api/8/cache/contexts for an overview of cache contexts (what they are, how to use them, which ones core ships with).

---
Tags: 8, caching
---


# Question
Title: Drush 8.0.3 is unable to update D7 modules
I have Drush installed via Homebrew on my Mac. I am currently unable to execute "drush up" in a Drupal web site. When I attempt, I get the error:

Destination directory \[...\] already exists.

Is this normal? Do I need to use a different version? Do I need to stop using Homebrew?

# Answer
You could be hitting this issue \- there is a bug if you have a version control system such as SVN installed.

If it is this bug, the error should go away if you pass --version-control=backup. Of course you will then lose some integration with your version control system.
> 1 votes

---
Tags: drush
---


# Question
Title: How to only allow published content to appear on the front page?
I'm using the `Scheduler` module to schedule when certain nodes get published & unpublished. They are set to be "Promoted to the front page" and even after the `Scheduler` unpublishes the content, it stays promoted to the front page where it still appears and leads to a dead link.

How can I automatically set the content to also get un-promoted from the front page when it gets unpublished?

I also submitted a feature support request.

My front page is the default front page that comes with Drupal 7. I understand, that if I had my own view, I could select what kind of content gets displayed. But how can I do this with the Drupal 7 news feed?

Note: With mchar's suggestion, I came up with follwoing patch:

```
--- scheduler_orig.module   2016-02-20 12:52:02.002658565 -0800
+++ scheduler.module    2016-02-20 12:50:57.174657579 -0800
@@ -20,6 +20,20 @@
 define('SCHEDULER_DATE_LETTERS', 'djmnFMyY');
 define('SCHEDULER_TIME_LETTERS', 'hHgGisaA');

+/** [inserted by Ron 02/20/2016] -  to automatically unpromote a node as it gets unpublished**/
+/**
+ * Implements hook_node_presave().
+*/
+function my_module_node_presave($node) {
+  $was_published = !empty($node->original->unpublish_on);
+  $now_is_unpublished = empty($node->unpublish_on);
+
+  if (!$node->is_new && $was_published && $now_is_unpublished) {
+    $node->promote = 0;
+  }
+}
+/** [/inserted by Ron 02/20/2016] **/
+
 /**
  * Implements hook_permission().
  */

```

# Answer
> 1 votes
As far as I know scheduler module is not responsible for promoting or not nodes to the frontpage, so you have to go with a custom solution.

Try to implement hook\_node\_presave as follows:

```
/**
 * Implements hook_node_presave().
*/
function my_module_node_presave($node) {
  $was_published = !empty($node->original->unpublish_on);
  $now_is_unpublished = empty($node->unpublish_on);

  if (!$node->is_new && $was_published && $now_is_unpublished) {
    $node->promote = 0;
  }
}

```

Hope that helps!

---
Tags: nodes
---


# Question
Title: Clearing cache failed to add the new CSS properties
For Drupal 7, I'm using

* Cache pages for anonymous users
* Compress cached pages.
* Aggregate and compress CSS files.
* Aggregate JavaScript files.

The problem is when I update the CSS code for one of my CSS file, the code doesn't show in my page.

I have tried to **Clear all cache** and even run **cron**, but the new CSS code doesn't get added to the cached and minified version of my CSS.

The only workaround is just to disable "Aggregate and compress CSS files."

Any thought on this will be helpful.

# Answer
Your Drupal is not able to write inside `DRUPAL_ROOT/sites/*/files/css` directory. That's why aggregated CSS files are not renewed. Consult your sysadmin to correct permissions and allow Drupal full write access inside `DRUPAL_ROOT/sites/*/files` and all subdirectories, that should solve it.
> 1 votes

# Answer
Check the permissions on the parent directory holding your stylesheets to make sure your updates are writeable to those files.
> 0 votes

# Answer
Try the AdvAgg module. Go to the status page and check to see if AdvAgg complains about anything.
> -1 votes

---
Tags: theming, caching
---


# Question
Title: How to show a view each 5 rows in another view
I'd like to create a complex view which combines several views. I'm using Views Infinite Scroll

The view logic:

- view A row-1
- view A row-2
- view A row-3
- view A row-4
- view B Block 1
- view A row-5
- view A row-6
- view A row-7
- view A row-8
- view B Block 2

The difference between view B Block 1 and view B Block 2 is that Block 2 has offset from view B Block 1

Ok the adequate minimum is to insert view B Block 1 to each n row of the view A.

I tried to insert block in the view template but vainly.

Please help!

# Answer
this can be done by overriding your View's template for the Style Output plugin (e.g. views-view-unformatted--yourview\_machine\_name.tpl.php). Then in that template outputting something like this:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
    <?php
      // this tells the view to do something after every 4 rows
      if (($id % 4) == 0):
      print views_embed_view('view_machine_name', 'block_1');
      } ?>
  </div>
<?php endforeach; ?>

```

If you wanted to alternate your secondary View's blocks - you could add some logic for that too.
> 1 votes

---
Tags: views, theming
---


# Question
Title: My images are not showing up after importing to Pantheon
I finished creating my drupal site with WAMP and then imported the database. None of my images are showing up. I am assuming this is a file-path problem, but i'm not quite sure how to fix it?

For example, I have a image field in a content type, but it does not tell me where / how I can edit or change the pathing file.

# Answer
> 1 votes
By default, images uploaded through an image field are saved to the sites/default/files folder and not the database. Be sure that you have also imported your /files folder into your new site and the images should show up without needing any changes to file paths.

---
Tags: 7, database, media
---


# Question
Title: How do I create a rule to prevent a user from sending a message via the Privatemsg module?
As a courtesy to registered users on my website, I require all users who send private messages to have a profile picture.

I already have system messages throughout the site to encourage them to upload such a picture (for example, when they log in, or visit a user's profile) with a link to their account edit page where they can upload such a picture.

But how do I block them (without banning them of course) from sending a private message if they do not have a picture (in other words BEFORE the message is sent?)

Fall back scenario: If I cannot stop the action before it happens, how do I prevent the message from being delivered, with the appropriate warning to the sender of course?

The message is sent by the Privatemsg module, not the Rules module.

Any idea?

---

## UPDATE

I have tried both solutions proposed below (jeroen and Pierre Vriens) and both did the job.

Pierre's solution below works well and is easiest to implement.

For those who need guidance in implementing it, here are the steps:

1 - Create a new role. I called mine "can send private messages"

2 - Give this new role the "send privatemsg permission" only. Remove the same permission from the authenticated user permission (and other roles that have it and shouldn't.) At this stage, only those users who have the new role will be able to send private messages. The others will be sent to a "you do not have permission to access..." page.

3 - Create the first rule: Give it a name and select, under User, "an account is created." Save it. Create a second event and, still under User, select when an "account is updated." You now have two events in the same rule.

4 - Create the condition: Select "Data value is empty." Then drill down and select the name of the field that should contain the main picture (in my case, it is "site:current-user:field-user-image".) Below that, check the Negate box. This means the rule will check if the field is NOT empty.

5 - Create the action: You want the role to be granted if the field is not empty. So select "Add user role" under User. Data selector is "account" and select the value of the role (it's the name you gave to the new role.)

And that's it. To make the user lose the role if he removes the picture, you need to create a new rule, albeit a little less complicated. I called mine "disable private messages send." It only has one event: "After updating an existing user account" The condition is, again, "Data value is empty" but DO NOT check the Negate box. For the action, it's pretty straightforward. Like for the first rule but select the remove role instead.

For this rule to work the user must go into his account and click the save button. This is ok with new accounts but it may be a drawback if your site already has many users. But eventually, they will all update their account one way or another and the rules will be implemented then. If only a few users, the administrator (user #1) can go into their accounts and click on the new role box to grant the role.

See my second update below.

Again, thank you to Pierre for his insightful approach.

# Answer
Have a look at the community documentation about Privatemsg-Rules Integration, especially the child page about Introduction to Privatemsg-Rules: it lists the various Rules Events, Conditions and Actions you have available. I don't think there is anything in it you can take advantage of to do what you are asking for, and it won't help to implement your fall back scenario either.

But, as an alternative to "***trying to solve a problem***", you could use an approach to "***prevent the problem from happening***" ... here is what, pretty sure, should work:

1. Create a role like "PrivateMsgOk" (call it whatever you want).
2. Only grant access to private messages for role "PrivateMsgOk".
3. Use Rules to automatically assign role "PrivateMsgOk" after they uploaded their picture (and remove it again if they somehow can "remove" that picture afterwards).

The disadvantage of the above approach is that it does not permit the posting of a system message to notify (inform) the users (that are not allowed) to explain why such users cannot send a message. However here is a variation (enhanced version) of it in which you can make that work:

1. Create a role like "PictureUploadOk" (call it whatever you want).
2. DO NOT limit access to private messages to only those who have role "PictureUploadOk". Instead give that access to anybody you'd want to be able to "see" the private message functionality. But for those where their profile picture is missing they, they'll be interrupted when they try to send a private message, as explained below.
3. Create a 1st rule (using the Rules module) to automatically assign role "PictureUploadOk" after they uploaded their picture (and remove it again if they somehow can "remove" that picture afterwards).
4. Create a 2nd rule (using the Rules module) which is a variation of the rule included in my answer to "How to specify a Rules condition like 'Before creating new content'?". Here are the details of this 2nd rule:

* Use (System) **Rules Event** "Drupal is initializing".
    * Use a 1st **Rules Condition** like "Does NOT have the role 'PictureUploadOk'".
    * Use a 2nd **Rules Condition** that must also be true (so combined with the 1st Rules condition via an "AND") and which is like either of the `text_matches` that corresponds to an url like (say) `/messages/new` (assuming that's the URL to send a private message).
    * Within the **Rules Action** set your "*system message to notify (inform) the users (that are not allowed) to explain why such users cannot send a message*". Make sure to make it of type "Error" (not just "warning").
> 2 votes

# Answer
I don't think you can use the Rules module directly for this, because the only action that is provided by Privatemsg is called when a message has been sent. Therefore, I suggest you write an easy piece of code.

When a user hasn't set a profile picture yet, the field is empty or displays the default picture if you picked one in your configuration. In both cases, `$user->picture` has value `0`. You could use this fact by hiding the sending form for a private message with the following code in a custom module:

```
function MYMODULE_form_privatemsg_new_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($user->picture==0) {
    hide($form);
  }
}

```

As suggested in the comment below, you can also use `$form['#access'] = FALSE;` instead of `hide($form);`. You can add a line of code that, for example, displays a message *Please add a profile picture!* or whatever you want in the `if` statement.
> 4 votes

# Answer
Ok. Thanks again to Pierre.Viriens who provided the perfect answer. I wasn't too familiar with the "Drupal is initializing" event but it did the trick and the link he provided How to specify a Rules condition before creating new content was very helpful. Of course, I had to play with it and adapt it to my own circumstances to make it work. For those who are interested, I am reproducing the export of the final rule below:

```
{ "rules_private_messages_send_authorization_check" : {
    "LABEL" : "Private messages send authorization check",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "messages\/new" } },
      { "AND" : [] },
      { "data_is_empty" : { "data" : [ "site:current-user:field-user-image" ] } },
      { "AND" : [] },
      { "NOT data_is" : {
          "data" : [ "site:current-user:roles" ],
          "value" : { "value" : { "9" : "9" } }
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "message\/new" } } ]
  }
}

```

Note the two similar paths. The first one ("messages/new") is the Privatemsg module path for accessing the new message page (notice "messages" is plural.) The second "message/new" (singular) is the path of the node (article or page) I created. It is on this node that I can enter any message I want (and even include pictures and graphics too.)

If a user who does NOT have a profile picture tries to beat the system and adds an "s" to make the path read "messages/new" on the URL address bar he is redirected to a "You are not authorized to access...." default error page.

The value of "9" in the rule is assigned by the Rules module and corresponds to the name of new role I created for users who do not have a profile picture (see UPDATE above.)

All of this results in the user being sent to the module's "messages/new" page where he can send a message if he has a profile image or to the "message/new" page if he doesn't. Once there, he can't send a message and is informed why this is so.

I have thoroughly tested this rule and it operates flawlessly. The three conditions are necessary in my case.

Thanks you @Pierre.Viriens.
> 1 votes

---
Tags: 7, rules, privatemsg
---


# Question
Title: How to give the image path in the check box field option for a content type
I am creating a checkbox field in my content type and I want images to be displayed as checkboxes option.

In Drupal 7, there is a feature to add images as field list, but I am unable to give the full path for that image.

See the below screenshot for better understanding.

I cannot give my image path as http://localhost/sites/default/.. because the base path changes when we move to the Production. How can I achieve this?

# Answer
Your image path needs a `/` before `sites`. Should be `"/sites/default/files/test-image1.jpg"`

If you don't have a `/` at the start, then it appends your url code to whatever page you're on. Example: `node/1/sites/default/files/test-image1.jpg` which is not what you want (broken image since it doesn't exist)
> 1 votes

---
Tags: 7, entities, media
---


title: How do I extend an existing entity?

text:
# Question
Title: How do I extend an existing entity?
I would like to add some custom fields to the taxonomy\_term\_data table.

How do I programmatically extend the *Term* entity?

# Answer
> 3 votes
There is a hook for that `hook_entity_base_field_info()`. The code could look something like this

```
/**
 * Implements hook_entity_base_field_info().
 */
function module_name_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'taxonomy_term') {
    $fields['new_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setLabel(t('Label'));

    // You can add more options about visibility configuration etc.

    return $fields;
  }
}

```

The above could add "hidden" field, (not visible in display or edit mode and not configurable). You need to do the same thing as when creating base fields in a custom entity.

---
Tags: 8, entities
---


# Question
Title: Adding a Field 'Name on Credit Card' to Product Payment Page
I'd like to add a field called 'Name on Credit Card' to the product payment form on my site but I can't figure out how to add fields to that form. I'm using Commerce and the PayPal WPP module. The default fields for the payment page include only cc number, cc type (visa, etc.), csv, and expiration date.

Anyone know how to add a field to that payment form?

# Answer
You'll need to **implement some Commerce Payment form builder callback function within a custom module**, in order to **alter the existing form** that PayPal WPP provides.

The payment form is generated using **this callback**:

CALLBACK\_commerce\_payment\_method\_submit\_form

You will need to **create a custom form building callback function**, and then **use a hook to change the module's form building callback function name**.

Unfortunately I'm not sure off hand which hook you need to use, but the following links could guide you in the right direction:

Whatever you do, **don't edit the PayPal WPP module directly**, but you probably already know that.

**EDIT**

See **line 182 of commerce\_paypal\_wpp.module** for the form building callback you need to replicate and change in a custom module.

**EDIT**

I just found the correct hook for you to implement, in order to point the payment method to use your custom CALLBACK function. It comes from **commerce\_payment.api.php**. See extract from module function comments below (line 129):

```
callbacks (optional): an array of callback function names for the various
types of callback required for all the payment method operations, arguments
per callback in parentheses:

```

hook\_commerce\_payment\_method\_info\_alter
> 2 votes

---
Tags: commerce
---


title: How to debug closed connection error

text:
# Question
Title: How to debug closed connection error
I run a panopoly project currently with many many addidtional modules. How to debug a closed-connection-error while uploading an image?

# Answer
Disable all modules, including all core modules, that are not absolutely necessary for the failing functionality (uploading images). If the minimal configuration is working, enable each module one-by-one and test until the error occurs again, then you got the culprit.

In particular, disable Database logging.

If the basic install still causes the problem, start reading the server logs (it wouldn't hurt to check them immediately, but they might be empty), and check the server configuration.
> 0 votes

---
Tags: debugging
---


# Question
Title: The drush command 'migrate-manifest' could not be found
Not sure if it's a dupe issue, couldn't find it. Just trying to run an upgrade in drush8 and get:

The drush command 'migrate-manifest' could not be found. Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.

Tried with previous 8.\* version and got the same problem.

# Answer
answering my own question, this is now in the contrib module migrate-manifest:
> 1 votes

---
Tags: drush
---


title: I cannot clone my site

text:
# Question
Title: I cannot clone my site
Whenever I try to clone one of my sites, I get this error:

> Drush command terminated abnormally due to an unrecoverable error.
> Error: Cannot redeclare entity\_features\_get\_controller() (previously declared in /data/disk/dd/distro/005/drupal-7.41.1-prod/sites/www.firstsite.com/modules/entity/entity.features.inc:11) in /data/disk/dd/distro/005/drupal-7.41.1-prod/sites/www.clonesite.com/modules/entity/entity.features.inc, line 19

Could you tell me what the reason could be?

# Answer
> 6 votes
I would recommend that you avoid multisite, and clone the code into a separate codebase -- then copy the database. This is much easier to manage for simple use cases, and would entirely avoid your problem above, as you would only have one copy of each module present in your code base, so Drupal would not be able to load any of them twice.

I am not sure exactly how your situation above came to be, but the database from the original site contains references to all of the paths of all of the enabled modules; somehow, Drupal is trying to bootstrap both the old cached paths, and also the new paths for the same module in its new location. If you want to continue with a multisite setup, it is likely that a registry rebuild would clear this up.

---
Tags: drush, aegir
---


# Question
Title: How do I remove the information section available below the comment box?
As shown in the image, below the comment text-area there is an information section I do not want to show. How do I remove the part highlighted in red?

I want the comments to appears as they do on StackExchange, where user just have a text-area for entering their comments.

# Answer
Simplify module is what you are looking for. Besides hiding the text format selection, it has a few more settings to hide, which really "simplifies" the user interface.

> Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.
> 2 votes

# Answer
> Stack Exchange doesn't allow to use more than one input format

You can use the better formats module to allow 1 format, just like SE, which will get rid of the text format box.

### Better Formats

> * Set allowed text formats per field.
> * Set default order of text formats per field.
> * Hide format tips per role.
> * Hide more format tips link per role.
> * Hide format selection per role per entity.
> * Currently only works on Field API fields on fieldable entities implementing core style text processing. The good thing is that is most things in core and contrib.

The rest you will have to css `{ display none: }` it away

If anyone knows a better way, I'd like to hear it.

Actually, reading this I just realised there is a **hide format tips per role** :O

Perhaps that will get rid off the rest? :O
> 1 votes

---
Tags: 7, comments
---


# Question
Title: How to reload page after ajax form submit
I'm using FAPI #ajax to make the form more user friendly (it reloads in-place on validation). Works like a charm. However I would like to reload the page after form is submitted. How to that?

Obviously if I call for example `drupal_goto(current_path())` inside submit handler it won't do anything since this function is called via AJAX call. The actual page that user is on is not reloaded.

Is there some neat Drupal AJAX API trick that will allow whole page reload after AJAX form submit?

# Answer
> 0 votes
If you want to avoid the ctools dependency but want to avoid the pitfalls of inline js-ing...

In your submit handler

```
if (current_path() == 'system/ajax') {
  // This was an ajax submission.

  // Cause Drupal to rebuild the form
  $form_state['rebuild'] = TRUE;
  // Special flag, call it what you want.
  $form_state['ready_to_go'] = TRUE;
}

```

Then in your build form function do something like

```
if (!empty($form_state['ready_to_go'])) {

  // Add js to autosubmit, stored in an external js file.
  $form['#attached']['js'][] = drupal_get_path('module', 'mymod')
    . '/my-bit-of-js.js';

}

```

Then your `my-bit-of-js.js` file finds the form and submits it immediately.

## What this will do

Your form is ajax enabled. Validation errors are returned, as you wish. Once there are no validation errors, the form is submitted, but is actually returned rebuilt identical, except for the inclusion of your auto-submit-my-form js, which submits the form through a non-ajax submission, and from there you can issue whatever redirect you want.

While you could have your js do the redirect (as in your inline example), the benefit of doing the full non-ajax submission is that you can use PHP to determine *where* to redirect to, since the external js file is not going to be based on any of your form values, which the redirect might need to be. I know in this specific case you just want to reload. So just treat all this as a helpfully intended *jus' sayin'* :-)

## Aside: Multi-step form ajax except last page

I came upon this when I had a multi-page form that I wanted to be ajax until the final page (because I wanted a redirect on final submission). The way I'd done this was that I'd built the *last* page of the form *without* the `#ajax` on the submit elements. This resulted in quirky behaviour though because Drupal could no longer call the ajax callback that would return the last page of the form because it looks to the rebuilt form to find the callback(!). The solution I found was to hide (`'#type' => 'hidden'`) the "next" button and leave it's `#ajax` stuff in place, but then provide a different submit button without the `#ajax` stuff (which needed a different `#name`).

# Answer
> 10 votes
For the purpose of the question, an easy-ish way to do a redirect after ajax is with `ctools` and `ctools_ajax_command_redirect`

```
// In your ajax form submit callback
ctools_include('ajax');
ctools_add_js('ajax-responder');
// Path to redirect to
$path = 'node/12';
$commands[] = ctools_ajax_command_redirect($path);
// you can also use ctools_ajax_command_reload() –  xurshid29
print ajax_render($commands);
drupal_exit();

```

Note, it depends on ctools, which is a popular contrib module.

# Answer
> 3 votes
Another simple solution could be using a custom ajax command in your module JS file :

```
(function($) {
    // Custom AJAX commands
    if(typeof Drupal.ajax != "undefined") { // Ensure follwing code will not generate errors in administration pages
        Drupal.ajax.prototype.commands.reloadPage = function(ajax, rsp, status) {
            location.reload();
        };
    }
})(jQuery);

```

Then call it when returning your array of commands in your ajax callback function :

```
$commands = array();
...
$commands[] = array('command' => 'reloadPage');
...
return array('#type' => 'ajax', '#commands' => $commands);

```

# Answer
> -2 votes
Instead of messing with ctools i've just set a flag in submit handler to let the ajax callback know that the form was submitted correctly and the page can be reloaded. Then inside the callback function I just returned some JavaScript instead of a form.

```
function my_module_ajax_callback($form, $form_state) {
  if ($form_state['my_flag']) {
    $ret =  '<script>';
    $ret .= 'jQuery(document).ready(function($) {';
    $ret .= '  location.reload(true);';
    $ret .= '});';
    $ret .= '</script>';
  }
  return $form;
}

```

Works perfectly.

---
Tags: 7, forms, ajax
---


# Question
Title: Manipulate a field before it is rendered
I want to add two text fields and programmatically alter their content before the fields are rendered. The fields should use a WYSIWYG editor.

How would I go around this?
Should I create my own custom field or use hooks?
Can you provide a not too complex example?

# Answer
Since version 5, Drupal provides filters, a mechanism to manipulate the value of a text filter before rendering. In Drupal 8, filters are implemented as plugins.

So, in order to have two (text) fields which can can manipulate the value before display, you would need to

1. Create a custom filter (in a custom module)
2. Define a text format specific for your two fields, configured to use your custom filter (and any other filter you still want to apply)
3. On your content type, configure the two fields to use that text format
4. ?
5. Profit

You filter code would look like

```
namespace Drupal\celebrate\Plugin\Filter;

use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * @Filter(
 *   id = "filter_ninjafart",
 *   title = @Translation("NinjaFart Filter"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class NinjaFartFilter extends FilterBase {
  public function process($text, $langcode) {
    $text = doSomethingWith($text);
    return new FilterProcessResult($text);
  }
}

```
> 3 votes

---
Tags: entities, 8
---


# Question
Title: Any way to have "Path Will Be Viewed" trigger?
I would like to restrict certain roles from visiting certain pages, ideally by using Rules.

I am able to do this with Nodes, however for Pages such as a Views Page, I can't see any way of triggering this redirect?

# Answer
> 3 votes
If you simply want to restrict the access to the View, you should alter the settings for the View.

Under the access settings, select Role instead of Permission, and select the appropriate role.

However, if you have to use Rules for some other reason, I would create a rule that triggered every time Drupal is initializing. And then, add a condition with custom PHP code. You could do something like

```
global $user;
$rid = 1;
return ($_GET['q'] == 'my/forbidden/path' && isset($user->roles[$rid]));

```

and then add an action that redirects the user to another page.

# Answer
> 1 votes
I guess you can achieve what you're looking for using Page Manager Redirect instead of Rules.

# Answer
> 1 votes
Selection rules like this are why we typically use Panels for displaying all pages. Rather than use different access methods for different page types, you get a consistent interface.

In you case, you would set up your view as a Content Pane and not a Page. You would then build a new panel page, and when you can add content, your view will show up in the View Panes tab.

You can then set up your selection rules. Among the rules are User Permissions and User Roles.

# Answer
> 1 votes
Sure there is a way to exactly do what you are asking for, i.e. "***... restrict certain roles from visiting certain pages, ideally by using Rules.***".

The trick (clue) to actually do this is like so:

* Use **Rules Event** "Drupal is initializing".
* Add the appropriate **Rules Conditions** to check for the "Roles" you want to verify, and the "Path(s)" you want to apply this to.
* Typical **Rules Actions** you might want to do are to set some Drupal Message, and/or some redirect to some other page.

Below is an example of such rule (in Rules export format) that is pretty close to what you asked for:

```
{ "rules_limit_access_to_some_urls_" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "abc\/x123",
                  "efg\/y456",
                  "hij\/z789"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "some_path" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

Some more details about verification in the **Rules Conditions** in the above example:

* check if the current user is not an administrator (for administrators the Rules Action does not apply)
* check if the "path that will be viewed" is either `abc/x123`, `efg/y456` or `hij/z789`, or if it is a path with a pattern like `node/x/something` (with x some digit(s)).

If both **Rules Conditions** are true, then the **Rules Action** will perform a redirect (to a path like `some_path`), and some message is shown to the user.

To make the above rule work in your case, just adapt the paths (change them to whatever fits), and the message to be shown for those who are not allowed to access those paths.

Note that it doesn't matter what these paths relate to: they can be nodes, views pages, user profiles, etc (all such cases should work).

---
Tags: 7, rules, redirection
---