# Question
Title: How to change authoring information with Rules?
I'm trying to create a rule that fires upon saving a node with a few conditions. The rule takes the current author, and sets it in a field called "field\_original\_author" and after that changes the value of the current author information to a particular author.

It does the first bit but not the second. Even if I only use the second part, it still doesn't change the author information into the other author that I specified.

What gives?

# Answer
I can't remember exactly, but you can create an action "Fetch entity by ID". Add user as the entity type, and create another action "Set a data value" with selected data \[node:author\]
> 1 votes

# Answer
Have a look at this custom rule, which should answer the "*...after that changes the value of the current author information to a particular author*" part of your question:

```
{ "rules_optionally_change_node_author" : {
    "LABEL" : "Optionally hide change author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : {
              "article" : "article"
            }
          }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : "68" },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched user" } }
        }
      },
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "user-fetched" ] } }
    ]
  }
}

```

Some more details about this rule:

* The rule checks that the content type is "Article" (adapt to fit your needs, or just omit it if you want this logic to be applied for any content type).
* I added 2 extra Rules Conditions to verify that the field with machine name "`field_optionslist`" has a value of "`C`" (adapt to fit your needs).
* In the Rules Action, it fetches the user with `uid=68` (replace `68` in it by the `uid` that matches your *particular author*).

PS: I'm assuming this question is about D7.
> 0 votes

---
Tags: rules
---


title: Role level file access control

text:
# Question
Title: Role level file access control
I have been asked to control access by different groups of users to files uploaded to a website.

This covers both files uploaded as a field, and files uploaded via IMCE and CKEditor.

I have several Roles to handle; Anonymous users, Authenticated Normal User, Authenticated Coordinator. And probably some more later.

There are already Permissions controlling access of users to relevant nodes and forum topics. For example, an anonymous user can only see the public part of the site, the normal user can see some content types and forums and coordinators can see everything a normal users can see as well as some extra forums.

I need files uploaded by authenticated users in the restricted part of the site to 100% not be accessible to anonymous users. And, I need documents uploaded by the coordinators to not be accessible by the normal users.

Currently, normal users can bypass the node and topic permissions to access files if they have the direct link.

How should we approach this?

# Answer
The first step is using private files, because you can not control access to to public files as Drupal is not involved when they are delivered.

Private files in plain file fields (file and image, not media entity) automatically respect node access and will only be accessible if the user has access to at least one node that is using the file.

As you mention that users can bypass node access, I assume you have node access already implemented and it should then just work
> 0 votes

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


# Question
Title: How do I dynamically modify a block's mark up at render time, in Drupal 7?
I have a page with the following structure:

* Header zone

+ Header One Area (block)
* Content zone

+ Content Area (node)

The rendered node has an image attached to it. What I need to have happen is to make the attached image render inside the "Header One Area" block instead of as part of the content.

This is proving difficult, since blocks and their #markup are rendered before a node is processed. The better idea I had is to create a preprocess function for the page, through code figure out the node\_id being rendered, grab its images, and then dynamically modify the blocks markup.

I have tried creating a `MYTHEME_preprocess_page()` method inside my template.php and then accessing the block via:

```
if ($block = block_get_blocks_by_region('header_one_area')) {
   // what code do I need here to make a #markup modification stick ???
   $block['block_4']['#markup'] = "<h2>TEST</h2>";
   print kpr($block);
}

```

I'm not quite sure how to actually modify its markup dynamically before it is rendered here.

Do you have any suggestion?

# Answer
> 7 votes
I think you are looking for `hook_block_view_alter()`. It provides both the alterable `$data`, as well as `$block`, which contains the module and delta.

To determine which blocks are available, you could start off with:

```
function MYTHEME_block_view_alter(&$data, $block) {
  kpr($block->module);
  kpr($block->delta);
}

```

Then once you find the module:

```
/**
 * Implements hook_block_view_alter().
 */
function YOURTHEME_block_view_alter(&$data, $block) {
  if ($block->module == 'block' && $block->delta == 1) {
    $data['content'] = '<p>New content</p>';
  }
}

```

Or even:

```
/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function YOURTHEME_block_view_block_4_alter(&$data, $block) {
  $data['content'] = '<p>New content</p>';
}

```

# Answer
> 0 votes
if you can delegate the changes to the browser client, you can use Jquery to manipulate the html. See this functions (with examples) to manipulate (change/move/detach/attach/etc) your html http://api.jquery.com/category/manipulation/

http://www.w3schools.com/jquery/jquery\_html.asp is another interesting resource.

here is one example to move one html element inside other (in this example the div with id="one" will be inserted inside div id="six"using the appendTo() Jquery method):

```
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("div#one").appendTo("div#six");
});
</script>
</head>
<body>
<div id="one"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/200px-FullMoon2010.jpg"></div>
<div id="two">text</div>
<table border=1><tr><td>
<div id="six">text</div>
</td></tr></table>
</body>
</html>

```

note that you can use jquery in the header (like previous example) to put inside your `page.tpl.php` or you can use jquery after render your html target:

```
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="one"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/200px-FullMoon2010.jpg"></div>
<div id="two">text</div>
<table border=1><tr><td>
<div id="six">text</div>
</td></tr></table>
<script type="text/javascript">

    $("div#one").appendTo("div#six");

</script>
</body>
</html>

```

# Answer
> 0 votes
The accepted answer will overwrite the block's content altogether. #prefix and #suffix can be used to add markup to the block before or after the content.

```
function mymodule_block_view_alter(&$data, $block) {
  $data['content']['#prefix'] = '<div class="my-class">';
  $data['content']['#suffix'] = '</div>';
}

```

The `#prefix` and `#suffix` will be honoured for any Drupal render array when it's passed through `render()` (or `drupal_render()`).

---
Tags: 7, nodes, blocks, theming
---


title: Redirect when submit Feedback form

text:
# Question
Title: Redirect when submit Feedback form
I have made a Feedback Form in comments entity, Each node has multi file fields, I'm looking to force the users to submit the form & give their feedback after that redirect them to file download when click submit button, I'm using Views & Custom Formatters and I made the feedback form displays in Colorbox popup to keep them on the same page

feedback URL "node/%/feedback"

is there any function that can help me ? I'm using Drupal 7

# Answer
> 1 votes
You have to add a submit function if you dont have and set the url you want redirect in $form\_state\['redirect'\].

```
function my_custom_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/10';
}

```

More information here.

# Answer
> 0 votes
You should use custom submit handlers for your form.

After submitting the first form, you should make a redirect tour feedback form and after submitting the comment form you should make a redirect to the files page.

See this tutorial for further information.

---
Tags: 7, views, javascript
---


# Question
Title: How to change value of hidden field on node publish?
My client has a system in which they allow nodes of certain content types to be created by authenticated users. The nodes are unpublished until they are reviewed by someone with the proper role and this all works correctly.

One of the requirements was allowing users to save a node as draft. I initially used the Save Draft module but found that was defaulting nodes to be published which caused problems. I worked around this by adding a hidden field called status that would change values based on which submit button was clicked via hooks.

Now, the issue comes when the node is reviewed. At that point, an admin will change the node to published. They would also like automatically like this hidden status field to change from "submitted" to "published". Normally, I would use a hook for this but through my testing, I can't seem to get form alter hooks to work in the admin section.

I suppose I have two questions here:

1. Is there an easier way to achieve my end result here?
2. Failing that, is there a way to automatically change the value of one field when a node is updated via the admin section?

# Answer
Piece of cake, if you are willing to use the Rules module for this ... like so:

* Rules Event: before saving content, which covers all variations of updates of nodes, and creations of new nodes (and does not require an explicit "entity save" action).
* Rules Conditions:

+ Entity has field, for your hidden status field, that way the logic implemented via this rules only applies for nodes that use this field.
    + Node-unchanged has status unpublished.
    + Node-changed has status published.
