# Question
Title: Giving a default value to a password element in D7 form API?
I wrote a custom feeds fetcher class that does an authentication call before it gets the feed. In its settings, I have username and password fields in the form. I tried to set the field `#type` to `password`, but it seemed not to use the `#default_value` element, thus obliterating the saved password when you hit the 'save' button.

This maintains the password, but shows it in plaintext:

```
$form['password'] = array(
  '#type' => 'textfield',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

```

This shows dots for the password, but does not populate the field using the `#default_value`, causing you to have to enter the password any time you want to change and save any value on the form:

```
$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

```

I need to be able to have the user enter a password and have it stay no matter what other values they change on the form and save. Does this preclude me from using the `password` field type, since it appears not to use the `#default_value` element?

# Answer
You can try to add your default value directly with `#attributes` option just like that :

```
$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#attributes' => array('value' => $this->config['password']),
);

```

After I'm not sure if you will be able to get that value on `validate` and `submit`callback, you should check.
> 3 votes

# Answer
This is a pretty common use-case, but you wouldn't want to re-expose the password to the client at any point by setting a password field's default value. So either the user can change a password by updating the password input, or leave it unchanged by leaving the field blank.

To implement this in code, you can add another submit handler to your form:

```
$form['password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#description' => t(''),
);

$form['#submit'] = array_merge(array('my_default_password'), (array) $form['#submit']);

```

And in this handler, put the password back in:

```
function my_default_password($form, &$form_state) {
    if (empty($form_state['values']['password'])) {
        $form_state['values']['password'] = variable_get('the_password');
    }
}

```

This way you don't have to expose the existing password to the user, which wouldn't be considered a good security practice, but you also get the expected workflow.

Note that I assumed the default password is stored in 'the\_password' variable, but your code likely would have it elsewhere.
> 3 votes

# Answer
A password field can't have a default value, that makes no sense. It would be written in plaintext in the attribute so all that password specific stuff would be pointless (\*, copy-protection, ...).