* Rules Action: Set a data value, for your hidden status field, to assign the value 'published'.

With the above in mind, have a look at this rule (in Rules export format), in which I'm using a status field with machine name `field_status` (and for which a value of "`P`" reflects "`Published`" status:

```
 "rules_change_value_of_hidden_field_on_node_publish" : {
    "LABEL" : "Change value of hidden field on node publish",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } },
      { "NOT node_is_published" : { "node" : [ "node-unchanged" ] } },
      { "node_is_published" : { "node" : [ "node" ] } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-status" ], "value" : "P" } }
    ]
  }
}

```

If you adapt the machine name `field_status` to match your own field's machine name, together with the value used to reflect "Published" status, you should be able to import the above rule in your own site. After doing so ... you should be done!
> 2 votes

# Answer
You should be able to do this with a hook.

If you get frustrated with hooks, you can try the Rules module.

I would set it up something like this:

Event: When publishing a node

Conditions:

* Node is of content type ABC
* Status field is "Submitted"

Actions:

* Change status field to "Published"
* Entity save

These names are from memory, so the actual names will be a little different. Rules is not faster than writing hooks, but if you are having trouble with hooks, it can sometimes be an easier solution that doesn't require writing code.
> 1 votes

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


title: Indentation in Drupal 8 form

text:
# Question
Title: Indentation in Drupal 8 form
I have a drupal 8 form as follows:

```
   $form['extra_fields']['email'] = [
        '#type' => 'checkbox',
        '#options' => ['email' => 'email'],
        '#title' => $this->t('Email')
    ];

   $form['email']['required'] = array(
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => array(0 => $this->t('Required'), 1 => $this->t('Not Required')),
    );

```

which shows up as:

I would like to have the radios a bit indented. Is it possible to achieve this? Also, how to make the radio buttons inline?

Thanks.

# Answer
## Assuming you built this form programmatically (custom module):

### Wrap your radios field inside a class using #prefix and #suffix

```
   $form['email']['required'] = array(
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => array(0 => $this->t('Required'), 1 => $this->t('Not Required')),
        '#prefix' => '<div class="indent">',
        '#suffix' => '</div>',
    );

```

### Use CSS to alter the look.

Create a CSS file.

**my\_module/css/myform.css**

> a bit indented

```
.indent {
  margin-left: 10px;
}

```

> make the radio buttons inline?

```
.indent .js-form-type-radio {
  display: inline-block;
}

```

Create a library

**my\_module/my\_module.libraries.yml**

```
form-stuff:
  version: 1.x
  css:
    theme:
      css/myform.css: {}

```

### Attach library to your form so it loads your CSS

```
$form['#attached']['library'][] = 'my_module/form-stuff';

```
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Nightly truncating all cache_* tables? Good or bad?
I'm having some issues on various D7 sites with some cache tables growing stupidly large (e.g `cache_metadata` or `cache_menu`) which then makes `drush cc all` very slow (more than 1 minute).

Do you think that there is any problem if I setup a nightly linux cronjob which will be truncating `cache` and `cache_*` tables apart from `cache_form`? And after that I plan on executing a `drush cc all` for safety.

p.s I do not plan on investigating and trying to fix the root cause that makes those tables grow large.

# Answer
> 0 votes
Cron job to truncate the tables might cause some metadata locks due to the TRUNCATE command being a DDL statement; depends on how busy your server is. What APDQC does is a table rename swap and then truncate; if you did something similar then you should be ok. APDQC will also use gzip to make the table sizes smaller; something that would be a benefit in your case. Without compression our DB cache tables would take about 50GB, they now take about 12gb.

---
Tags: 7, caching, performance, cron
---


# Question
Title: What reasons are there for views not rendering a link?
The link passes the nid and date to another view. List of classes presenting a link to a list of bookings.

In the following example John's class has a link but Jake's class does not.

The 'Add booking' and 'Claim' links work for all classes and pass the url as nid/time where time is in seconds rather than formatted to be passed to views.

The date field is setup with the date formatted as follows

The link is created through rewriting

More things that don't work.

* Turn off Style settings \> "add default classes"
* Just rewrite the text instead of "Output this field as a link". I get the half closed span. This is true if I rewrite the source field.

2017-09-26AEST14:35"\>View Bookings
* Creating a plain text field and rewriting there. Same result as for rewriting inline.

I can see why taking the default classes away might work, as it might stop the date formatter wrapping the text. The link formatter looks like it is removing the span, so any other rewriting doesn't work.

# Answer
> 0 votes
This works if you set up a source field:

* Create a source field with the date formatting.
* Rewrite the output of the field with just the tag. \[date\_when\_2\] in my case.
* Select "Strip HTML tags".

Then create a custom text field that rewrites the output as the link.

---
Tags: views
---


title: Folder and file sharing in Drupal

text:
# Question
Title: Folder and file sharing in Drupal
Here is what I am trying to achieve. I have two roles Teachers and Students.

Each teacher has images of answers written by the students in an exam. After checking these papers, teacher takes an image of each answer-sheet. He names it in a certain pattern using student-id. Thus, teacher has many images (like sid-1-im1.jpg, sid-1-im2.jpg, sid-2-im1.jpg). A student can have multiple images on his name depending on how many sheets he had submitted.

I want to create a website where a teacher can create a folder for this exam, say, Economics-2017-2018. Within this folder, he can upload all images. What would be the best way to achive this folder+multi-file upload?

Next I want to programmatically assign permissions to these uploaded images based on student id of the file name. So that, a student can view only his files.

How can this programmatic feature be achieved.

There are more features such as notifying students, ability to comment on files etc. But, I think drupal can handle them easily.

I intend to use Drupal 7 or 8 for the purpose.

# Answer
You wouldn't actually need to write any custom code to implement something like this.

A possible solution is outlined below. It is aimed at Drupal 7. Some of the functionality mentioned may not be ready for Drupal 8 so you might need alternate modules or custom code in those cases.

1. Create a new content type, which would be named "Exam paper" or similar. There would be one node per student per exam.
2. Add a multiple value file field to the content type. Make sure it uses the private file system. Using the private file system will mean that only users with access to the node will be able to access the files attached to the node.
3. You can use the file field paths and token modules to make it so that the file directory structure and file names match the pattern you want. With the tokens you can easily reference student, teacher or exam information from fields on the node in the path or file name. This has no effect on access control but might make things better for you in other ways.
4. There are a number of ways you can handle access control as there are a variety of access control modules available for nodes, however I would be inclined to go with the node access user reference module. So you would add an entity reference field on the content type that references users with the student role. You can then set permissions so that the referenced user can access the node and other users cannot.
5. You can use the rules module to notify the user under various circumstances.
6. You can use Drupal core comments to have comments on exam paper nodes.
7. Due to using nodes you can leverage the wide variety of add on modules that focus primarily on nodes.
8. If you want to store additional data with each specific file, you can install the file entity module, which will allow you to add fields at the file level as well as the node level.
> 1 votes

---
Tags: users, files
---


# Question
Title: Display suite, two layouts for the same node?
I'm using display suite with nodeblock and I'd like to have a different layout for the block than the main page. How can I do this?

# Answer
You can do this by using different view modes.

1. On the content type edit page (eg. admin/structure/types/manage/page) you can set a default view mode for node blocks of that content type.
2. On the content type manage display page (eg. admin/structure/types/manage/page/display) configure the full content display mode (or default if you haven't enabled the full content mode) the way you want the full pages to display and configure the view mode you specified in step 1 the way you want the blocks to display.
3. You mention display suite in your question. You can also create additional view modes using display suite (admin/structure/ds/view\_modes)
> 2 votes

---
Tags: blocks, display-suite
---


# Question
Title: Access field value in template_preprocess_views_view_field function?
I have a client with a Drupal 8 site who prefers curly quotes to straight quotes. I have successfully made this change for node titles using a regex replacement in template\_preprocess\_page\_title. Now I am trying to accomplish the same thing for a different text field that is rendered by a view, using template\_preprocess\_views\_view\_field or template\_preprocess\_views\_view\_fields, but for the life of me I cannot figure out how to get individual field values using this function. Am I even trying the correct preprocess functions?

I have also tried rewriting the output of the field by accessing the variable in a custom twig template, with poor results.

# Answer
It depends how you have your view set up.

If you have your view using the format 'Fields' then you can override the content with template\_preprocess\_views\_view\_field() like you say, like this (although you might want to target individual fields with some if statements):

```
/**
 * Implements hook_preprocess_HOOK() for views-view-field.html.twig.
 */
function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      // Replace characters in the field output.
      $variables['output'] = Drupal\Core\Render\Markup::create(str_replace('find', 'replace', $variables['output']));
    }
  }
}

```

If you are using the format 'Content' then you could do it at the field template level or node template level instead, since in that case it doesn't use the views field templates.
> 16 votes

---
Tags: views, theming
---


# Question
Title: routing.yml for a custom form not working
I have a form I'd like to use as a standalone page, which I'm defining in a module I've called "SREvent". I have created modules/srevent/src/Form/SREventListForm.php:

```
<?php
/**
 * @file
 * Contains Drupal\srevent\Form\SREventListForm.
 */
namespace Drupal\srevent\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\srevent\Entity\SREvent;
use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\field_collection\Entity\FieldCollection;

class SREventListForm extends FormBase {
    public function getFormId() {
        return 'srevent_list_form';
    }

    //used in getEvents()
    public $inactive = [];
    public $active = [];

    //function to get all appropriate entities
    function getEvents() {
        //....
    }

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

        getEvents();

        //form builder logic

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        return;
    }

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

```

In routing.yml, the route is as follows:

```
srevent.list_form:
  path: '/srevent/listform'
  defaults:
    _form: '\Drupal\srevent\Form\SREventListForm'
    _title: 'SREvent List'
  requirements:
    _access: 'TRUE'

```

There are other routing entries in this file as well, but none of those are giving me errors. I double checked for typos in the routing file as well as to make sure all indents are spaces and not tabs.

After flushing the cache repeatedly, /srevent/listform is still a 404.

This is how I set up all of my forms and have never seen this issue before, and every post I see on the topic tells me to set up exactly like this.

Is there something I'm missing? This is driving me crazy...

# Answer
Try these steps one by one.

**Keep calm.**

1) Check you are in the correct domain in your browser

* Ugh, I hate when this happens, wrong domain, lol.

2) Check you're uploading or committing to the correct environment

* Download the file from the server to see if it indeed changed and make sure you're in the correct environment.

3) Check that your form (SREventListForm.php) is indeed inside the /Form folder.

**Simplify your process**

4) Back up your current module. Delete all the other routes except for the one that you're trying to dbug.

5) Simplify your form's code. Put some basic code in there.

6) Change your routes path
> 0 votes

# Answer
You don't need the first slash in your path:

```
path: '/srevent/listform'

```

Change for this:

```
path: 'srevent/listform'

```

Clear caches after that. That can be the problem. I recommend following the form examples from examples 8.x. It contains very useful examples of drupal code.

Ensure too your routing yml file is stored in the same level of your module and is called srevent.routing.yml
> 0 votes

# Answer
In your routing.yml file under **requirements** try writing ***\_permission: 'access content'*** instead of \_access: TRUE

OR

May be you should try creating a new permission like ***\_permission: 'perfom some action'***, then you can create a permissions.yml file and write below mention code

```
perform some action:
  title: 'Perform some action (you can give any meaningful title over here)'
  restrict access: true

```

Once again just clear the cache, also you can try opening it in a private window after getting cache cleared.

I hope this should work.
> 0 votes

---
Tags: 8, routes
---


# Question
Title: An entity autocomplete widget with opportunity to save its text content
There is the standard insert or edit node form with an entity\_reference field and the EntityReferenceAutocomplete widget.

The client needs to save string values inputed to the widget in case of entity wasn't selected from the autocomplete list. That is, client needs to have possibility to select entity from the autocomplete list or input string value if, for example, entity is absent in the list. And new entity shouldn't be created in this case.

I'm thinking how to create this opportunity the best way. And I'm little bit confused.

Is it possible to perform it with alter hooks only and without creating new field widget ?

Or otherwise is it possible to do it creating a new field widget having inherited it from the class EntityReferenceAutocompleteWidget ?

Or maybe the single solution for it is creating a custom widget based on TextField with including autocomplete function manually ?

Has anyone encountered with a simular task ?

# Answer
There is no need to create a custom table or a second field. While editing your entity reference field, in the "Reference type" section, you could check the "*Create referenced entities if they don't already exist*" option. If for instance, your field is referencing taxonomy terms, a new term for the referenced vocabulaty will be created. I hope that this helps.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How do I get an argument of a path with Rules URL Argument?
I am trying to get the first argument of a path in rules. That argument would be needed to fetch an Entity. I have no idea how to "tell" Rules URL Argument "get the first argument". Then I tried to get that part of the URL with regex...but I failed retrieveing just that part (it only checks whether it is "there").

I am not a coder....no idea of php...

**Note**: I tried for example to set the Argument path Name: `site:current-page:path:1` \- which is obviously not working.

# Answer
> 2 votes
To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

For an example of a rule (in Rules export format) that uses this module, refer to (Step 4 of) my answer to "How to limit access of a view about Group Memberships to the Group's administrator?".

The above explains ***How to get AN argument*** (as in the question title) using this module. However, to my knowledge this module cannot be used to ***set the ARGUMENT value to "the first Argument"*** (as in your comment below this answer).

---
Tags: 7, rules
---


# Question
Title: How do I add an image to a block in Drupal 7?
I want to add an image to a block located in the First Sidebar in Drupal 7. Does anyone know how to do this? Thank you.

# Answer
> 8 votes
This answer may seem needlessly complex to answer such a simple question, but that is because I have no interest in giving fishes away, I want to teach fishing.

Other answers suggest you embed the image directly in the block with an `<img>` tag. Personally I oppose that solution because it's "one-off" and prevents the rest of your site's functionality from interacting with the image, such as automatic rescaling of the image.

Two suggestions:

1. Upload the image to a node, create a View that lists your image, and expose it as a block
2. Use Panels to control the rendering of your page, and add the image, also from a node

While I strongly recommend using Panels, it's usually quite complicated to setup and understand for Drupal beginners so you may want to skip that.

# Answer
> 3 votes
First question-What kind of block is it? If it is just a new block that you made from the "add a new block" link, then you could either use HTML code, or as WYSIWYG (What you see is what you get) editor to put one in there.

Second question - Do you have a WYSIWYG module installed?

A good one is CK editor located here

You will also need an upload tool to upload your images, A lot of people use IMCE, which is located here

If you decide to go with CK Editor, you will have to choose IMCE as your file upload tool

Also, once you have these modules installed, you will have to create an input format that will allow for the display of the images you posted, since the CK editor and the like essentially put raw html into your block

Check out this article here - http://drupal.org/documentation/modules/filter. It will give you the low down on input formats

This may seem like a daunting process for those beginning with Drupal, but once you get the hang of it, it will all make sense.

# Answer
> 3 votes
The text format used in the block will need to allow images. If you use Filtered HTML, you can add the `<img>` tag to the allowed tags, or you can use Full HTML (generally not recommended, use with caution!). If you have already uploaded the image via FTP, you can include it using something like `<img src="/sites/default/files/image.jpg"/>`.

If you want to be able to easily upload and insert images via the user interface, a good and often used combination is WYSIWYG API with the CKeditor library (ckeditor.com)and the Media module. If you use that, add the Media filter to your text format and configure its WYSIWYG profile to use CKeditor. You can then use a 'Media browser' button to upload and insert images (and other media) via the editor.