Either use a normal textfield with a default value (that's what most of those forms do I think) or leave it empty, add some special code to only overwrite the existing value if not empty and add a corresponding description.
> 2 votes

# Answer
I was able to accomplish this with validation and hook\_update\_N. In my case, I had a settings page with a few form elements, one of them being a password field. If they filled out other settings, but not the password and clicked Save, it would set the password to a blank string.

In my case, I validated the form like this in `mymodule.module`:

```
<?php

function mymodule_form_callback($form, &$form_state) {
  $form = array();
  // code for other elements here...
  $form['my_password_field'] = array(
    '#type' => 'password_confirm',
    '#title' => t('Enter password'),
  );
  return $form;
}

function mymodule_form_callback_validate($form, &$form_state) {
  if (empty($form_state['values']['my_password_field'])) {
    $form_state['values']['my_password_field'] = variable_get('my_password_field');
  }
}

```

Then created a default value in `mymodule.install`:

```
<?php

function mymodule_update_7001() {
  variable_set('my_password_field', 'Jabron1jabroni');
}

```

To get this default to be set initially, you have to run Drupal updates in the UI or with `drush updb -y` if you use Drush.
> 0 votes

---
Tags: 7, forms, users
---


# Question
Title: Render array in controller response without surrounding theme
I have custom controller in which I would like to take a render array (as such returned by `EntityViewBuilderInterface::view`) and return it as HTML without anything additional page theming wrapping it. I'm using this with a custom ajax call and would like to fetch html fragments to dynamically render on the page. Is this possible?

# Answer
There are two ways.

One is, you render it yourself into a string, then build a Response object with it and return it. Drupal won't alter/touch a Response object and return its content as-is.

Second, since you mention ajax, Drupal actually has a built-in mechanism for its own ajax command system. If you pass ?\_wrapper\_format=drupal\_ajax to the request, it will automatically transform it into ajax commands that will take care of not only the html content but also contained assets like css/js and drupal settings that are required to correctly display that HTML.

I don't really know in detail how the JS part works, but it basically all happens in ajax.js, for example in Drupal.Ajax.success, which then triggers the commands defined in Drupal.AjaxCommands (which can be extended), so you could write a more or less generic implementation of dealing with that response.
> 5 votes

---
Tags: theming, 8, ajax
---


# Question
Title: How to re-create a notifications 'inbox' similar to the one here at stackexchange?
I'm looking for a simple way to let users know when new content (comments mainly) has been submitted to nodes they published or commented on and groups they are members of.
Is it possible to groupe that new content within a view ?
The ideal scenario would be to have something that works like stackexchange's inbox in the upper left side of the nav bar with the badge showing the number of new notifications.

I'm using drupal 7 with basic content types and organic groups 7.x-2.9

Any suggestions are welcome.

# Answer
You could use the Menu Badges module for such notifications, which you can add to any **menu item** and/or **menu tab** of your choice. In your case something like "***New comments***" seems like one, out of a few, appropriate menu item (or menu tab).

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, by using this integration you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

However, there is a small caveat: if you really want the actual number (shown in the red circle) to be accurate, make sure you have some field in your view that will actually correspond to the "`new`" part of your question. To better explain this: have a look at the "`tracker`" view (disabled by default), which has the field "***Content:Has new content***" (or variation: "***Content:Has new comments***"). This is a perfect field to use if you want to use Menu Badges to get notified whenever there is new content (or variation: new comments).

If you don't have such "new" indicator, then you basically have 2 variations to get around that:

### Video tutorials:
> 2 votes

---
Tags: 7, notifications
---


# Question
Title: Does moving to PHP 7 require any system change to be done with Drush or from the GUI?
After moving a Drupal site from PHP 5.6 to 7.13, is it better to change something from the GUI or from Drush?

# Answer
> 3 votes
No, there's no action that needs to be taken through the GUI or drush when you change PHP versions.

# Answer
> 3 votes
It is plausible, though very unlikely, that there is something in the compiled container that has a dependency on the PHP version. If you switch PHP versions, it is safest to to a

```
$ drush cr

```

to force a rebuild.

To my knowledge (and based on IRC conversations with people who know **way** more than I do), there is nothing in core that would require this, but it is possible that there is a contrib module that introduces a service that would require this.

---
Tags: 8, drush
---


# Question
Title: After moving to a new server, the site doesn't load the CSS styles
I moved two sites to a different hosting provider; the first works fine with a custom theme, while the second doesn't load the Bartik CSS styles.

Both sites has been moved via the user root; almost all of their directory permissions are 755 (user: root, group: root). The temporary directory is /tmp.

Manually clearing the cache doesn't make any difference.

>

How can I resolve this issue?

# Answer
> 4 votes
This sometime happens if Apache server is not able to write files or directory.

Since you mentioned you moved using root user, Apache server may not be running on root user.

To further clarify this: If the inodes of both sites have the same permissions, ownership, grouping, but only one works, it's because it doesn't have CSS and JS aggregation on (a thing that requires an **Apache user** --- that is, `www-data` ownership and grouping, that you should apply).

You could either turn off CSS and JS aggregation for the non working site (and then it'll work), or make sure you give both sites **such** ownership and grouping if you want both of them to work properly with CSS JS aggeregation.

If at least for now you just want to turn off CSS JS aggregation, read here how to do so, but for troubleshooting this (and take care of the root cause), read the following (you might want to precede it with this piece of data on the aforementioned Apache user):

1. First check on which user apache server is running. Finding out what user Apache is running as?
2. Change your *tmp* folder and *files* folder ownership to that user so that it is writable by Apache.Giving ownership of the directory to the apache user?
3. Make sure you have *tmp* directory created in your files folder and is writable by Apache server. You can define it your Configuration \> File System

---
Tags: 8
---


# Question
Title: Migrating a Drupal 6 site to Drupal 7 can I copy the D6 database as a local source?
I am trying to migrate a small D6 site over to D7 and the Migrate/D2D modules look like they will handle most of my content. Is there any way to simply copy the D6 database over to the D7 machine and use it as a local source to migrate into the D7 database? Or, do I need to specify a path and access credentials to the mysql server on the active D6 website? Thanks.

# Answer
Yes, you can source the migration from a copy of the D6 database running on the same database server as the D7 site's database. Be aware: the migrate D2D wizard will ask you for a "File prefix". In the "File prefix" field, you must specify a path to the uploaded files directory of the D6 site. Those could be a local copy also.

If in addition, you are asking how to copy a MySQL database from one server to another, that may be out-of-scope for Drupal Answers. There are tons of resources on the Internet for that—your own hosting provider may provide tools to do this. But I won't stop someone else from answering if they please. Apologies if that is not an aspect of the question posed.
> 0 votes

---
Tags: migrations
---


title: Drupal Migration Date format

text:
# Question
Title: Drupal Migration Date format
On the old server in the database my date column has rows in this format: **2014-10-15 13:00:00**

When i do $this-\>addFieldMapping('field\_date\_time', 'date'); it imports, but is off by 12 hours.

I've tried various ways to convert it in a prepareRow function but with no luck. Am I missing something?

# Answer
> 0 votes
Sorta embarrassing, but adding the solution to my problem, just in case anyone else runs into this. If you configure the date field in the content type. There is a drop down of time zone handling. Ours got set incorrectly somewhere down the line. After fixing that, and rerunning the migration everything worked as intended.

---
Tags: 7, entities, datetime, migrations
---


title: Redirect to /user upon login

text:
# Question
Title: Redirect to /user upon login
I can't figure out why users are redirected to http://example.org/user (the domain is just an example) when they log in. I don't see a rule anywhere. I have written rules to redirect somewhere else upon login, and the rules do not work. I suspect the Logintoboggan or the Drupal Commerce, but I can't find any settings that would cause this. I don't have any other redirect modules installed.

Why are user redirected to their user profile after they log in?

# Answer
> 0 votes
The redirect is specified in the login form forst\_state array under the redirect key, that's why. You can change that by altering the user login form.

---
Tags: users, redirection
---


# Question
Title: How to remove image script if it has no image?
I created a block using views. The fields has image, title and body.

While the article has no image, it still render out the image script and it make a space before the title.

How do it make the image script disappear if there is no article in its.

# Answer
> 3 votes
Go to **Image field configuration**:

Click on **No results behavior** section.

You will get the option to hide.

---
Tags: views
---


title: How to add fields to file entities?

text:
# Question
Title: How to add fields to file entities?
In Drupal 7, the Media module allowed you to add fields on a file entity. I don't see this ability out of the box in Drupal 8.

How can I add fields to file entities in Drupal 8?

# Answer
In D8 the module File Entity provides this feature, same as in D7. It was required by Media, so you probably installed it without noticing in D7.

The new Media package for D8 doesn't use this anymore. Instead it uses a new media entity for the extra information. There is work going on to put the media entity in core for 8.3:

https://www.drupal.org/node/2825215
> 3 votes

---
Tags: 8, entities, files
---


# Question
Title: How do I migrate the file attachments field from a content type?
My Drupal 6 site has different content types, and there is a *File Attachments* field added to the content types. While migrating to Drupal 8.1, this field is not getting migrated, but the attached file is present in the files directory. While doing the migration, it is displayed that the "upload" module in Drupal 6 has migration path, yet it is not migrated.

How can I migrate the file attachment field to Drupal 8?

# Answer
In Drupal 6, file attachments are considered enabled if the upload-module is enabled, and the variable 'upload\_\[content\_type\]' is true **or not set**. The latter could be the cause that your attachment fields are not being migrated.

There is an open bug report for this scenario, including a patch, at https://www.drupal.org/node/2829274
> 1 votes

# Answer
This is using the full upgrade process (/upgrade UI or drush migrate-upgrade command), I assume? Did the migration create an 'upload' field on the relevant content types (even if it didn't populate it)? The question is whether the failure is at this point (creating the field), or in connecting it to the actual files when migrating the nodes.

You might want to open a bug report under the "migration system" component: https://www.drupal.org/node/add/project-issue/drupal
> 0 votes

---
Tags: 8, files, migrations
---


title: Issue Tracker for Open Atrium 2.0

text:
# Question
Title: Issue Tracker for Open Atrium 2.0
I just installed Open Atrium 2.0 and noticed, as many people have, that the Issue Tracker functionality is not included. I understand why they didn't want to include it in version 2: to make way for a better solution that fits in with Drupal Core.

However, this functionality is pretty killer for what I use Open Atrium for.

So, other than https://drupal.org/project/oa\_worktracker, are there other alternatives to implementing issue tracking within Open Atrium. I guess I'm unaware of a standard issue tracker for D7.

# Answer
> 1 votes
I dont know whats OA2 friendly but Case Tracker, and Project Management are both D7 friendly.

From the project page of Case Tracker:

> Actually, the 7.x-1.x-dev version has the content types for Project and Cases working without problems. The Notifications, Actions and View integration that needs to be tested.
>
> The development is active and we're working toward a release. Check out the 7.x-1.x branch and post your patches!

From the project page for Project Management:

> Project management software, allowing you to manage:
>
> Organizations, Teams, People, Projects, Tasks, Tickets, Timetrackings, Notes, Invoices, and Expenses. Each of these features is managed as a separate module within the suite.

# Answer
> 0 votes
This answer is long after the OP presumably moved on, but for posterity...

I'm using an issue tracker on an OA2 system. I didn't set it up, but I'd be very surprised if what we used wasn't standard stuff.

OA2 in this case uses the 'Task' content type for issue tracking, which is implemented by `oa_worktracker`, which I can see in the filesystem at `.../htdocs/profiles/openatrium/modules/apps/oa_worktracker`.

http://docs.openatrium.com/node/294 also shows the Tracker as part of OpenAtrium.

---
Tags: distributions
---


title: Rewrite View field value

text:
# Question
Title: Rewrite View field value
I have a Views table that simply shows a list of Entities.

Now at the moment, field 'status' just outputs the raw data 0 or 1.

I want this to be rewritten as 'Pending' or 'Approved' respectively.

I've looked at rewrite behaviour but this seems to be limited and my requirements out of the scope. Everywhere people say that adding PHP through the UI is bad practice.

So how do people normally deal with select boxes stored as integers, when displaying the data using Views?

(Maybe there is a hook to create a function in my module that will always rewrite this field wherever it displays in the Drupal system?)

# Answer
You could do this several ways, the easiest from a hook standpoint might be to use `views_pre_render()`, eg, something along the lines of...

```
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='THE_VIEW_YOU_ARE_LOOKING_FOR') {

     drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>'); // to see what you have to work with

     foreach($view->result as $r => $result) {
      if ($result->node_data_field_status_field_status_value) { // or whatever the $result field is you are looking to change from 0 or 1 to Pending or Approved
        $result->node_data_field_status_field_status_value='Approved';
      } else {
        $result->node_data_field_status_field_status_value='Pending';
      }
    }

  }

}

```
> 5 votes

# Answer
I had the same problem in a view of entityform submissions and I found that it is possible to change the results "0" or "1" of the field "*Entityform Submission: Draft*" in this way:

1) Select "Rewrite the output of this field" and insert 'Pending' in the text area
2) In "No results behavior" insert 'Approved' in the text area, check Count the number 0 as empty and check Hide rewriting if empty

I hope these configurations could help you!!
> 0 votes

# Answer
There is also a module that can help you achieve this. It's View conditional. With that module you can add conditional field like: if this field is equal to/not equal to/empty/not empty/greather than/contains ecc something, then write something, otherwise write something else.
> 0 votes

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


# Question
Title: Unique violation when trying to create a new Field Collection using Rules
When I try to create a new field collection for a node I just saved, I encounter following error:

> PDOException: SQLSTATE\[23505\]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "node\_pkey" DETAIL: Key (nid)=(47) already exists.:

However, if I try to create a node this way, it works fine, so I assume it's a bug in Field collection.

I don't know it it matters, but I'm using PostgreSQL 9.3 as my DB. Also, this issue might be related to the issue about Field Collection Item Duplicate with Rules, but I'm not sure (there is not DB level error mentioned there).

Example of failing rule:

```
{ "rules_generate_field_collection_items" : {
    "LABEL" : "Generate field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--smlouva" : { "bundle" : "smlouva" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "field_collection_item",
            "param_field_name" : "field_dodatky_ke_smlouve_fc",
            "param_host_entity" : [ "node" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

```

For example, this works fine:

```
{ "rules_generate_nodes" : {
    "LABEL" : "Generate nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--smlouva" : { "bundle" : "smlouva" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "mesto",
            "param_title" : [ "node:title" ],
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
It seems to be working fine, when I'm using event "Before saving content (of type ...)". If you also want to make sure, that it only affects newly created entities (mostly nodes), you'll also want to add condition "Data value is empty" for `node:nid` or another entity ID.

# Answer
> 0 votes
I doubt a little bit about the comment"*... it is a bug report for a contributed module ...*". And IMO changing the event to "***Before*** *saving content (of type ...)*", as in the existing answer, seems like changing the question, which was NOT about that Rules Event.

Have a look at the issue about ***"After updating existing content" runs before content is saved***, about an event which is a variation of your event here, and somehow explains that "***after*** saving something" actually happens "***before*** saving something". Therefor I'm about sure this is not a bug, but simply how the Rules module works.

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

---
Tags: rules, entities
---


# Question
Title: How do I update core in commerce 2.x distribution?
I would like to update drupal core from 8.2.1 to 8.2.3 in a local environment. The normal procedure of deleting both the vendor and core folders along with the files in the site root won't apply. The commerce2.x disto installation puts the vendor folder outside of the site root and it contains more files than in a fresh drupal 8 downloaded vendor folder. I'm guessing there must be a slighty different process.

I run `composer update drupal/commerce --with-dependencies`.

The image attached shows the error.

If anyone can give me the steps I need to take, that would be great.

# Answer
Simple solution found in the end. Before running a composer command I had to add paths in my Windows Environment path variable to both the Git.exe file and the ssh-agent file.

I then ran a slightly different composer command from the one above: composer update drupal/core --with-dependencies
I did this from the root of my site.

I had to make sure that drupal/core is in the require part of the composer.json file and not the replace part.
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How do I remove the "submitted by" text on node display?
In Drupal 6 the option to remove that text was located in the theme settings; where is it in Drupal 7?

# Answer
> 20 votes
For the "basic page" type, it would be `example.com/admin/structure/types/manage/page/edit`. For the "article" type, it's `example.com/admin/structure/types/manage/article/edit`.

# Answer
> 22 votes
You can find the option by editing the content type settings.

Structure \> Content Types \> *Type Name*

Click **Edit**

Then uncheck the **Display author and date information.** option in **Display Settings**.

# Answer
> 3 votes
Module Submitted By is a more fine-grained solution FWIW. Here is a quote about it (from the module's project page):

> ... lets you control the format of the "Submitted by" information on your content per content type. It adds a fieldset to your node edit form called Appearance that lets you put in a tokenized pattern for the text you want to display.
>
> Depends on Token module. Note: This module does not create any data; rather it relies on other modules providing that data through Token.
>
> You might find the Custom Tokens module useful for things that aren't already provided.

# Answer
> 0 votes
In case you want to hide the "Submitted by" text in code, which is rather more flexible than the node settings:

```
function my_theme_preprocess_node(&$variables) {
  if ($variables['submitted']) {
    $variables['submitted'] = t('!username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  }
}

```

---
Tags: 7, nodes
---


# Question
Title: Type hinting - which is better, UserInterface or AccountInterface?
Recently I've finally begun shifting my focus from D7 to D8, and I'm converting a site over to D8. In D7, I type-hinted my account objects as \stdClass, since they were not members of any class. However in D8, they are now members of the User class.

That said, I'm finding in some code on the net that people are typehinting as Drupal\Core\Session\AccountInterface, and in other places as Drupal\user\UserInterface. How should we be determining which one to use for our typehints, and what is the difference between the two types of objects?

# Answer
`UserInterface` extends `ContentEntityInterface`, `EntityChangedInterface`, and `AccountInterface`. This means there are methods an object implementing `UserInterface` needs to have but objects implementing `AccountInterface` don't need to have. For example, there is `UserInterface::hasRole()`, but `AccountInterface::getRoles()`; in the first case, there is a helper method allowing to check the object has a specific role, while in the second case you would need to write your code for that, getting the list of the roles with `AccountInterface::getRoles()`.

Which hint should be used is given from the documentation. For example, `hook_user_logout()` gets an object implementing `\Drupal\Core\Session\AccountProxyInterface`, since it gets the object returned from `Drupal::currentUser()`. See `user_logout()`, the function invoking `hook_user_logout()`.

```
  $user = \Drupal::currentUser();

  \Drupal::logger('user')->notice('Session closed for %name.', array('%name' => $user->getAccountName()));

  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

```

Sometime the documentation for a hook doesn't show a specific hint, such as in the case of `hook_user_login()`. In this case, it could help to see which hint is used from the implementations of that hook, for example `system_user_login()`, which uses `UserInterface` as hint for its argument.

When you aren't sure about the correct interface implemented by the object passed to a function (including a hook), use the most generic one as hint. In the case you describe, that would be `AccountInterface`.
> 8 votes

# Answer
As *UserInterface* extends *AccountInterface* setting type hint to *AccountInterface* would allow you to accept both types of objects. You may think about *UserInterface* as advanced *AccountInterface* which declares a few extra methods (*hasRole*, *addRole*, *removeRole*, etc). I would use *AccountInterface* interface wherever it possible unless you need some of these extra methods.

One more detail, object of *UserInterface* should also implement methods from *ContentEntityInterface* and *EntityChangedInterface*.
> 4 votes

# Answer
Check the documentation for `AccountInterface`:

> Defines an object that has a user id, roles and can have session data. The interface is implemented both by the global session and the user entity

It's in the `Session` namespace for a reason – it represents something that can have session data.

The `ContentEntityInterface` and `EntityChangedInterface` interfaces extended by `UserInterface` tell you that it represents a different concept:

> Content entities use fields for all their entity properties and are translatable and revisionable, while translations and revisions can be enabled per entity type.

#

> Defines an interface for entity change timestamp tracking.
>
> This data may be useful for more precise cache invalidation (especially on the client side) and concurrent editing locking.

A `UserInterface` represents a full Drupal user account that can have revisions, fields, translations, etc.

---

I can't tell you which is more fitting for your use case, but I encourage you to think about which of these interfaces is most applicable for the code you are writing.

My instinct tells me that you would use `AccountInterface` for something that is minimally "logged in" (e.g. logged in user, a list of users online, someone signed in through SSO) and `UserInterface` for anything more than that (e.g. user profiles, associated authors, long-lived data, most things we do in Drupal).
> 3 votes

---
Tags: 8
---


# Question
Title: How do I access the Drupal class from a standalone PHP file?
How do I use the `\Drupal` class in an standalone PHP file?

# Answer
You can make use of drush php-script command.

```
drush scr /path/to/file.php

```
> 1 votes

# Answer
You can use drush in a shebang, if you have drush installed.

This is an example for a standalone php file, where you can access Drupal classes:

```
#!/usr/bin/env drush

$sitename = \Drupal::config('system.site')->get('name');

echo "This is the site $sitename\n";

```

See http://www.drush.org/en/master/shellscripts/
> 1 votes

# Answer
Since most of the drupal core components are composer packages you can load them quite easily using composer:

```
composer require drupal/component_name

```

You just need to require the composer's autoloader into your PHP script and you can quite easily use these classes in your own scripts.
> 0 votes

---
Tags: 8, external-scripts
---


title: twig attribute class

text:
# Question
Title: twig attribute class
I want to add multiple class to my `{{item}}` twig template. The following code

```
{% set item = item|merge({'#attributes': { 'class': 'project-label'}}) %}

```

sets only one class ... how can I assign multiple class ? can i do something like this

```
{% set item = item|merge({'#attributes': { 'class': 'project-label'}}),
({'#attributes': { 'class': 'project-term{{ loop.index }}'}}`)%}

```

Please help.

Thanks

# Answer
Put the classes in an array:

```
{%
  set itemclasses = [
    'project-label',
    'project-term' ~ loop.index,
  ]
%}

```

And add the array to attributes:

```
{% set item = item|merge({'#attributes': { 'class': itemclasses } }) %}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Custom Field Type only shows -hidden- Widget
I want to create a Field Type with text\_textfield as default widget. But all I get is -hidden-

Here is my FieldType Class

```
<?php

namespace Drupal\gettweet\Plugin\Field\FieldType;

use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'get_tweet_field_type' field type.
 *
 * @FieldType(
 *   id = "get_tweet_field_type",
 *   label = @Translation("Get tweet"),
 *   description = @Translation("Reference a tweet token"),
 *   default_widget = "text_textfield",
 *   default_formatter = "text_default"
 * )
 */
class GetTweetFieldType extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    return [
      'max_length' => 255,
      'is_ascii' => FALSE,
      'case_sensitive' => FALSE,
    ] + parent::defaultStorageSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Text value'))
      ->setSetting('case_sensitive', $field_definition->getSetting('case_sensitive'))
      ->setRequired(TRUE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      'columns' => [
        'value' => [
          'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
          'length' => (int) $field_definition->getSetting('max_length'),
          'binary' => $field_definition->getSetting('case_sensitive'),
        ],
      ],
    ];

    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

    if ($max_length = $this->getSetting('max_length')) {
      $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
      $constraints[] = $constraint_manager->create('ComplexData', [
        'value' => [
          'Length' => [
            'max' => $max_length,
            'maxMessage' => t('%name: may not be longer than @max characters.', [
              '%name' => $this->getFieldDefinition()->getLabel(),
              '@max' => $max_length
            ]),
          ],
        ],
      ]);
    }

    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $values['value'] = $random->word(mt_rand(1, $field_definition->getSetting('max_length')));
    return $values;
  }

  /**
   * {@inheritdoc}
   */
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
    $elements = [];

    $elements['max_length'] = [
      '#type' => 'number',
      '#title' => t('Maximum length'),
      '#default_value' => $this->getSetting('max_length'),
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#min' => 1,
      '#disabled' => $has_data,
    ];

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('value')->getValue();
    return $value === NULL || $value === '';
  }

}

```

# Answer
> 1 votes
If you are absolutely sure your field type is compatible with some existing widgets and formatters you can reuse them by implementing hook\_field\_widget\_info\_alter and hook\_field\_formatter\_info\_alter.

```
/**
 * Implements hook_field_widget_info_alter().
 */
function gettweet_field_widget_info_alter(array &$info) {
  $info['text_textfield']['field_types'][] = 'get_tweet_field_type';
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function gettweet_field_formatter_info_alter(array &$info) {
  $info['text_default']['field_types'][] = 'get_tweet_field_type';
}

```

---
Tags: 8, entities
---


title: Create a link in hook_mail_alter()

text:
# Question
Title: Create a link in hook_mail_alter()
I am using hook\_mail\_alter to modify the email that the user gets when an administrator creates an account. What I am trying to do is create a link in the email body, the link gets created but it adds a \[1\] to the link text and after the email text is done. There is the \[1\] again with the actual link. Is there anyway to actually have the link created in the text instead of having it render at the end? Here is my code:

```
function my_module_mail_alter(&$message) {
if ($message['id'] = 'user_register_admin_created') {

    $url = Url::fromUri('https://www.google.com');
    $external_link = \Drupal::l(t('Google'), $url);
    $message['body'][] = t("Go to: ");
    $message['body'][] = $external_link;
}
}

```

# Answer
> 1 votes
That happens because the class normally handling the email sending (`PhpMail`) uses the following code, in `PhpMail::format()`.

```
  // Convert any HTML to plain-text.
  $message['body'] = MailFormatHelper::htmlToText($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = MailFormatHelper::wrapMail($message['body']);

```

In particular, this is the code handling the links. (See the comment before the code.)

```
  // Replace inline <a> tags with the text of link and a footnote.
  // 'See <a href="https://www.drupal.org">the Drupal site</a>' becomes
  // 'See the Drupal site [1]' with the URL included as a footnote.
  static::htmlToMailUrls(NULL, TRUE);
  $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  $urls = static::htmlToMailUrls();

```

To send HTML emails, you need a different class implementing `MailInterface`. The Swift Mailer module implements it, for example, and allows to send HTML emails; it also allows to select in which way to send a message (server SMTP, MTA agent, `mail()` function).
The Mail System module provide a UI that allows to select the mail plugin used to send emails, so you don't need to mess with the configuration to do it.

>

---
Tags: 8, emails
---


# Question
Title: How to use Rules to send an eMail with a body containing all items of a field collection?
I've defined a content type that contains a **field collection**. The field collection contains 4 fields. When the content is created, it may have one or more of the field collections.

I set up a rule to send the email to users of a specific role. I've used tokens in the rule to specify some data fields in the body. I'm currently stumbling on ***how to specify the one or more field collection fields in the body of the email***.

I found some posts that indicated that I needed to add a condition for *"node has field"* which I have done. I wasn't sure what to select from the drop down lists, so, I took a logical guess. That seemed to provide some more tokens.

However, I've tried several different methods to specify the field collection in the body of the email, but, all have failed. The email is empty in the spot where I tried to display the field collection.

How can I specify the fields of a field collection in the body of an email?

# Answer
# Part 1: Custom Rule

Have a look at this rule (in Rules export format), which IMO is a possible answer to your question:

```
{ "rules_field_collection_msg_and_email_body" : {
    "LABEL" : "Field Collection msg and eMail body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The  list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E"
          },
          "PROVIDE" : { "variable_added" : { "variable_for_email_body" : "Variable to use in eMail body" } }
        }
      },
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "article details item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-for-email-body" ],
                "value" : "[variable-for-email-body:value]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E"
              }
            },
            { "drupal_message" : { "message" : "The host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      },
      { "mail" : {
          "to" : [ "site:current-user:mail" ],
          "subject" : "Demo of an eMail with a body containing all items of a field collection",
          "message" : [ "variable-for-email-body" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some more details about what this rule does:

**\- Rules Event**: Content is viewed (change to whatever fits).

**\- Rules Conditions**:

* Entity has field, for entity=node and field (machine name)= `field_article_details` (adapt this machine name to whatever fits).
* User has role(s), for user=`[site:current-user]` and role administrator (adapt this condition to whatever fits, or just delete it entirely, doesn't make any difference).

**\- Rules Actions** (this is where the *party* starts ... pay attention!):

* `Add a variable` (to use in eMail body later on ...), with machine name `variable_for_email_body` (adapt to whatever fits), and set an initial value which corresponds in the demo with everything from **Part 1** and the header line from **Part 2**.
* `Show a message on the site`, this is just for QA-testing, to see what's happening when the previous Rules Action is executed. It shows the equivalent of the initial value assigned to the `variable_for_email_body` variable from the previous step.
* Add a `Loop` for list `[node:field-article-details]` (are you following, the field collection field!), and for list item use `article_details_item`. Within this loop, add these Rules Actions:

+ `Set a data value`, for variable `[variable-for-email-body]` (which we added as the very first Rules Action!), and with value (watch out, here comes the clue) ... something that looks like so (in each iteration of this Rules loop, we concatenate (append) the actual data for each field collection item to the end of the our `[variable-for-email-body:value]`, and surround it with whatever other fixed text and/or HTML tags that we want to see in our eMail body):
> `[variable-for-email-body:value]<br />`
>
> `Host entity of this field collection item: [article-details-item:host]<br />`
>
> `Unique ID of the field collection item: [article-details-item:item-id]<br />`
>
> `Field "field_author": [article-details-item:field-author]<br />`
>
> `Field "field_price": [article-details-item:field-price]<br />`
>
> `Field "field_approval_required": [article-details-item:field-approval-required]<br />`
>
> `<hr />`

+ `Show a message on the site`, this is just for QA-testing (also), to see what's happening when the previous Rules Action is executed. It shows what got concatenated (appended) to the previous value assigned to the `variable_for_email_body` variable.
* `Send mail`, which is extremely basic (after the work completed in the loop above ...):

+ To: `[site:current-user:mail]` (adapt to whatever fits)
    + Subject: ***Demo of an eMail with a body containing all items of a field collection*** (adapt to whatever fits)
    + Message: `[variable-for-email-body]` (adapt to whatever fits, either you add anything to the message body BEFORE or AFTER this message body here, or you adapt what gets moved as content of this variable in the previous Rules Actions `Add a variable` or `Set a data value`)

If you have the Rule UI enabled, you should be able to import the above rule in your own site, provided you first apply some of the changes I suggested, after you adapt the machine names to fit your names. After importing you may want to also change any of its events or conditions in it, or apply changes to any of its actions.

# Part 2: Demonstration

### Status message

```
This is a demo of a node containing a field collection ...
About this demo:

The machine name of the field collection is field_article_details, and the number of values for it is unlimited.
This field collection has these fields:

- a text field labeled Author with machine name field_author.
- a decimal field labeled Price with machine name field_price.
- a boolean field labeled Approval required with machine name field_approval_required.

Part 1: The list of items contained in the field collection with machine name 'field_article_details' looks like so (note the comma to separate each item):
Approval required:     No
Price:     12.45
Author:    Pierre Vriens
,
Approval required:     Yes
Price:     9.15
Author:    Barak Obama
,
Approval required:     No
Price:     3.40
Author:    Hillary Trump
,
Approval required:     Yes
Price:     1.23
Author:    Donald Clinton

Part 2: The result of a Rules loop that iterates for each of the field collection items (using its unique ID) ...
Host entity of this field collection item: 73
Unique ID of the field collection item: 1
Field "field_author": Pierre Vriens
Field "field_price": 12.45
Field "field_approval_required": No
Host entity of this field collection item: 73
Unique ID of the field collection item: 2
Field "field_author": Barak Obama
Field "field_price": 9.15
Field "field_approval_required": Yes
Host entity of this field collection item: 73
Unique ID of the field collection item: 3
Field "field_author": Hillary Trump
Field "field_price": 3.40
Field "field_approval_required": No
Host entity of this field collection item: 73
Unique ID of the field collection item: 4
Field "field_author": Donald Clinton
Field "field_price": 1.23
Field "field_approval_required": Yes

```

### eMail body

This is how the entire content of the body of the delivered eMail looks like (look for "*Part 2*" in it to see the most interesting, I think, part of it):

```
-------- THIS IS A DEMO OF A NODE CONTAINING A FIELD COLLECTION ...----------

------------------------------------------------------------------------------
*About this demo*:
The machine name of the field collection is *field_article_details*, and the
number of values for it is unlimited.
This field collection has these fields:
- a text field labeled *Author* with machine name *field_author*.
- a decimal field labeled *Price* with machine name *field_price*.
- a boolean field labeled *Approval required* with machine name
*field_approval_required*.
------------------------------------------------------------------------------
*Part 1*: The  list of items contained in the field collection with machine
name *'field_article_details'* looks like so (note the comma to separate each
item):
------------------------------------------------------------------------------
-------- APPROVAL REQUIRED: ------------------------------------------------

No
-------- PRICE: ------------------------------------------------------------

12.45
-------- AUTHOR: -----------------------------------------------------------

Pierre Vriens
 * Delete [1]
 * Edit [2]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

Yes
-------- PRICE: ------------------------------------------------------------

9.15
-------- AUTHOR: -----------------------------------------------------------

Barak Obama
 * Delete [3]
 * Edit [4]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

No
-------- PRICE: ------------------------------------------------------------

3.40
-------- AUTHOR: -----------------------------------------------------------

Hillary Trump
 * Delete [5]
 * Edit [6]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

Yes
-------- PRICE: ------------------------------------------------------------

1.23
-------- AUTHOR: -----------------------------------------------------------

Donald Clinton
 * Delete [7]
 * Edit [8]

 * Add [9]

------------------------------------------------------------------------------
*Part 2*: The result of a *Rules loop* that iterates for each of the field
collection items (using its unique ID) ...
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 1
Field "field_author": Pierre Vriens
Field "field_price": 12.45
Field "field_approval_required": No
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 2
Field "field_author": Barak Obama
Field "field_price": 9.15
Field "field_approval_required": Yes
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 3
Field "field_author": Hillary Trump
Field "field_price": 3.40
Field "field_approval_required": No
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 4
Field "field_author": Donald Clinton
Field "field_price": 1.23
Field "field_approval_required": Yes
------------------------------------------------------------------------------

[1]http://www.example.com/field-collection/field-article-details/1/delete?destination=node/73
[2]http://www.example.com/field-collection/field-article-details/1/edit?destination=node/73
[3]http://www.example.com/field-collection/field-article-details/2/delete?destination=node/73
[4]http://www.example.com/field-collection/field-article-details/2/edit?destination=node/73
[5]http://www.example.com/field-collection/field-article-details/3/delete?destination=node/73
[6]http://www.example.com/field-collection/field-article-details/3/edit?destination=node/73
[7]http://www.example.com/field-collection/field-article-details/4/delete?destination=node/73
[8]http://www.example.com/field-collection/field-article-details/4/edit?destination=node/73
[9]http://www.example.com/field-collection/field-article-details/add/node/73?destination=node/73

```

I know, the formatting of this eMail body is pretty (really?) poor, but watch what's below the line with "*Part 2*": everything you possibly may want to know about every item in your field collection, in the eMail body ... which is exactly what this question was about, no? So just reformat the eMail content to your liking (i.e delete everything in it you don't want, and improve the formatting of what you're really interested in).
> 1 votes

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


# Question
Title: Render value of custom content type in html.html.twig
is there a way to render a value from a node of custom content type in html.html.twig?

E.g. in my custom content type "book" I have a field called "author\_name". I now like to render the node value of "author\_name" anywhere in html.html.twig.

Is this somehow possible using just twig? I tried a few things with extends, embed, include etc, but nothing worked so far.

# Answer
> 3 votes
Load the node and get the field value in a preprocess hook:

```
function mytheme_preprocess_html(&$variables) {
  if ($variables['node_type'] == 'book' && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $variables['node_field1'] = $node->field_field1->value;
  }
}

```

This makes sense to check first for the correct content type, because then you know which fields are defined. Otherwise you would have to check if the field is present to prevent an error. But then you have already loaded the node for nothing.

Output the value in twig:

```
{{ node_field1 }}

```

---
Tags: theming, 8
---


# Question
Title: How to collect a list of file URLs using Rules and send a single email containing that list?
I am using the Rules module to send an email when a content node gets saved/updated.

I have a basic node where users can upload a large number of files and enter an email address to notify someone about the change.

In this example, the Rules Action to `Send Email` is in a Rules loop, and I get one email per item in list. When I move `Send Email` to the left, I cannot access the "`list_item`" variable.

**Rules Events**:

* After saving new content
* After updating existing content

**Rules Conditions**:

* *Content is of type*, Parameter: Content: \[node\], Content types: BasicPage
* *NOT Data value is empty*, Parameter: Data to check: \[node:field-email\]

**Rules Actions**:

* *Loop*
* Parameter: List: \[node:field-file\]
* List item: Current list item (list\_item)

+ *Send Email*
    + Parameter: To: \[node:field-email\], Subject: Test \[node:title\], Message: \[list-item:file:url\], From: noreply@host.ca

# Answer
## Problems with what you tried so far

> the Rules Action to `Send Email` is in a Rules loop, and I get one email per item in list

Your rule works as implemented: for each iteration of your loop, you have a `Send an eMail` action ... That's not really what you want of course ...

> When I move `Send Email` to the left, I cannot access the "`list_item`" variable.

With that "*move Email to the left*", you must mean something like "***Using the Rules UI, I change the Rules Action to `Send an eMail`, so that it is no longer considered as one of the Rules Actions to be performed for each iteration of the loop. And instead that `Send an eMail` Rules Action should only be performed 1 time after the Rules loop is completed finished***".

So yes, that's a way to only execute such `Send an eMail` Rules Action 1 time (instead of for each iteration of the loop). However, by doing so, your Rules Action to `Send an eMail` no longer has access to that crucial variable `list_item` which is like a local variable inside your loop.

## Solution to make it work anyway

However, if what you're looking for (= the list of files as stored in your file field) is not available, then just (a) make it available first and (b) wait with your `Send an eMail` action until it is available. Read on for more details ...

**The trick to do so** is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

1. **Add** some new Rules variable that will be used later on as part of the eMail body, before the start of your loop. Say you name the variable `file_list_var_for_email_body`.
2. Within your loop, for each iteration, prepend or append the value for each `list_item` to that variable `file_list_var_for_email_body` (see where we're going???).
3. Move that `Send an eMail` action outside your loop, and after the loop completed. And finetune the details (configuration) of your Rules Action to `Send an eMail`. When doing so, you'll be able to select the token for `file_list_var_for_email_body` to include anywhere in your eMail body.

***Easy, no?***
> 0 votes

# Answer
Concatenating text in Rules was difficult when I did it. What I did was to keep two variables: a text array with a starting element value (such as "This is a digest:...") and a text value.

For each iteration of a loop over items to concatenate into a digest, etc. I set the text value to be the first item in the array (\[array:0\]) and then set the \[array:0\] value to be a concatenation of the text value and the new value from the loop. When the loop finishes, you know the \[array:0\] has the digest content.

I do not know why this couldn't work in a simpler way by concatenating the text value each loop directly or using two text values instead of an array. When I tried either of the other ways it only kept the last item or first item of what was being concatenated.
> 0 votes

---
Tags: 7, rules, files, emails
---


title: Assign a role upon registration

text:
# Question
Title: Assign a role upon registration
I'd like to assign a specific role when a new user registers on my site using the regular registration form, beyond that of just "authenticated user".

How can I do this?

# Answer
> 8 votes
This is easily accomplished using the Rules module and setting up the "event" and "action" to behave the way you want it to behave.

I set it up so that "after saving a new user" I "added a user role" of the type that I wanted to have. That should do the trick.

# Answer
> 4 votes
There's a module for that: Registration role.

> Registration role lets an administrator select a role to automatically assign to new users. The selected role will be assigned to new registrants.

# Answer
> 2 votes
Another option is the Auto Assign Role module:

> The Auto Assign Role serves three primary purposes. The first is to provide an automatic assignment of roles when a new account is created. The second is to allow the end user the option of choosing their own role or roles when they create their account. The third is to provide paths that will trigger a specific role when an account is created.

# Answer
> 2 votes
Try the Role field and Rules modules.

* Create a role field, field\_user\_role (check boxes/radio button) in admin/config/people/accounts/fields
* Create a rule in admin/config/workflow/rules, for the *After saving a new user account* even
* Add \_Entity has field \> Entity: \[account\], Field: field\_user\_role\_ as condition
* Set a data value in Actions.

# Answer
> 1 votes
This is the most straightforward method, in a custom module.

```
function MY_MODULE_user_insert($account, $data) {
  $role = user_role_load_by_name('role-name');
  user_save($account, array('roles' => $account->roles + array($role->rid => $role->name)));
}

```

---
Tags: 7, users
---


# Question
Title: How to use Rules to send an eMail containing a list of nodes with a selected value in a field?
I try to send a list of nodes with certain value in a specific field via the Rules module.

This is what I have so far:

* Event: "After updating existing content of type MyContentType"
* Conditions: "Parameter: Data to compare: \[node:field-status\], Data value: sendmail"
* Actions:

+ "Parameter: Entity type: Node, Property: Status, Value: \[node:field-status\], Limit result count: 100 Provides variables: Fetched entity (entity\_fetched)"
    + "Send HTML e-mail"

Here is an export of this rule:

```
{ "rules_send_node_list" : {
    "LABEL" : "Send node list",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "ON" : { "node_update--mycontenttype" : { "bundle" : "mycontenttype" } },
    "IF" : [ { "data_is" : { "data" : [ "node:field-status" ], "value" : "0" } } ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "field_status",
            "value" : [ "node:field-status" ],
            "limit" : "100"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "mimemail" : {
          "key" : "[node:title]",
          "to" : "to@example.com",
          "from_name" : "QX",
          "from_mail" : "from@example.com",
          "subject" : "Node flagged",
          "body" : "[entity-fetched:0]\r\n[entity-fetched:1]\r\n[entity-fetched:2]\r\n[entity-fetched:3]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

The list with nodes with the `field-status` set to "sendmail" is indeed send out. The problem I'm facing here is that I have to put in the email body tokens like `[entity-fetched:0]`, `[entity-fetched:1]`, etc.

In the section *Replacement patterns for Fetched entity* I only have `[entity-fetched:0]` till `[entity-fetched:3]` available. But I have more nodes than that. I would like to have the complete list with these flagged nodes.

Any suggestions about this?

# Answer
## How to get a complete list

Your Rules Events and Conditions are pretty sure OK, but you're missing a crucial Rules Action: a Rules **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

The result of your first Rules Action is actually a list, which as per the "**PROVIDE**" that is shown in your exported rule, is stored in a variable named `entity_fetched` (BTW, try to use a more meaningful variable name for such variables, eg `nodes_with_status_sendmail`).

As you seemed to have understood already, the `entity-fetched:0`, ..., `entity-fetched:3`, correspond to your 1st, 2nd, 3rd and 4th node in that list of fetched entities (nodes).

What you need to do to repair your Rules Actions, are these steps:

1. AFTER your first Rules Action (which fetch those nodes, and which is fine), use the link "Add a loop" as the next (2nd) Rules Action. When doing so, specify these options for it (note the looooong variable name for my 'List item', I bet you get its meaning just from its name ...):

* **Parameter**: List: \[entity-fetched\]
    * **List item**: Single node with status sendmail (single\_node\_with\_status\_sendmail)
2. Within that loop you added, use the link to the right of it (in the Rules UI), to "Add an action". That way the Rules Action you add, will be performed as part of the loop. The actual Rules Action to add is similar to the (last) Rules Action you already have, with machine name "`mimemail`". As you will notice while creating a similar Rules Action, you'll now be able to select/specify tokens that relate to ... `single_node_with_status_sendmail`. However, the content of your eMail message body should now **only** (repeat: only!) refer to the "List item" being processed in the current iteration of the Rules loop (instead of those 4 items in your existing "`mimemail`" action).

As you will probably understand, since you're now processing 1 single node in each iteration, and it doesn't matter how many nodes you have in your list of nodes, there is no more restriction to 4 nodes only.
3. After you completed the previous step, there is no more need for the existing (last) Rules action about "`mimemail`", so just delete that Rules Action.

With these changes you solve your limitation of 4 nodes maximum. However, in case you don't realize yet, you may have introduced a new challenge, as detailed below ...

## Solution to your problem ... might (will?) change the problem

Using the approach detailed above, the result of your adapted rule is that you ***will*** get 1 ***separate*** eMail for each node fetched via that first Rules Action (which created the list of nodes to be processed). If you typically only have a few nodes that may not be a real issue to worry about. But if you have dozens (or more?) of such nodes then you might want to consider consolidating all such eMails in a single eMail, which contains (in its eMail body) the complete list of nodes.

A possible solution to implement such consolidation, is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

1. **Add** some new Rules variable that will be used later on as part of the eMail body, before the start of your loop. Say you name the variable `nodes_list_var_for_email_body`.
2. Within your loop, for each iteration, prepend or append the value for each "list item" to that variable `nodes_list_var_for_email_body`.
3. Move your (new) "`mimemail`" action outside your loop, and after the loop completed. And finetune the details (configuration) of your (new) "`mimemail`" Rules Action. When doing so, you'll be able to select the token for `nodes_list_var_for_email_body` to include anywhere in your eMail body.

## Summary

If you think about it, you'll end up more or less with a variation of the last Rules Action in the rule you already have, in which the body part now contains `nodes-list-var-for-email-body` instead of `entity-fetched:0`, ..., `entity-fetched:3`.

But for this (crucial) `nodes-list-var-for-email-body` token to be available, you need to (a) add the Rules Loop and (b) add 2 more Rules Actions to create the content (value) of `nodes-list-var-for-email-body`.

## Voilà

... That's really all it takes to get this to work.
> 1 votes

# Answer
You need to loop through the list of nodes. Create a views list of the nodes to loop through, add a vbo field (doesn't matter which) and save it. Now rules components (action set) will have the list available to loop through.
> 0 votes

---
Tags: entities, rules, tokens, workflows
---


# Question
Title: How to add a user rank in their profile?
I want to have rank for every user. A simple -\> amin rank is 18 with 300 points.

Any suggestions?

# Answer
> 0 votes
Use a combination of the Rules, Userpoints and User badges module, as further detailed below ...

# Add a new badge

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

```
{ "rules_grant_a_new_badge" : {
    "LABEL" : "Grant a new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "user_badges", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "7" } },
            "DO" : [
              { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
            ]
          }
        ]
      }
    ]
  }
}

```

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 7, it will grant the user badge.

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?"). However, by using the Conditional Rules module, you can consolidate the logic for various user badges in a single rule, e.g bronze for 7 points, silver for 77 points, gold for 777 points.

The clue to make this rule work is the very first Rules Action "***Load user points of a user***". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".

# Remove a new badge

If you want "*a user's old badge to be replaced by a new one*", then you should also add a 2nd Rules Action to the rule shown above. The action to be used is `remove_badge_by_name` (instead of `add_badge_by_name`).

# Only grant a new badge once

To avoid "*displaying a message each time when user getting more than 7 user points*" (as in your question), just add a Rules Condition like "NOT `User has badge`". This is one of the Rules Conditions provided by the User badges module.

# Display the badge

To actually "*display the badge with the username at the top*", you could use what's written in the Community Documentation about User Badges, i.e:

> To display user badges in your theme use:
>
> ```
> <?php
>   if (module_exists('user_badges')) {
>     print user_badges_for_uid($uid);
>   }
> ?>
>
> ```
>
> Note: $uid means 'a user id' here, not the literal use of $uid. Most people will use the uid of the node ($node-\>uid) or comment ($comment-\>uid) author.
>
> In Drupal (and theming), $node is a PHP object that represents the node, and $comment represents the comment. They are not always both available in every template file, so check the comments at the top of the file to see what is available. You may have access to other uids (user ids), and in these cases you can replace $uid with that value.

---
Tags: 7, users, userpoints
---


# Question
Title: Filter by end date if it exists, if not then filter by start date
I have a view of events, which has a start date and an end date (2 separate fields as the end date was added later). The end date is optional. I want to show events that are either in the future or are currently ongoing. So somehow I need to check if the node has an end date - and if so apply the filter on that, but if not then use the start date instead.

Is there any way to achieve this? Maybe I'm looking at in the wrong way.

# Answer
> 0 votes
Either you make end date field mandatory or use hook\_views\_query\_alter to get ongoing or future events.

If you go with field mandatory option, you simply need to add two view filters with OR condition.

1. Start date \>= Today **OR**
2. End date \>=Today

---
Tags: 7, views
---


# Question
Title: Disable a Module after Fatal Error without Server/DB access?
I'm working on a Drupal 7 site and recently triggered a fatal error via installation of incompatible modules. Is it possible to disable a module when site is giving fatal error on each page? Specifically without direct access to files or database?

# Answer
> 1 votes
Without access to the server, files or database?

No, there's nothing you can do.

It's the database you need to update, and if you can't get to that externally or locally to run some SQL, you're out of luck.

You could theoretically alter some code somewhere in core to bypass the issue of the broken module, but of course that would require access to the files, at which point you could've just run the SQL via PHP.

---
Tags: 7, debugging
---


title: Base table missing in database?

text:
# Question
Title: Base table missing in database?
I just emptied the cache in my Drupal database via MySQL, and all of a sudden I'm getting this error on my home page? Help! How can I fix this? It almost seems like a table was deleted by accident?

**Original**

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'databasename.entity\_test\_type' doesn't exist: SELECT et.\* FROM {entity\_test\_type} et; Array ( ) in entity\_test\_entity\_info() (line 73 of /var/www/drupal/true-001/sites/all/modules/contrib/entity/tests/entity\_test.module).

**Additional**

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'databasename.locales\_source' doesn't exist: SELECT lid, location FROM {locales\_source} WHERE source = :source AND context = :context AND textgroup = 'default'; Array ( \[:source\] =\> An AJAX HTTP error occurred. \[:context\] =\> ) in \_locale\_parse\_js\_file() (line 1563 of /var/www/drupal/true-001/docroot/includes/locale.inc).

# Answer
Yes that is correct, the errors are saying `entity_test_type` and `locales_source` do not exists. Try searching for them with PHPMyAdmin or any other DB viewer and you will very likely not find them. So yes, somehow those tables got deleted or possibly renamed?

> Help! How can I fix this?

If they got deleted, you have the following options:

A) **Disable and uninstall** those modules, then enable them again and they should create the missing tables.

B) Revert back to a DB backup where those tables exist, then export the 2 tables only. Now revert back to your latest DB backup where they are missing and just import those 2 tables.

C) Manually re-create those tables with the proper column names
> 1 votes

---
Tags: 7
---


# Question
Title: How to resolve the 403 error when creating a new node via RESTful module?
I'm trying to create a new node through REST on Drupal 8 with no success and a 403 (Forbidden) error. I'm using REST UI module to enable permissions with the following config for Content resources:

> GET authentication: basic\_auth formats: hal\_json, json
>
> POST authentication: basic\_auth formats: hal\_json, json

After many failed tries I installed a fresh copy of Drupal 8.2.3 to discard it had to be with the recent core upgrade on my original site. The big surprise is on the fresh site there are no other RESTful module permissions than *Administer REST resource configuration*, no permissions to grant DELETE, GET, PATCH or POST to each role.

I'm using Postman for testing purposes as follows:

Request body:

```
{
    "_links": {
        "type": {
            "href": "http://fischer.dev:81/rest/type/node/article"
        }
    },
    "title": [
        {
            "value":"My article"
        }
    ],
    "type": [
        {
            "target_id":"article"
        }
    ]
}

```

User role is granted permissions to create Article nodes. I tried even with the admin credentials with no success. The GET method for retrieving an existing node is woking fine.

I don't know if there was any change on the latest Drupal release since the official documentation page for this module appears to be outdated. Am I missing something?

# Answer
For headers you only need `Content-Type` and `Authorization`.

Your POST url needs to be **`http://fischer.dev:80/entity/node`** (this is only for POST).

If you are going to PATCH or DELETE, the url would then be the url of the node, Ex: `http://fischer.dev:80/node/1` that you want to update (patch) or delete.

**PS:** Not really sure why you have port numbers in your url, and why you were using port 81 instead of 80, using `http://fischer.dev/entity/node` should be good enough.
> 0 votes

---
Tags: 8
---


# Question
Title: How can i add edit profile link dynamically?
I have change the default user account page url to cms/dashboard and its redirect to custom page where edit profile link is not available. So i want to add the custom edit link, i add the block image and add the link to that image which is cms/\[account:uid\]/edit but its converting like cms/%5Baccount%3Auid%5D/edit. Is there any other way to add the Edit Profile link so that user can access the default edit page and change the profile information.

# Answer
> 0 votes
You can use the link directly as `/user`. It goes to the profile page which is similar to the /user/{$GLOBALS\['user'\]-\>uid}

OR

Use Token module to create a menu link with this path: `user/[current-user:uid]/edit`.

# Answer
> 0 votes
There is a "Me Alias" module which you can use this. Like if you want a edit profile link then simply pass the reference user/me/edit.

---
Tags: 7
---


# Question
Title: How to grant User Points after Quiz questions are answered correctly?
I have the User Points module enabled and I want to use the Rules module to create a rule which lets a user win User Points whenever the user answers correctly my questions.

I don't know what should I put as Rules Event and as a Rules Condition.

How can I specify that the user only earns User Points when the answer is correct?

# Answer
> 2 votes
# If using Quiz 7.x-5.x

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

To do so, have a look at the delivered rule, which looks like so:

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

```

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and replace both Rules Actions with a Rules Action to grant an amount of User Points that you may want to be related to `[quiz-result:score]` (note that this token is also shown in the Rules example above (within the Rules Action).

If you're not familiar with how to use Rules to grant user points, then have a look at the answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?" (which also includes a Rules example to make that happen).

# If using Quiz 7.x-4.x

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

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

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


# Question
Title: How to see Database logs in Devel module
I have installed Devel module in Drupal 7. I am able to see logs of error in each page I visit (when I am logged as admin), but, however, have not been able to see the database logs except in the Admin GUI, in the layer windows.

When I close the Admin GUI (without logging out) and visit other pages of my site, I cannot see the database logs. I installed Devel in other project long time ago, and I would dare to say that I saw these database logs in every page.

What is the recommended config: see all errors, and which template to use?

# Answer
You need to give Devel permissions to the user from which, you are logged in, and want to view logs.Go to People \>\> Permissions and give Devel permissions to the role you want to.

However, giving Devel permissions to anonymous user is a security risk. So, avoid that.
> 0 votes

# Answer
I tried everything, from giving permissions to all users (it is a web in development stage), re-installing Devel, re-building permissions, even hacking the database to erase any mention to Devel.

It turned out that the problem was in a single function, which called to a single View, which returned a number (a COUNT). This I discovered trying early gits.

I have replicated the View step-by-step and everything goes fine. The SQL is exactly the same. I am not interested on knowing what the error is, Drupal is not a trusty CMS and I cannot waste the precious time of my life trying to figure out the thousands of bugs that are left behind just to show some text, image and eventually sound in a browser, or, in other words, the thousands of bugs to cope with just to render a handful of HTML.
> 0 votes

---
Tags: 7, database, debugging
---


# Question
Title: How can I implement a feature to change settings?
in our site we have a country field in a registration page of our drupal site. admin can download the all registered users as excel report. I added a new country field in my users.XLS report in data export option at *Structure \> Views \> Administrator:users* in my development site.

How can I deploy these changes in my staging site(other development site) by using the Features module? Which feature components can I choose while creating the feature?

# Answer
1) If you made the changes in only views then only export the view form your local development and import it in your production server

or

2) If you added an new field in content type then goto admin/structure/features/create select the field from FIELD INSTANCES (x) (field\_instance) and module will select the dependency automatically then add Name in GENERAL INFORMATION and download and upload it in your module folder and enable it and then follow the 1 point

Note: First try it on your another test development and then on production
> 1 votes

---
Tags: 7, features
---


# Question
Title: Field collection item table names in mysql
I am building a feature which will conditionally need to output entity data. The entity type is a custom one I created, which is complex and implements multiple nested field collections.

My issue is that looping through entities using `Entity::loadMultiple()` is very slow, as each entity needs to use `FieldCollectionItem::load()` multiple times to get to the data it needs to output. Over 1000 entity instances this uses up a lot of resources and takes a long time to load.

I am trying to circumvent this by retrieving the data via a SQL query and joining tables together. I'm hitting a road block when retrieving data from field collection items with long machine names, as the data appears to be stored in tables with names like `field_collection_item__5d28be6634`, basically just "field\_collection\_item\__" with a 10-character hexadecimal hash added to it.

This would not theoretically be a big issue, except it looks like all records for the same field collection item seem to be split up across many of these tables with no pattern or connection that I can discern.

How do I know which tables to retrieve my data from for any given parent field collection instance?

Edit: I have revisited this recently and thought some of these tables might be revision tables, but none of them include the "\_r\_" in the table name. I still cannot determine which tables to use as there seem to be multiple tables (not including revision tables) for one field collection item. Looping through entities and loading nested field collections is taking upwards of 5 minutes which is just too long for my users.

# Answer
> 3 votes
In Drupal 8 the field tables are created as **`[ENTITY_TYPE]__[FIELD_NAME]`** and **`[ENTITY_TYPE]_revision__[FIELD_NAME]`** in database. The `[ENTITY_TYPE]__[FIELD_NAME]` is a main field table where latest revision data of entity field is stored. Where as `[ENTITY_TYPE]_revision__[FIELD_NAME]` is field revision table where all revision data is stored for a field.

In your case I think your Drupal/Database has some issue, because of which the table name has random character (10 characters) hexadecimal in it. I'm not sure of exact reason of this, but I too have notice this sometime in my Drupal Site (only twice one in D7 and one in D8) not every time.

In such case, where you're unsure of which table is used for which field, you can use **`name`** and **`value`** column in **`key_value`** table to get field table mapping. The `name` column contains, the entity and field name and `value` column contains serialized array of field schema stored in blob type. The `name` column format is as below:

**`[ENTITY_TYPE].field_schema_data.[FIELD_NAME]`**

So if I've field named as `field_test` in `field_collection_item` entity, then the mapping will be stored as `field_collection_item.field_schema_data.field_test` in `key_value` table. Check the screenshot below:

**Screenshot 1: `key_value` table showing record of `field_test` field.**

**Screenshot 2: `value` column data from `key_value` table for `field_test` field.**

I know this is not a better solution but, if table name doesn't has field name in it you can use data in `value` column in `key_value` table, you can find which table is used for which field.

Hope this helps.

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


# Question
Title: How to remove custom block parent div's?
I have created custom block in my custom module. I have created block template file into module templates folder. Custom block content coming successfully as per given in block\__MODULENAME\__dummmy\_xyz.tpl.php file. I have only added following code into my block tpl file:

```
<div class="wrapperDummy">Hello</div>

```

But it is coming with block parent div's, Block id and block-inner tag. I dont want to show those extra div's. Following is the hook\_theme which I have in my module file:

```
/*
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {

    $items = array();

    $items['MODULENAME_dummmy_xyz_block_theme'] = array(
        'type' => 'theme',
        'path' => drupal_get_path('module', 'MODULENAME') . '/templates',
        'template' => 'block__MODULENAME__dummmy_xyz',
        'variables'  => array()
    );
    return $items;
}

```

I am rendering block into tpl using,

```
$block = block_load('MODULENAME','dummmy_xyz');
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

```

block.tpl.php code:

```
<?php print $outer_prefix . $inner_prefix; ?>
  <?php print render($title_prefix); ?>

  <?php if ($title): ?>
    <h2<?php print $title_attributes; ?>><?php print $title; ?></h2>
  <?php endif; ?>

  <?php print $content_processed; ?>

  <?php print render($title_suffix); ?>
<?php print $inner_suffix . $outer_suffix; ?>

```

Kindly guide me.

# Answer
> 0 votes
`_block_get_renderable_array` function render default block theme where I couldn't remove parent element, So I made it by using module\_invoke function:

```
$block = module_invoke('custom_module_name', 'block_view', 'block_name');
              print render($block['content']);

```

---
Tags: theming, blocks
---


# Question
Title: How to trigger a rule when clicking on a link?
I am looking for a way to trigger a rule when clicking on a link. What I am actually trying to do, is fireing a VBO with a Button, instead of the Dropdown solution. For this, I created a Rules-Component that does the job, but I don't know how to fire that rule, as it should start from within a view.

# Answer
> 3 votes
take a look at Rules Link:

> This module lets you create links which trigger arbitrary functionality with the help of Rules.

# Answer
> 2 votes
First of all, rules components cannot be triggered on their own. You will need to create a rule for that that will be triggered when one event occurs. Then you should write some code. I would do it like this:

* have a custom page in your module (Eg: "actions/my-custom-rule")
* trigger the rule using `rules_invoke_event('the_event', $params);`
* redirect the user back to the previous page using `drupal_goto(drupal_get_destination());`

If the event is something custom, you need to define the event in your module. Find out more about integrating rules in your module from here.

# Answer
> 0 votes
> I am looking for a way to trigger a rule when clicking on a link.

This is answered correctly by @geoff

> What I am actually trying to do, is fireing a VBO with a Button, instead of the Dropdown solution. For this, I created a Rules-Component that does the job, but I don't know how to fire that rule, as it should start from within a view.

This is a setting in the views panel. Click the field "Views bulk operations" and select to expose each component as a separate button instead of a droplist under "Bulk operations settings".

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


title: How to change url for a page?

text:
# Question
Title: How to change url for a page?
We have a production system xxx.org and a test system at test.xxx.org. We copy production to test. Some of the URL's on the test system keep pointing to production where we want them to point to test.xxx.org.

The production URL looks like they are hard coded in the menu.

We want to easily move production to test so we can test the next version.

# Answer
Look at the value of **$base\_url** value on */sites/default/settings.php*. It may help. Also don't forget to clear the cache on your test site.

If the absolute URL in the menus is not specified directly on the menu items (through *Structure / Menus*) maybe it was embedded within the template and you'll have to search for the code on the .tpl files of your theme.
> 1 votes

# Answer
Go to your /sites/default/settings.php and check your $base\_url.

You can also try this: Log into your Drupal admin panel. Go to Configuration page. Click on URL aliases located under the Search and metadata section: Click Add alias button: Fill in the Existing system path and the Path alias. Save changes.
> 0 votes

---
Tags: 7, uri
---


title: CORS error in reading file

text:
# Question
Title: CORS error in reading file
I'm working on a headless website based on Drupal 8; I installed the CORS module and in CORS domain set `*|*`. Client side can read my view rest endpoint, but when client side try to load a file url returned by views rest result, I am faced with CORS error:

> XMLHttpRequest cannot load http://domain.com/sites/default/files/home-slider-slide3-audio/2016-11/tr\_SaidNursi.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xx.domain.com' is therefore not allowed access.

How can I resolve this problem?

The webserver is Nginx.

# Answer
As @ya.teck mentioned first it need handled by webserver so puting following lines in your site Nginx Configuration could help

```
add_header Access-Control-Allow-Origin '$http_origin' always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Headers 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
add_header Access-Control-Expose-Headers 'Authorization';

```
> 2 votes

# Answer
As this file is public the HTTP request is not served by Drupal. You need to configure your web server to send correct CORS headers. If you are using Apache and have *mod\_headers* installed you can set these HTTP headers in .htaccess file.

http://enable-cors.org/server\_apache.html
> 5 votes

---
Tags: 8
---


# Question
Title: Attach JavaScript and CSS assets when render entity using Views REST export
Goal:

1. Have a REST endpoint which will deliver list of rendered entities.
2. Each row should contain a ready-to-use HTML.
3. All the necessary JavaScript and CSS files should be also included on the page.
4. P.S. I need this endpoint for lazy-loading of entities.

Given:

1. I have a Views display with REST export.
2. I render entities there using the rendered\_entity field.

Problem:

1. JavaScript and CSS files, needed for rendering, are not attached on the page.
2. E.g. scripts for display of an image gallery, lazy-loading of images.

# Answer
> 1 votes
We came up with a new module: Ajax Assets Plus.

The module provides a new render which collects all the necessary libraries during rendering. It results in an array:

```
return [
      'commands' ['An array with ajax commands for settings'],
      'content' => 'Rendered content(HTML)',
      'libraries' => 'all the needed assets grouped into libraries',
    ];

```

We had to to override the `AjaxResponseAttachmentsProcessor` and `AssetResolver` classes.

Also we implemented the `hook_js_settings_build()` to collect all the libraries on the page, as `ajaxPageState` does not contain all the dependencies.

---
Tags: views, ajax, 8
---


# Question
Title: Attach JavaScript and CSS assets when render entity using Web Sockets
Goal:

Attach all the necessary JavaScript and CSS files to the page, when a rendered entity is delivered on a Web Socket event.

Given:

1. I have a Web Socket with an event when a new entity is created (Via pusher.com but nevermind).
2. The Web Socket delivers JSON with some meta-data(entity id, created date, title, etc.) and HTML of a single rendered entity.
3. I catch the event in and render the entity (I do it in JavaScript, client is the same Drupal website).

Problem:

JavaScript and CSS files, needed for rendering, are not attached on the page. (E.g. scripts for display of an image gallery, lazy-loading of images).

My ideas:

I think that I should list all the necessary JavaScript and CSS files (or something like ajax commands, which can attach assets) in the JSON, when I push the event. To achieve this I might need to rendered the entity via some Drupal-AJAX-Renderer.

Afterwards (when I receive the JSON from Web Socket) there should be some way on a Drupal website to attach these files by executing some JavaScript method in Drupal.ajax.

Currently I haven't figured out how to achieve this. Could you give some advice?

# Answer
> 0 votes
It was quite some work to adapt the rendering process. There is a lot of code, I will just summarise the solution. If you want more details, just write a comment.

The solution looks similar to my ideas/hypothesis in the question's description.

I created a custom render which collects all the libraries during rendering in an array. It results in an array:

```
return [
      'commands' ['An array with ajax commands for settings'],
      'content' => 'Rendered content(HTML)',
      'libraries' => 'all the needed assets grouped into libraries',
    ];

```

I had to to override the `AjaxResponseAttachmentsProcessor` and `AssetResolver` classes.

Also I implemented the `hook_js_settings_build()` to collect all the libraries on the page, as `ajaxPageState` does not contain all the dependencies.

At the front-end side it is not possible to attach all the assets by comparing `ajaxPageState` and the response from a Web Socket.

---
Tags: theming, 8, ajax
---