# Answer
> 1 votes
Just download CKEditor and install it to your Drupal 7 then also install all the corresponding modules. You will be able to put images even videos at any position in any block CKEditor.

CKEditor might give you a problem showing you some errors but don’t worry just un install it ant reinstall it. I used `ckeditor_3.6.2-3_for_drupal_7` and worked for me.

# Answer
> 1 votes
Personally I have never been a fan of WYSIWYG editors, instead I prefer coding PHP straight in to the body. The Drupal puritans amongst you will no doubt be aghast at the use of PHP in a block but if its only accessible to the admin user then it really isn't a problem.

Whilst these are all valid answers and all work in their own particular use case, the simplest method merely involves having the image reside in your currently enabled themes directory and ensuring that the block content body field is enabled for PHP code.

```
<?php
$theme_name = 'name-of-enabled-theme';

/* optional parameters */
$alt_text = 'image-alt-text';
$image_width = '100';
$image_height = '200';
$image_class = 'the-class-name';
$image_id = 'the-id';

/* pass it all into theme_image() */
print theme('image', array(
                      'path' => drupal_get_path('theme', $theme_name) . '/path/to/image.jpg',
                      'alt' => $alt_text,
                      'width' => $image_width,
                      'height' => $image_height,
                      'attributes' => array(
                                        'class' => $image_class,
                                        'id' => $image_id
                      )));
?>

```

This will produce the HTML markup;

```
<img width="100" height="200" alt="image-alt-text" src="http://www.mydomain.com/sites/all/themes/mytheme/images/imagename.jpg" typeof="foaf:Image" id="the-id" class="the-class-name">

```

Most of the attributes/parameters really aren't needed as it does the same job when all you pass into the theme function is the theme name and the image path and name. If you are building out a responsive site then don't include the width and height attributes instead use the class name and set it to 100% in your CSS, that's assuming the image container element is also percentage based according to its container.

I have to admit though that the fact that the `theme_image()` function doesnt produce a self closing image element (`<img />`) has always troubled me :)

# Answer
> 1 votes
I think now in drupal 7 another good option would be using BEAN module ("Bean is an acronym that stands for Block Entities Aren't Nodes"). This module is not as simple as Imageblock but it extends blocks funtionality futher. You can create "content types" for nodes as "block entities". Not only for showing images, also multiple images, or any other field type avaible in drupal field system. I get to BEAN searching for an imageblock type module with an integration to the Media module. I will give a try in my current proyect.

The BEAN module also was covered here:

The last release was on 8-Aug-16 but Maintenance status is Seeking new maintainer and Development status is Maintenance fixes only.

# Answer
> 0 votes
I am using one really quick and easy solution on my Drupal 7.22 - **Wysiwyg** editor with **TinyMCE 3.5.8** and i have also enabled the **IMCE module** and **IMCE Wysiwyg bridge**

You have open

> Configuration -\> Content Authoring -\> Wysiwyg profiles -\> Select Full HTML

or which one do you use?

**Edit**
In the setting you have to open **Buttons and plugins**, than almost on the bottom is IMCE, which add you icon for using its own upload manager.

Its usable everywhere on the site, where is Wysiwyg editor available.

# Answer
> 0 votes
Enter bean module.

> What is Bean? Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require. The bean content can then be placed around the site just like any other block.

Quick instructions:

1. Enable bean and bean\_admin\_ui module.
2. Create a bean type to host images.
3. Add an image field. Configure the field to suit your needs.
4. Create blocks of the new type.

# Answer
> 0 votes
Image Block module

> Image block is a module where one can create a simple block that includes an image. The 6.x version of this module integrates with Imagecache and 7.x with the core Image module's Image Styles for dynamic image sizing and manipulation.
>
> **How to use:**
>
> 1. Enable Image block module.
> 2. Navigate to admin/build/block.
> 3. Click the "Add image block" link in the local tasks menu.
> 4. Configure your image block, and save.

# Answer
> 0 votes
Image block is a module where one can create a simple block that includes an image. The 6.x version of this module integrates with Imagecache and 7.x with the core Image module's Image Styles for dynamic image sizing and manipulation.

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

# Answer
> 0 votes
There are many ways to add images in blocks. One way is:

> 1. create content type and image fields
> 2. Create view for this content type and add image field in view
> 3. Asign a block for your view
> 4. Add an image you want to display in the block.

---
Tags: 7, blocks, media
---


# Question
Title: How to get the URL of an entity being created at hook_entity_insert() stage?
I'm trying to send an email "someone added content" with the URL to the entity as the message body.

```
function MYMODULE_entity_insert(EntityInterface $entity) {
  if ($entity->getEntityTypeId() === 'node') {
    switch ($entity->bundle()) {
      case 'contact':
        MYMODULE_mail_notify_admin($entity);
    }
  }
}

function MYMODULE_mail_notify_admin($entity) {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'MYMODULE';
  $key = 'contact';
  $to = 'secret@secret.com';
  # $to = \Drupal::currentUser()->getEmail();
  $params['message'] = $entity->toUrl()->getUri();
  $params['title'] = $entity->label;
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

```

The problem is that `$entity->toUrl()->getUri()` gives an error, "This URL has a Drupal route, so the canonical form is not a URI".

How do I get the URL from a URL object? Is this a problem because the entity hasn't been created yet, and the route hasn't been assigned?

# Answer
The URL object is there, you're just calling it wrong.

The code for this is a little complicated:

```
  $path = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
  $params['message'] = $path;

```

For more info, see this issue.
> 1 votes

---
Tags: 8, entities, routes, emails
---


# Question
Title: How to send an email after a specific node field gets updated by an admin?
I need to send an email notification to the node editor (reviewer/moderator) when an admin changes a (custom) field.

I've added the list of editors as a field in node form.

The nodes will be created by users and unpublished by default.

The nodes will be assigned to editor for review by admin, the editor should be able to view records assigned to the editor.

When admin assigns a node to editor, the editor should be notified by email.

How can I notify editors when they are assigned a node by admin?

Rules requires data comparison, conditions to trigger action. But I need to trigger action when a particular field gets changed.

I would like to use Drupal hooks like `hook_node_update`, by that way we can get the email id of the editor (in my scenario) and notify the editor.

Programmatically where and how I use `hook_node_update()` to achieve this? Or can the Rules module be used? If so please explain in detail how to create a rule for this.

# Answer
Check notification email link my point is enough to post in comment box so i am posted here
> 0 votes

# Answer
Using the Rules module to answer your question seems to me like the most straight forward solution.

Here is a rule (in Rules export format), which does exactly what your question is about:

```
{ "rules_email_reviewer_after_admin_updates_custom_field" : {
    "LABEL" : "eMail reviewer after admin updates custom field",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-free-format-text" ],
          "value" : [ "node:field-free-format-text" ]
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_assigned_user" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "node:field-assigned-user:mail" ],
          "subject" : "Node with id=[node:nid] is waiting your review",
          "message" : "An administrator assigned the Node with id=[node:nid] to you, please review it.",
          "from" : [ "site:current-user:mail" ],
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "User [node:field-assigned-user:name] will be notified by eMail that you just assigned this node to that user (waiting review)." } }
    ]
  }
}

```

This rule is based on these assumptions:

* The admin who performs the change, is a user with role id = 3 (adapt to fit your needs).
* The field with machine name `field_free_format_text` is a single value field, and reflects the custom field that is changed (adapt the machine name to fit your needs, pick whatever type for this field that fits your needs).
* The field with machine name `field_assigned_user` is an entity reference field to a user entity, defined as required, and with a single value (adapt the machine name to fit your needs).

Some more details about the above rule:

* The Rules Actions will only be performed if a user with role "administrator" updates a node, and actually also updates the value of the `field_free_format_text` field.
* This Rule will perform these Rules Actions:
    + Send an eMail (1) **From** the eMail Id of the administrator (2) **To** the eMail Id of the user referenced via the `field_assigned_user` field, and (3) with an eMail **Body** which looks similar to this example: ***`An administrator assigned the Node with id=71 to you, please review it.`***
    + Show an informational message to the administrator, which looks similar to this example: ***`User Pierre.Vriens will be notified by eMail that you just assigned this node to that user (waiting review).`***
> 0 votes

---
Tags: 7, rules, hooks, nodes, notifications
---


# Question
Title: Multilingual content and single language admin interface
I want my site's content to be multi-lingual. I have a language switcher that can toggle between both the English and Spanish translations of a page. I want the administrative interface to always be in English, no matter whether you navigate to it from a Spanish or English translation of the page.

Here is my configuration at */admin/config/regional/language/detection*:

Here is my configuration at *user/1/edit*:

My admin interface is always in English, but now my content is also always in English, no matter if I toggle the page to Spanish.

I have tried many settings, including the settings in **Content language detection**.

What is the correct configuration to achieve this?

---

*/es/node/1*

*/admin/config/regional/language/detection/url*

*/admin/config/regional/language*

# Answer
On a fresh install, I could get it working that way:

In `admin/config/regional/language/detection`

* put *Account administration pages* on top of *Interface text language detection* an enable it of course.
* enable *URL* method as second choice
* enable *Content language detection* and put *URL* on top of detection methods.

In `user/1/edit` language settings :

* set *Administration pages language* with your preferred language

There are various issues on D.O about that, maybe this is the most relevant one : When content language detection is different from interface language detection, the detected language is not applied to the rendered content.

Apply these patches :

Empty caches :

* `$ drush cache-rebuild`

Language dropdown switcher and everything else seems now to be working fine !

An example of spanish content, strings passed through t() are translated, admin toolbar in english...

The same page edited: admin interface fully in english, but content shows the correct translation....
> 18 votes

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


# Question
Title: My submit function for the node form doesn't execute
I need to add my submit function to the node insert/edit form.

Here's my code.

```
function yrv_event_trainer_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    if (in_array($form_id, ['node_veranstaltung_edit_form', 'node_veranstaltung_form'])){
        // Here we're adding our submit function before standard one.
        array_unshift($form['#submit'], 'yrv_event_trainer_submit');
    }
}

function yrv_event_trainer_submit(&$form, FormStateInterface $form_state){
// Here's code inside my submit function
}

```

But when I'm pressing the "Save and publish" button on the form, this submit function doesn't execute.

For example, I can't debug it having set a breakpoint inside the submit function.

But the array $form\['#submit'\] has my submit function.

Could you clarify me, what can be a reason of the problem ?

# Answer
> 2 votes
In node forms the submit callbacks from #submit are not executed. Instead, there are executed submit from #submit property of submit form element. You should add the submit in this way:

```
$form['actions'][$action]['#submit'][] = 'yrv_event_trainer_submit';

```

Here is an example too.

---
Tags: 8, forms
---


# Question
Title: Which hook to use to give a user a role after purchasing something in Commerce 2?
I made a site that sells services in Commerce 2. I want to hide access to the "Orders" and "Payment info" pages until a user purchases the first product.

To do this, I created a role, **Paid**, for users who have purchased something. This role has permission to view orders and so forth.

Which hook should I use to give the user the **Paid** role after making a purchase?

# Answer
In Drupal 8 Commerce is using Event dispatcher instead of hooks.

In this case, you should subscribe into the event named **commerce\_order.order.assign**, the hook invoked then a order is assigned to a user. In this moment you can code to grant the role to the user. You can see an example of how commerce\_log submodule from commerce used this event here.

If you need, you have this tutorial which tells you how to subscribe to a event from event dispatcher.
> 3 votes

---
Tags: 8, commerce
---


# Question
Title: How to configure access to courses for teachers and students?
In my site I have teachers and students. The student can subscribe to max 3 courses.

I created cTypes:

* Modules (which contains the actual information itself) and
* Course (which contains a reference to the module)

I create rules:

* The moment the student is subscribing to a module I create a instance of Course. I set a field course.status to active. (list integer)
* When the student is ending the course the field course.status is going to deactive.

Questions:

1. Which access module helps me to organize the student to denied access to the module while course.status is deactive?
2. Which access module helps me to organize teachers to see information only from students who followed or is following his course?

Everything should be organized by itself or by rules.

I looked into a custom ruleset with the help of vbo's. I looked into Organic groups and I looked into workbench access and I do not know what to choose. How to keep it simple and effective...

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

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

# Sample configuration

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

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

```

### Group Types

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

* Class.
* Customers.
* Project.

### Group Roles

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

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

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

On top of the group specific roles, there are also *Special Global Roles*: These are the special (hardcoded) roles named **Outsider** (= a signed in user that did not join a group) and **Member** (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role **Anonymous** is related to a user that is not signed.

### Groups

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

Examples of groups:

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

### Permissions

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

# Comparison with the Organic groups module

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

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

# Resources

# Integration with various modules

The Group module integrates with various other (popular) modules, including:

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

# Addressing your specific questions

> Which access module helps me to organize the student to denied access to the module while course.status is deactive?

Probably the easiest implementation of this, is to use the Rules module to create an appropriate "Group Membership" entity, which is what it takes to grant a user access to a Group. And assuming you have something in place that allows you to create a view of all students (users) that at some point should receive access to some course, you could use the Views Rules to create such entity for each user in such views result, and thereby using some Rules Event(s) / Condition(s) related to the update of course.status from deactive to something like active.

> Which access module helps me to organize teachers to see information only from students who followed or is following his course?

This is by design of the Group module (just a matter of appropriate configuration of the Group module).

**PS**: this answer applies to either D7 or D8.
> 2 votes

---
Tags: users
---


# Question
Title: Page template for specific path: page--about.html.twig
I have a page with the path `/about` that I would like to have a different page layout from the rest of the site.

I have created `page.html.twig` as my general page template, and `page--about.html.twig` as the template for this specific page. Both files are in the `/templates` directory of my theme. However, only the general template is getting used.

Yes, I have cleared the cache.

Appreciate any help!

James

# Answer
> 3 votes
You don't say if /about is a different content type or just a node.

If it's a node, you need to use the format:

page--node--1.html.twig

Replace 1 with the about page node id. See the d.o. page for reference info.

If you are trying to have a template for an about content type. You need to add code to your theme like this:

```
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
  }
}

```

See this d.o page for more info.

---
Tags: theming, 8
---


# Question
Title: How to check with Rules if a new element has been added to a list in a node?
I'm using the Rules module and I would like to make a rule to check wheter a new element has been added to a list in a node.

First I have tried "List Count comparison" but it can only compare a list to an integer, then I have tried with a custom php code condition but I have troubles with getting the right data. i don't understand if i'm missing something and there is a simple way or it can be done only with custom php code (in which case i'd like to know how to correctly do it, it's worth telling that the list is an entity reference)

This is the PHP code i have tried. The event is "After the update of an existing content of type Q&A", so I have `$node` and `$node_unchanged` available. The field is called field\_lista\_gestori and contains a list of users.

```
$gestoriCount=count($node->field_lista_gestori)>count($node_unchanged->field_lista_gestori);
return $gestoriCount;

```

But then I have discovered that field\_lista\_gestori just contains a number (which I think is the reference ID) and I haven't made any other attempts after this.

# Answer
You're counting the wrong thing...item data is a bit further down the rabbit hole (inside the language array):

```
$count_new = count($node->field_lista_gestori[$node->language]);
$count_orig = count($node_unchanged->field_lista_gestori[$node->language]);

```
> 1 votes

# Answer
Sure you can do this "without custom code" (and more important: without the need to enable the dangerous PHP filter ...). Read on for more details about how to get this to work ... and not only to discover new items added to the list (as in your question), but also to discover items removed from the list.

To process a multi-value field with Rules, I think you should use a completed different approach, which is related to the Rules Condition "List contains item" (and the negations of it).

Have a look at this rules example (in Rules export format), which processes a multi-value field also, in my case it is a list of eMail Ids (replace "eMail ID" by whatever matches your case):

```
{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-email-addresses" ] },
          "ITEM" : { "previous_email_id" : "Previous eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node:field-email-addresses" ],
                      "item" : [ "previous-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [previous-email-id:value] was removed from the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

If you just replace the machine name "`field-email-addresses`" by the machine name of your field (prior to import), you should be able to experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

Here is a sample of the messages I get when I update an article, and while doing so I add 1 more eMail ID and at the same time I remove an existing eMail Id:

```
Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

```

So the clue to make this work is:

1. first iterate over all field values of your field of the ***unchanged node*** (to find the removed values).
2. then also iterate over all field values of your field of the ***changed node*** (to find the inserted values).

Note: As an alternative to using the Conditional Rules module (which is required for this rule to work), you can also rework the relevant part of my Rules example into performing equivalent Rules Component. For more details on using Rules Components instead of Conditional Rules, refer to the answer to "What's the alternative to using the Conditional Rules module?".

PS: I'm assuming this question is about D7.
> 0 votes

---
Tags: nodes, rules
---


title: Render menu twice

text:
# Question
Title: Render menu twice
I'm looking for a possibility of rendering the same menu twice, once on the regular place, and another for mobile on a completely different place in my layout, with a completely different structure.

I was looking at JavaScript, but would rather do it with PHP and Twig

# Answer
> 1 votes
1) Add the menu block a second time (@/admin/structure/block). Give it a specific machine name (eg. main\_menu\_mobile).

2) Create a second menu template (derived from menu.html.twig) and give it a specific name (eg. menu--main-mobile.html.twig).

3) In your theme, implement a new preprocess hook for blocks and assign another template to your menu:

```
function mytheme_preprocess_block(&$variables) {
  // Use another template for the main mobile menu.
  if ($variables['elements']['#id'] === 'main_menu_mobile') {
    $variables['content']['#theme'] = 'menu__main_mobile';
  }
}

```

# Answer
> 0 votes
I assume you have a custom page-template for your site. And you are using the block-system for rendering your regions. So you may have a region called header with your menu in it.

```
<div class="regular-menu">
  {{ page.header }}
</div>
<div class="mobile-menu">
  {{ page.header }}
</div>

```

let me know if I got your question correctly.

---
Tags: 8, routes
---


# Question
Title: Doing a post to create a node using Drupal services endpoint with Postman app
I got my endpoint setup and I'm able to to do a get request to return a bunch of nodes. But I'm having issues doing a POST to create a new node.

I see that I would first need to do a user login post as seen in other tutorials. I tried doing that with the following settings in postman, but I'm getting a blank response. What could I be doing wrong? I've enable user resources as seen below also.

# Answer
In that petition you are calling the path user.login, but in services is user/login, with a slash.

Also, maybe you are not preceding the path with the base name of your api (normally is /api). So the url should be /api/user/login. You can see the path in 'Edit' tab, in 'Path to endpoint' field.

I recommend you the module services tools which gives you a page where you can see the urls of the endpoints. This module contains a submodule called services\_definitions, enable it to have this page available.
> 1 votes

---
Tags: 7, services
---


# Question
Title: How to show/hide the prefix/suffix for fields?
Sometimes in theming I want to programmatically hide the prefix or suffix of numeric fields. How can I do so?

# Answer
When you look at the code of the numeric field formatter:

*NumericFormatterBase::viewElements*

```
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $settings = $this->getFieldSettings();

    foreach ($items as $delta => $item) {
      $output = $this->numberFormat($item->value);

      // Account for prefix and suffix.
      if ($this->getSetting('prefix_suffix')) {
        $prefixes = isset($settings['prefix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['prefix'])) : [''];
        $suffixes = isset($settings['suffix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['suffix'])) : [''];
        $prefix = (count($prefixes) > 1) ? $this->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0];
        $suffix = (count($suffixes) > 1) ? $this->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0];
        $output = $prefix . $output . $suffix;
      }
      // Output the raw value in a content attribute if the text of the HTML
      // element differs from the raw value (for example when a prefix is used).
      if (isset($item->_attributes) && $item->value != $output) {
        $item->_attributes += ['content' => $item->value];
      }

      $elements[$delta] = ['#markup' => $output];
    }

    return $elements;

```

You see three things, first this is fully configurable, so it has not to happen in the first place, second it's hard to change afterwards, because the field content and the prefix/suffix is concatenated into one string and third you can get the raw values without prefix/suffix from the items attribute `content`:

*field--field-number.html.twig*

```
<h3>Field raw values:</h3>
<ul>
  {% for item in items %}
    <li>{{ item.attributes.content }}</li>
  {% endfor %}
</ul>

```
> 4 votes

# Answer
***This answer is for Drupal 7 users and does not address the original question.***

The following is an example of what someone might add to their theme template.php file. Use Devel to find your field values.

```
if(some value = true){
    hide($variables['content']['field_name']..['#prefix']);
    hide($variables['content']['field_name']..['#suffix']);
    $variables['field_without_prefix_or_suffix'] =  render($variables['content']['field_name']);
}

```

And then just render the variable within your TPL file.

```
print $field_without_prefix_or_suffix;

```
> 1 votes

---
Tags: 8, nodes, entities
---


title: Add an input field to the product view

text:
# Question
Title: Add an input field to the product view
How do I add input fields to the commerce products (in Drupal 8) in order to save the information of those fields when the user purchases the product?

For example, if I want to sell t-shirts I would like an extra field to add some text and print it in the t-shirt.

# Answer
> 5 votes
Instead of adding the field to the product, consider adding the field to order items.

Then make it available in 'manage form display' -\> 'add to cart'.

in Drupal 7 this functionality was provided by Commerce customizable Products module, now it has been moved into Commerce 2.x itself.

# Answer
> 1 votes
You can add fields to products by following this path: Commerce -\> Configuration -\> Product Types (`/admin/commerce/config/product-types`). Then choose **Manage Fields** for the relevant product type.

---
Tags: 8, commerce
---


# Question
Title: Webform doesn't send email using MIME Mail
My webform forms doesn't send the email if I set `Site-wide default MailSystemInterface class` to MimeMailSystem.

It works fine if I set `Site-wide default MailSystemInterface class` to `DefaultMailSystem`

Take a look at my captures:

I was working fine until yesterday, then all the sudden this problem is happening.

How can I trace this?

# Answer
I had a similar, slightly different, issue after updating from webform version 7.x.3.25 to 7.x.3.27

**WORKED FOR ME:**

Upgrade to webform 7.x.4-branch
> 0 votes

---
Tags: emails
---


# Question
Title: Auto add nodes on save to a queue using entityqueue
I am using entity queue module, Created a queue with a name *ABC*.

I want to add nodes automatically to this queue for a specific content type while creating new nodes.

Is there a way to do this?

# Answer
Try Auto Entityqueue module to Automatically add entities to entityqueues.
> 2 votes

# Answer
Create a custom rule which calls a function like

```
/**
* Add a node to a subqueue
*/
function abc_queue_add_node_to_entityqueue($subqueue, $node){
  $existing_nodes = abc_entity_queue_get_subqeueue_nodes($subqueue);
  if (!in_array($node->nid, $existing_nodes)) {
    $subqueue->eq_node[LANGUAGE_NONE][] = array('target_id' => $node->nid);
    entityqueue_subqueue_save($subqueue);
  }
}

```
> 0 votes

---
Tags: 8, queue
---


# Question
Title: How to inject code into node body after x paragraph
Trying to figure out if there is a way to inject code after the first or second paragraph on a node.

More specifically I am trying to inject an Adsense ad.

So far I haven't been able to find a solution or module that will do this.

Can anyone help?

I am not using paragraphs module. Just looking how to inject code right after the third or fourth

tags on the body of the node.

# Answer
> 0 votes
Well, one way to do this would be to modify the twig template that is outputting the paragraphs (on the node).

You could loop the paragraphs render array `{{ content.field_foo }}`:

```
{% for i in content.field_foo %}
  {{ content.field_foo[i] }}

  {% if i == 1 %}
    // print your output
  {% endif %}
{% endfor %}

```

`1` will be your second item, as the count starts at 0. This is just some rough untested pseudocode. But the idea is to loop over and print each item in the render array one by one, and inject the code at certain counts.

**edit**: This answer is for if you are using the Paragraphs module, which at the time of this answer is not clear from your original question.

---
Tags: 8, theming
---


title: Deleted 'Glossary View' by mistake D8

text:
# Question
Title: Deleted 'Glossary View' by mistake D8
Is there any way I can get back the default **Glossary View** which I deleted by mistake?

# Answer
> 2 votes
If you are exporting and importing your configuration, you can simply re-import config from your last export. If you are not doing that already, you should definitely learn how to do so.

If you don't have the view exported, one way to get it back is to create another Drupal 8 site in your local development environment and then go to the config single export page (`/admin/config/development/configuration/single/export`) and choose **Configuration type** View and **Configuration name** Glossary.

Then go to your other site and choose "Import" and import the code.

For reference, here is my export (Drupal 8.4-rc2):

```
uuid: 350860b2-753f-4774-b504-5cc14b62c099
langcode: en
status: false
dependencies:
  config:
    - system.menu.main
  module:
    - node
    - user
_core:
  default_config_hash: '-pCFOVfbt__jaohFffTLnVavh4OBC6CjREAnchiRomQ'
id: glossary
label: Glossary
module: node
description: 'All content, by letter.'
tag: default
base_table: node_field_data
base_field: nid
core: '8'
display:
  default:
    id: default
    display_title: Master
    display_plugin: default
    position: 0
    display_options:
      query:
        type: views_query
        options:
          query_comment: ''
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_tags: {  }
      use_ajax: true
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: mini
        options:
          items_per_page: 36
          offset: 0
          id: 0
          total_pages: 0
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: ‹‹
            next: ››
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: Title
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: title
        name:
          id: name
          table: users_field_data
          field: name
          label: 投稿者
          relationship: uid
          plugin_id: field
          type: user_name
          group_type: group
          admin_label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: user
          entity_field: name
        changed:
          id: changed
          table: node_field_data
          field: changed
          label: 前回の更新
          type: timestamp
          settings:
            date_format: long
            custom_date_format: ''
            timezone: ''
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: changed
      arguments:
        title:
          id: title
          table: node_field_data
          field: title
          default_action: default
          exception:
            title_enable: true
          default_argument_type: fixed
          default_argument_options:
            argument: a
          summary:
            format: default_summary
          specify_validation: true
          glossary: true
          limit: 1
          case: upper
          path_case: lower
          transform_dash: false
          plugin_id: string
          relationship: none
          group_type: group
          admin_label: ''
          title_enable: false
          title: ''
          default_argument_skip_url: false
          summary_options: {  }
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          entity_type: node
          entity_field: title
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          plugin_id: standard
          relationship: none
          group_type: group
          admin_label: author
          required: false
      style:
        type: table
        options:
          columns:
            title: title
            name: name
            changed: changed
          default: title
          info:
            title:
              sortable: true
              separator: ''
            name:
              sortable: true
              separator: ''
            changed:
              sortable: true
              separator: ''
          override: true
          sticky: false
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
          order: asc
          summary: ''
          empty_table: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      header: {  }
      footer: {  }
      empty: {  }
      sorts: {  }
      filters:
        langcode:
          id: langcode
          table: node_field_data
          field: langcode
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value:
            '***LANGUAGE_language_content***': '***LANGUAGE_language_content***'
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: language
          entity_type: node
          entity_field: langcode
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  attachment_1:
    id: attachment_1
    display_title: 添付
    display_plugin: attachment
    position: 2
    display_options:
      query:
        type: views_query
        options: {  }
      pager:
        type: none
        options:
          offset: 0
          items_per_page: 0
      defaults:
        arguments: false
      arguments:
        title:
          id: title
          table: node_field_data
          field: title
          default_action: summary
          exception:
            title_enable: true
          default_argument_type: fixed
          default_argument_options:
            argument: a
          summary:
            format: unformatted_summary
          summary_options:
            items_per_page: 25
            inline: true
            separator: ' | '
          specify_validation: true
          glossary: true
          limit: 1
          case: upper
          path_case: lower
          transform_dash: false
          plugin_id: string
          relationship: none
          group_type: group
          admin_label: ''
          title_enable: false
          title: ''
          default_argument_skip_url: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          entity_type: node
          entity_field: title
      displays:
        default: default
        page_1: page_1
      inherit_arguments: false
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  page_1:
    id: page_1
    display_title: Page
    display_plugin: page
    position: 1
    display_options:
      query:
        type: views_query
        options: {  }
      path: glossary
      menu:
        type: normal
        title: Glossary
        weight: 0
        menu_name: main
        parent: ''
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }

```

---
Tags: views
---


# Question
Title: How to update fields of a new node created using Rules?
I have created a content type called Tasks that helps me track things I need to do on my site. I am trying to create a rule that when some content is published, a new task item is created reminding me to do some follow up work.

I created a rule that when the new content is published, a new task item is created. I did this by adding Create a new entity to the Actions section. I can give the item a title and set the author, but I can't figure out how to update the other fields in the new Tasks item.

Can this be done using rules or do I have to write PHP code to accomplish this?

# Answer
> 1 votes
In Rules you have to add those fields as conditions - "Entity has x,y,z field" - then they will become available for your actions

# Answer
> 1 votes
To "*update the other fields in the new Tasks item*" (as in your question), you can perfectly do this by extending the current list of Rules Actions you already have to "Create an entity" (of type *node*).

Here is a typical set/sequence of Rules Actions to get the job done, say for also updating 3 other fields of the node to be created:

* Create a new entity (Entity type = Node), which is the Rules Action you already must have in place to create your *Task*.
* Set a data value for `field1` of the created entity (pick whatever value for it that fits).
* Set a data value for `field2` of the created entity (pick whatever value for it that fits).
* Set a data value for `field3` of the created entity (pick whatever value for it that fits).
* Save the entity (make sure to use "*Force saving immediately*").

For an example of a rule (in Rules export format) with a similar set of Rules Actions (for only 1 such field), refer to my answer to "Set value on newly created node using Rules".

Obviously, for this there is no need for any custom PHP code.

---
Tags: 7, rules, entities
---


title: Enable SSL for whole Drupal 8 site

text:
# Question
Title: Enable SSL for whole Drupal 8 site
I'm running a Drupal 8 site behind a nginx webserver. All http request are redirected to https. My problem is that rss links on that site are http links only.

With Drupal 7 by setting the base\_url all links are shown as https links. In Drupal 8 this option is missing. How can I set the whole site to https? Is there a config option for setttings.php?

# Answer
> 1 votes
Depending on how the RSS links are rendered, I would suggest calling them over with a protocol-relative URL such as:

```
//domain.com/rss-feed....

```

This will force the information to be sent over based on the way the page was rendered. If the page was rendered using https:// it will use https:// in place of '//'

# Answer
> -1 votes
To Enable SSL Certificate on Drupal, Write the following line of code in your .htaccess file.

```
RewriteEngine on

# Redirect to HTTPS

RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

---
Tags: 8, feeds, ssl
---


# Question
Title: How to properly attach a library to CheckoutPaneForm
I'm attempting to attach a library to a `CommerceCheckoutPane` plugin. I first started with using `$pane_form['#attached']['library'][] = 'commerce_paypal/express-checkout';`. There were some errors in my `commerce_paypal.libraries.yml` file but once those were resolved the libaries still don't appear to be loaded.

Right now, my setup looks like:

**commerce\_paypal.libraries.yml**:

```
paypal.checkout:
  remote: https://www.paypalobjects.com/api/checkout.js
  license:
    name: MIT
    gpl-compatible: true
  js:
    https://www.paypalobjects.com/api/checkout.js
express-checkout:
  js:
    js/paypal_ec.js
  dependencies:
    - commerce_paypal/paypal.checkout

```

**Drupal\commerce\_paypal\Plugin\Commerce\CheckoutPane\ExpressCheckout**:

```
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
  $pane_form['#theme'] = 'commerce_paypal_express_checkout';

  return $pane_form;
}

```

**commerce-paypal-express-checkout.html.twig**

```
{{ attach_library('commerce_paypal/express-checkout') }}

asdfas

```

**js/paypal\_ec.js**:

```
console.log('here');

```

When I place the pane form I see `asdfas` but the JS is not added. I've checked the source, no sign of paypal\_ec.js.

# Answer
> 1 votes
As usual, I was messing something up. JS libraries need `: {}`. Updating **commerce\_paypal.libraries.yml** to this solves it:

```
paypal.checkout:
  remote: https://www.paypalobjects.com/api/checkout.js
  license:
    name: MIT
    gpl-compatible: true
  js:
    https://www.paypalobjects.com/api/checkout.js: {}
express-checkout:
  js:
    js/paypal_ec.js: {}
  dependencies:
    - commerce_paypal/paypal.checkout

```

---
Tags: 8, theming
---


title: Config entity form fails to load entity

text:
# Question
Title: Config entity form fails to load entity
I have a custom config entity modelled closely on the example documentation and example module. The example module works fine on my site, my code does not, and I can't see the difference.

**What works**

* Show an empty list of config entities with an add button.
* Add a config entity and check it exists via "drush cget".

**What fails**

1. In my edit settings form (extends EntityForm), $this-\>entity has null/default values exactly as if I were adding a new entry. It does not load the actual entity. It does not perform validation (if I pass a URL /admin/config/content/rrssb/BADPARAM that doesn't map to an existing entity I still see a page, whereas if I do the same test with the example code, I get a 403 error).
2. In my listing page (extends ConfigEntityListBuilder), if an entity exists I get an error - for some reason the list builder fails to pass the id (machine name) from the entity when building the route.

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("button\_set") to generate a URL for route "entity.rrssb\_button\_set.edit\_form". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 180 of core/lib/Drupal/Core/Routing/UrlGenerator.php).

**Details**

```
/**
 * Defines the RRSSB button set entity.
 *
 * @ConfigEntityType(
 *   id = "rrssb_button_set",
 *   label = @Translation("RRSSB Button Set"),
 *   handlers = {
 *     "list_builder" = "Drupal\rrssb\RRSSBListBuilder",
 *     "form" = {
 *       "add" = "Drupal\rrssb\Form\RRSSBSettingsForm",
 *       "edit" = "Drupal\rrssb\Form\RRSSBSettingsForm",
 *       "delete" = "Drupal\rrssb\Form\RRSSBDeleteForm",
 *     }
 *   },
 *   config_prefix = "button_set",
 *   admin_permission = "administer rrssb",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "edit-form" = "/admin/config/content/rrssb/{button_set}",
 *     "delete-form" = "/admin/config/content/rrssb/{button_set}/delete",
 *     "collection" = "/admin/config/content/rrssb"
 *   }
 * )
 */

```

rrssb.routing.yml

```
entity.rrssb_button_set.collection:
  path: '/admin/config/content/rrssb'
  defaults:
    _entity_list: 'rrssb_button_set'
    _title: 'Ridiculously Responsive Social Sharing Buttons'
  requirements:
    _permission: 'administer rrssb'

entity.rrssb_button_set.add_form:
  path: '/admin/config/content/rrssb/add'
  defaults:
    _entity_form: 'rrssb_button_set.add'
    _title: 'Add RRSSB Button Set'
  requirements:
    _permission: 'administer rrssb'

entity.rrssb_button_set.edit_form:
  path: '/admin/config/content/rrssb/{button_set}'
  defaults:
    _entity_form: 'rrssb_button_set.edit'
    _title: 'Edit RRSSB Button Set'
  requirements:
    _permission: 'administer rrssb'

entity.rrssb_button_set.delete_form:
  path: '/admin/config/content/rrssb/{button_set}/delete'
  defaults:
    _entity_form: 'rrssb_button_set.delete'
    _title: 'Delete RRSSB Button Set'
  requirements:
    _permission: 'administer rrssb'

```

**Help requested**

Please can an expert suggest what I'm likely to be missing, or at least help me understand where to look?

In particular, what mechanism (Drupal class/code file) loads the config entry or generates a 403 if it is not found?

The relevant code in my own module spans several files, so I've not pasted it all here, but could upload specific snippets if asked.

# Answer
Looks like the id key isn’t matching the router parameter defined in the routing file. It should be either `button_set` or `rrssb_button_set`, depending on which one is right. Get that fixed and clear the cache and it should work.
> 0 votes

---
Tags: 8, forms, entities
---


title: Sender name in "send HTML mail" rule

text:
# Question
Title: Sender name in "send HTML mail" rule
I have a local site I am testing. I have PhPMailer installed which works fine to send plain text email with the Sender name populated properly. However when I installed MimeMail and try to use the same rule, except using action send HTML mail, the Sender name no longer appears. Any help would be great.

```
{ "rules_entityform_client_confirmation_email" : {
"LABEL" : "Entityform Client Confirmation Email",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

```

# Answer
> 1 votes
Try this variation of your rule (using the rules UI to import it in your site):

```
{ "rules_entityform_client_confirmation_email_pv" : {
"LABEL" : "Entityform Client Confirmation Email PV",
"PLUGIN" : "rule",
"OWNER" : "rules",
"TAGS" : [ "entity_rules_entityform_submission" ],
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "entity" : { "label" : "Entity", "type" : "entityform" },
  "continue" : { "label" : "Continue Rules", "type" : "boolean" }
},
"IF" : [
  { "user_has_role" : { "account" : [ "entity:user" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Email to: [entity:user:mail]\r\nHi [entity:user],\r\nThanks for creating a new project\r\n" } },
  { "mimemail" : {
      "USING" : {
        "key" : [ "entity:entityform-id" ],
        "to" : [ "entity:user:mail" ],
        "from_name" : "[site:name]",
        "from_mail" : "somebody@example.com",
        "subject" : "New Project Created",
        "body" : "Hi [entity:user],\r\nThanks for creating a new project",
        "plaintext" : "Hi [entity:user],\r\nThanks for creating a new project",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
],
"PROVIDES VARIABLES" : [ "continue" ]
}
}

```

The only difference with your exported rule is the line with `from_mail` that is added (and a slightly different machine name of your rule). Adapt the eMail Id I used to fit your needs.

---
Tags: 7, rules, mimemail
---


# Question
Title: Views - Filter "Content: Authored by" to show only content by anonymous users
When filtering content in Views using the filter **Content: Authored by**, you get these choices:

For the username, I typed "Anonymous", which gave me the UID of 0.

However, when I click **Apply (All Displays)**, I get this error:

`There are no entities matching "(0)".`

Is there a way to filter a view in Drupal 8 to only show content posted by anonymous users?

# Answer
Filter by User ID, is equal to 0.
> 3 votes

---
Tags: 8, views
---