# Question
Title: How to pass a Flag field's value to a Rules Component triggered by the flag?
Assume a flag (created using the Flag module) which triggers a rule, using Rules Event "When something is flagged" (with this flag). And assume that this flag has 2 fields defined for it also, i.e.:

* "Date from", with machine name `field_flag_a_group_date_from`.
* "Date to", with machine name `field_flag_a_group_date_to`.

When such rule is triggered, assume it performs a Rules Component, which contains a Rules Action to "Send an eMail".

**Question**: How to pass the values of those Flag fields to that Rules Component, so that they can be used in the message body of that eMail?

# Answer
### Step 1 - Add parameters to the Rules Component

Make the "Date from" and "Date to" available as extra parameters to the Rules Component. Here is an example of such Rules Component (in Rules Export format, if you have the Rules UI enabled you can import it in your own site).

```
{ "rules_send_email_to_all_members_of_a_group" : {
    "LABEL" : "Send eMail to all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "flag_from_date" : { "label" : "Flag from date", "type" : "date" },
      "flag_to_date" : { "label" : "Flag to date", "type" : "date" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail \u0022[member-of-group:user:mail]\u0022 will receive an eMail because of flagging this \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and id \u0022[group:gid]\u0022 (with Date from = [flag-from-date:value] and Date to = [flag-to-date:value])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail since user [site:current-user] just flagged this group.\r\n\r\nFYI: the \u0022From date\u0022 (from the flag) is [flag-from-date:value] and the \u0022To date\u0022 (from the flag) is [flag-to-date:value] ...\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

The above Rules Component uses these 2 parameters (together with some other parameter "Group"):

* "Flag from date" (label), with machine name `flag_from_date`, and data type "Date".
* "Flag to date" (label), with machine name `flag_to_date`, and data type "Date".

Note how both parameters are shown within "USES VARIABLES" (that's where they are 'defined'). But also note how within the message body of the eMail both parameters are used (referenced), with any "`_`" in the machine name replaced by "`-`".

### Step 2 - Make the Flag fields available in the Rule

Before you can use the "tokens" related to the Flag fields in a Rules Action (as in Step 3 below), the Rule needs to be made aware about those Flag fields. To do so, simply add those 2 Rules Conditions in the rule that is triggered by Rules Event "When something is flagged" (with this flag):

* Entity has field, whereas the Data selector for the entity is "flagging", and the value of the field to check for is `field_flag_a_group_date_from`.
* Entity has field, whereas the Data selector for the entity is "flagging", and the value of the field to check for is `field_flag_a_group_date_to`.

### Step 3 - Pass the Flag fields values from the Rule to the Rules Component

After you completed Step 1, Rules "knows" that for any Rules Action that performs the Rules Component, it is required that a value is specified for those 2 parameters that the Rules Component needs (expects).

So if you add a Rules Action like "perform the Rules Component" (from Step 1) to your Rule (not Rules Component!), you will be prompted to specify a *Data Selector* for each of the 2 parameters (labelled "Flag from date" and "Flag to date"). Here is the trick to complete the rule (puzzle?): ***if you first completed Step 2*** (and only then!), you will be able to:

* use `flagging:field-flag-a-group-date-from` as the Data selector for the "Flag from date".
* use `flagging:field-flag-a-group-date-to` as the Data selector for the "Flag to date".

Here is an example of such rule, which passes the values of those Flag fields to the Rules Component that is performed in the Rules Action (in Rules Export format):

```
{ "rules_send_a_group_notification_by_flagging_a_group" : {
    "LABEL" : "Send a group notification by flagging a group",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_flag_a_group" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "flagging" ], "field" : "field_flag_a_group_date_from" } },
      { "entity_has_field" : { "entity" : [ "flagging" ], "field" : "field_flag_a_group_date_to" } }
    ],
    "DO" : [
      { "component_rules_send_email_to_all_members_of_a_group" : {
          "group" : [ "flagged-group" ],
          "flag_from_date" : [ "flagging:field-flag-a-group-date-from" ],
          "flag_to_date" : [ "flagging:field-flag-a-group-date-to" ]
        }
      }
    ]
  }
}

```

If you have the Rules UI enabled you can import this rule in your own site (after you adapted the machine names of the flag fields to fit yours).

Note the 2 Rules Conditions that were added in the above rule (as detailed in Step 2). And how those fields are then also used within the Rules Action that performs the Rules Component (from Step 1).
> 1 votes

---
Tags: 7, rules, flags
---


# Question
Title: How can I create a path auto pattern token based on a menu path without placing node in menu?
Here is the scenario:

We have a D7 multisite set up with an installation profile that we created so that all sites are basically managed with the same rules. But we do allow some flexibility... So we have a content type "News Article". Usually news articles won't be in the menu because there can be thousands of news articles on any given site. One site might want to put their news articles under the "News" menu item in the main menu. Some might call it "News Room". Since we're not forcing the parent path, I can't set "news" as a root path for all the nodes in path auto. And even more crazy, some site users might chose to place node A under News while node B is under About. I was thinking of some type of menu "parent" selector as if they were creating a menu item, without creating the actual menu item in order to generate the path. I thought the menu position module might be on the path I needed, but it turns out you have to create rules administratively and not on a per-node basis where the user is making the determination.

# Answer
> 0 votes
With the use of the Menu Reference module and hook\_pattern\_alter, I was able to get this accomplished. The code piece ended up looking like:

```
function custom_paths_pathauto_pattern_alter(&$pattern, array &$context) {
  if (isset($context['type']) && $context['type'] == 'news_article' && isset($context['data']['node']) && !$context['data']['node']->menu['enabled'] && $context['data']['node']->field_menu_path['und'][0]['mlid']) {
    $menuitem = menu_link_load($context['data']['node']->field_menu_path['und'][0]['mlid']);
    $menupath = drupal_get_path_alias($menuitem['link_path']);
    $pattern = $menupath . '/[node:title]';
  }
}

```

---
Tags: path-aliases
---


title: Entity form additional arguments

text:
# Question
Title: Entity form additional arguments
I have normal Drupal8 Content entity, and I'd like to set up some additional arguments for the entity form builder.

Ie I have entity form path like so: */tilaus/uusi/{tilaus\_type}* and I'd like to add additional parameter, like so: */tilaus/uusi/{tilaus\_type}/{some\_additional\_argument}*. Preferably in a way that would have both of those urls working and I could handle the missing argument in buildForm method.

I've been searching for a while now, but can't find anything about adding stuff to entity form paths. Normal forms are fine and I know how to handle those. It seems that I just can't figure out the entity routing.

So: How to add additional arguments to entity form url and builder?

Cheers,

Janne

# Answer
> 2 votes
An entity add form is built with a new entity. And when you create this entity you can use parameters for this. See this example from the block module.

The new route with the additional parameter:

**block.routing.yml**

```
block.admin_add:
  path: '/admin/structure/block/add/{plugin_id}/{theme}'
  defaults:
    _controller: '\Drupal\block\Controller\BlockAddController::blockAddConfigureForm'
    theme: null
    _title: 'Configure block'
  requirements:
    _permission: 'administer blocks'

```

This adds the parameter `theme`.

And the controller for this route:

**BlockAddController.php**

```
 public function blockAddConfigureForm($plugin_id, $theme) {
    // Create a block entity with prepopulated values.
    $entity = $this->entityManager()->getStorage('block')->create([
      'plugin' => $plugin_id,
      'theme' => $theme,
    ]);

    return $this->entityFormBuilder()->getForm($entity);
  }

```

Here the additional parameter `theme` is used when creating the entity.

Using both routes at the same time is no problem, the standard entity route configured in the entity annotations will still be in place.

Another way to use parameters in entity forms is in the third parameter `$form_state_additions`:

```
$form_state_additions['langcode'] = $langcode;
$form = \Drupal::service('entity.form_builder')->getForm($entity, 'default', $form_state_additions);

```

This example is from the source of the entity formbuilder:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityFormBuilderInterface.php/8.2.x

# Answer
> 2 votes
You can access any request parameter directly in form builder as follows:

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

  $some_additional_argument = $this->getRequest()->get('some_additional_argument');

}

```

# Answer
> 1 votes
You are asking two questions here. I've tried to answer both in general terms for all forms, and provided specifics for entity forms which are a bit special.

# 1. How do I handle options parameters in routes?

This is fairly simple, you can provide a default value for the route, say you had a routing file looking something like this

```
some.route:
  path: '/foo/{bar}/{baz}'
  defaults:
    baz: 42
  ...

```

using `defaults` you can specify default values for the parameters. You can specify as many default values as you like, and Drupal will catch it, when there is no more unknown parameters. In the above example you would need to specify a value for `bar` so

* `foo/some-value`
* `foo/some-value/42`

would both give same result

# 2. How do I add additional parameters to en (entity) form?

## Solution a

There are two ways to do this. You can add additional parameters in `getForm` on the form builder which will be available in the `::buildForm` method. The `EntityFormBuilder` is a bit special in that it already has some support for this, the 3 argument to get form is array with data, which will be added to FormState which is used for `::buildForm` and `::form`

In code (for entity form class) it looks like this

```
$form = \Drupal::service('entity.form_builder')->getForm($entity, 'default', ['bar' => 'some_data']);

```

and in the entity form class

```
public function form(array $form, FormStateInterface $form_state) {
  $storage = $form_state->getStorage();
  $storage['bar'] == 'some_data';
}

```

## Solution b

The other method is often a bit more complex. Instead of using the entity form build, you can instantiate the form class and add whatever you want in the `::__construct`. Entity forms are are bit special as they don't have constructors, instead they have setters and a method to get the form class.

In code you entity forms, it could look like this

```
$form_object = \Drupal::entityTypeManager->getFormObject($entity_id, $operation);
$form_object->setEntity($entity);
$form_object->setCustomValue($value);
$form_render = \Drupal::formBuilder->getForm($form_object);

```

The advantage with this latter method, is that the data you add to the form class, will be available in all method calls. One issue could be that you need to display multiple variations of the same form on the same page. For Drupal to do this, they need a unique form id, which could be handled in the `getFormId` method. Or maybe you need to use a service, where it would be messy to use the form building method to store it some where and pass it through the submission process.

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


# Question
Title: How can I get a checkbox to return True/False?
I'm working with the form API and I have a series of checkboxes. I need them to return `true` or `false` instead of `1` and `0`.

```
$form['checkbox1'] = array(
    '#type' => 'checkbox',
    '#return_value' => 'true',
    '#title' => t('Checkbox title'),
    );

```

This works if the box is checked, but if it's left unchecked it still returns `0`. Is there a way I can get an unchecked box to return `false`?

# Answer
It depends how you want to use the true/false value.

**Case 1**

You could change the data in a validation handler. In hook\_form\_alter, something like:

```
$form['#validate'][] = 'my_great_handler';

```

Then:

```
function my_great_handler($form, &form_state){
  $form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value']
    = ($form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value'] == 1);
}

```

Not sure what that would do for you, though.

**Case 2**

If you want to show users true/false rather than 1 or 0, you could change that in a template. Create a template for the field, and add something like:

```
Checkbox: <?php print $checkbox1 == 1 ? 'True' : 'False'; ?>

```

**Case 3**

If you want to save the data in a custom data store, you would add similar code right before the save, in hook\_node\_save, or some such.
> 4 votes

---
Tags: 7, forms
---


# Question
Title: Drush bootstrap fail - wrong MySQL username
`drush sql-connect` produces valid, working MySQL credentials:

> mysql --user=drupaluser --password= --database=core\_20161101 --host=127.0.0.1 --port=33067

So does `drush status`:

> Database driver : mysql
> Database hostname : 127.0.0.1
> Database port : 33067
> Database username : drupaluser
> Database name : core\_20161101

However `drush -d uinf admin` and anything else that needs to read the database fails with:

> \[...\] sql-query: SELECT 1; \[0.35 sec, 4.88 MB\]
> \[notice\] Executing: mysql --defaults-extra-file=/private/tmp/drush\_dZeMQb --database=core\_20161101 --host=127.0.0.1 --port=33067 --silent \< /private/tmp/drush\_Tu2o2g ERROR 1045 (28000): **Access denied for user 'root'@'localhost'** (using password: YES) Bootstrap to phase 1. \[0.37 sec, 4.88 MB\]
> \[bootstrap\] Bootstrap to phase 6. \[0.54 sec, 6.68 MB\]
> \[bootstrap\] Bootstrap to phase 5. \[0.54 sec, 6.68 MB\]
> \[bootstrap\] Command user-information needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. \[0.54 sec, 6.68 MB\]
> \[error\] The drush command 'uinf admin' could not be executed. \[0.54 sec, 6.68 MB\]
> \[error\] Drush was not able to start (bootstrap) the Drupal database. \[...\]

Note the username is wrong, root@localhost, not drupaluser@127.0.0.1.

Any ideas why it would be switching to the wrong username?

**Versions:**
Acquia Dev Desktop 2 (built Sep 5 2016)
PHP 5.5.33 (as set by Dev Desktop)
Drush 8.0.5
Mac OS 10.11.6

# Answer
You don't happen to have a `~/.my.cnf` file (which sets the user to root)? MySQL will read that file after the file specified by `--defaults-extra-file`, and "If multiple instances of a given option are found, the last instance takes precedence".
> 4 votes

---
Tags: drush, acquia-dev-desktop
---


# Question
Title: How to change commerce order owner to someone else?
I create a commerce order for a spesific user prograticaly by admin user, after completing checkout process by admin, I want to change owner of order to someone else to show created order in order history of spesific user I changed the uid of order but does not work for me.

# Answer
> 1 votes
-\> If you want to do programatically, then Load Order as $order = commerce\_order\_load(1); $order-\>uid = 4; commerce\_order\_save($order);

-\> By admin UI Edit order and in User Information, specofy username of user you want to assign and save.

---
Tags: commerce
---


# Question
Title: Local Drupal installation can't copy files to another computer on network
I want to use file\_copy to copy a file from Drupal public directory to a shared folder of another

computer on the same network. I can access the shared folder by Finder (Drupal is installed on

MAMP) but coping files in that directory gives me the same error:

> The specified file public://file.pdf could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

The shared folder is totally writable. I tryed putting an alias on httpd.conf but no luck Could it be an apache permission problem? Or can I solve the problem within Drupal?

Thanks a lot

# Answer
> 0 votes
Go to the MAMP console under "**General**" tab, go to the setting for "Run Apache/MySQL server as user".

It should be setting to **www (Apache) / mysql (MySQL)**. So you need to change it to **username (Apache) / username (MySQL)**.

Save and restart the servers

Refresh the browser, then change it back to **www (Apache) / mysql (MySQL)**, save and restart, and everything should be working

---
Tags: files
---


# Question
Title: Select field descriptive or numeric keys
I have created a field of type `List (text)` with widget `Select list`. After editing most of its settings, it came to complete its `Allowed values list`. Following the help's text instructions, the values should have this form `key|label` and here is my question:

Should I use descriptive or numeric keys for the values (and why)?

> The `key` is the stored value

Does this (keys) selection will have any impact in the future if for example I want to use these values for aggregation (with views or not)?

# Answer
The `key|label` format is for scenarios where you want to present a different, user-friendly, label that differs from the underlying, machine-readable, storage. For example, a country select list that you want represent in the 2-character ISO 3166-1 format while showing the official country names to present to the user selecting it.

In the above scenario, regardless of using the `key|label` format or not, the underlying data will be represented as a string (`VARCHAR`) since it's a *Field (text)* field type. If your underlying data needs to be represented as numeric, then you should use the *List (Integer)* (or other number types) field type as it will be stored as `INT` within the DB column.
> 1 votes

---
Tags: entities
---


# Question
Title: How can I modify the $submitted variable for a custom node template?
I have a content type called "Blog post" (machine name = blog\_post).

I've set up a custom node template that works properly called "node--blog\_post.tpl.php"

I'd like my $submitted output to be "by User Name | Month, Day of Month, Year" (example - "by John Smith | November 2, 2016"

I've been working on this for 2-3 hours without being able to have *any* effect on the output, and have gotten to the point in my searching where the only links I'm finding that seem relevant are things I've already clicked on. I'm stuck.

I know there are multiple ways to do this, but I'm looking for how to make this happen using a theme\_preprocess\_node function in the template.php file. Not only because I've seen multiple posts saying this is the "best practice", but also to gain more familiarity with the template.php file itself & how it is used.

Any thoughts?

# Answer
You can do this.In your theme\_preprocess\_node function create a new variable which is used in your node--blog\_post.tpl.php .

```
 function yourtheme_preprocess_node(&$variables) {
 $node = $variables['node'];
  if ($node->type == 'blog_post') {
    $created = $node->created;
    $date = date('F j,Y', $created);
    $name = $node->name;
    $variables['new_variable'] = "By ".$name." | ".$date;
  }
}

```

then print this new\_variable in your tpl like this.

```
  <div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
  print $new_variable;
?>

```

Output show like this
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to catch username or password using hook_form_alter
I need to catch username/password using the `hook_form_alter()`. I'm using this code:

```
function sds_form_alter(&$form, FormStateInterface $form_state, $form_id ) {

  if (in_array($form_id, ['user_login_block_form', 'user_login_form'])) {
    $username= $form_state->getValue('name');
    echo "Username Value".$username;
  }

}

```

but it returns `null`. What am I missing here?

# Answer
> 3 votes
You can use in VALIDATE function like

```
$form['#validate'][] = 'mymodule_user_validate';

```

In this you can all values even if there is no successful values in it. But remember to call your function first before default validate function.

# Answer
> 1 votes
When `hook_form_alter()` is invoked, the form has not been submitted yet, so you cannot get any value from `$form_state`. You need to add a form submission handler, and from that get the username.

```
$form['#submit'][] = 'mymodule_user_submit';

```

If you are, instead, trying to get the default value set in the form, then you should use the following code, in your `hook_form_alter()` implementation.

```
$default_name = $form['name']['#default_value'];

```

It would still return an empty value, since Drupal doesn't set a default value for the username, but that is the correct code to get the default value of a form element from `hook_form_alter()`.

---
Tags: forms, 8
---


# Question
Title: How to disable stripping tags for View header?
I have created an view and set its header to:

```
<div class="filters">
    <strong>Filters</strong>
    <select><option value="Select filter" disabled default">Select filter</option></select>
</div>

```

But when I access it (via block created from view and placed anywhere on website) I get:

```
<div class="filters">
    <strong>Filters</strong>
    Select filter
</div>

```

So how to prevent Drupal 8 from stripping those form tags?

# Answer
> 1 votes
Please got to the view you have created and follow the below steps :

1. Header \> Add \> Type "Text area" in Search
2. Select Text area \> Add and configure header
3. Under the content insert

> ```
> <div class="filters">
>     <strong>Filters</strong>
>     <select><option value="Select filter" disabled default">Select filter</option></select>
> </div>
>
> ```

4. Dont forget to change the Text format to Full HTML and click on save

---
Tags: views, forms, 8
---


# Question
Title: How do I alter a template file in a multishared child-site?
The site I am working on is the child-site (is that the correct terminology?) of a larger parent site.
The company I am working with uses the main, parent site as a sort of framework or base. It has a basic theme that the child sites use and build off from.

I want to alter the HTML of a pane element. The original template file for this is located back in a module directory of the parent site. There is no equivalent module or folder structure on the child-site.
I don't want to change the template file on the parent site as this would affect the other child-sites.

I've read up that you can copy the template and place it into the child-sites structure. Is this true?
If so, would I need to re-create the directory path to replicate that of the parent site's?
What's the correct way to go about this?

# Answer
This is a bit tricky since normally template files are located in the Theme's folder and not in a module's folder.

You could create a `/modules` folder under yourchildsite.com folder and copy the parent site module and paste it there. Then modify what you need.

I am not 100% sure this will work, but I hope it does.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How do I filter an entityreference field based on other fields?
So I'm trying to create a node that has an entityreference to another node. THing is I need that field to filter the data from an entityreference view based on three use cases.

1. New content. Should only show referenced nodes created by the same user.
2. Editing created content. Should only show referenced nodes created by the person who created the edited node
3. New Content as Admin - An administrator/editor should be able to add content under another users name, and it should filter and show nodes created by that user.

I've got 2 out of three but I'm not sure how to get the last one done.

# Answer
Your question reminds me of this similar question you may or may not find it relevant.

Alternatively, you could use Masquarde

> The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.

Video Tutorial
> 0 votes

---
Tags: entities, views
---


title: Enable CKeditor on Webform's textarea

text:
# Question
Title: Enable CKeditor on Webform's textarea
I'm trying to create a contact form supporting HTML formatting with Webform and CKEditor. So I created a new webform with a single field of type Textarea and now I have a simple webform with the basic textarea.

How can I enable rich text formatting on this form? It doesn't work by default and I cannot find any option to enable it neither in Webform nor CKeditor settings.

# Answer
Webform HTML Textarea

Try this module.
> 0 votes

---
Tags: webforms, wysiwyg
---


# Question
Title: How to show field collection items with comma separated in views?
I have profile type *programmer*. This profile type having a field 'field\_collection' type named language.

In the field collection we have two fields

1. Language
2. Year of experience

Now I am going to create a view that will show all the users associated with that profile type(*programmer*). I want to add an field(language) in that view which will have all the languages with comma separated.

NOTE : I don't want to show '*year of experience*' in the field, just want to show the '*language*' only. Ex : C++, PHP, JavaScript

# Answer
The basic setting for fields with multiple values actually has that as default. When you are adding the field into your view click on the multiple field settings tab and it will show you the functions to do just this.
> 0 votes

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


title: Bootstrap horizontal form layout

text:
# Question
Title: Bootstrap horizontal form layout
In Bootstrap there is a nice horizontal form option. But in Drupal + Bootstrap base theme I couldn't find any ways to use this horizontal forms and layout form elements as it described, eg. col-2 for labels and col-10 for inputs.

The only way I found is Strapped theme (https://www.drupal.org/project/strapped) but it is in dev stage and I don't need one more base theme.

Bootstrap is so popular along with horizontal forms and I don't want to believe there is no way to solve this problem.

Or everybody uses `hook_form_alter()` and render horizontal form somehow in code?

Thanks in advance.

# Answer
> -1 votes
Can you paste an example here with the code that didn't work for you?

Did you respect the structure below?

```
<div class="form-group form-item form-item-example-input form-type-textfield">
  <label for="edit-example-input" class="control-label col-md-2">Enter long URL: </label>
  <div class="col-md-10">
    <input type="text" maxlength="100" size="60" value="http://" name="example_input" id="edit-example-input" class="form-control col-md-10 form-text" tabindex="1">
  </div>
</div>

```

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


# Question
Title: Issues removing text decoration from links in a custom block
I'm replacing the Bartik menu with a custom one. To do this, I'm building a custom block and placing it appropriately.

That all works. However, I am having issues with Text Decoration: No matter what I try, I cannot remove the line from under links, and I have also noticed a "Doubled/offset" text look. When I edit the code on 'Tryit', everything looks fine; when I unclick 'source' in the block editor, everything also looks fine.

When I update the page, I see these issues.

My entire block code is the following one.

```
<style type="text/css">body {margin:0;}
    ul.topnav {
      font-weight: normal;
      text_decoration: none;
      list-style-type: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #333;
    }

    ul.topnav li {
      display: inline-block;
    }

    ul.topnav li a {
      display: inline-block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      transition: 0.3s;
      font-size: 17px;
    }

   ul.topnav li a:hover {background-color: #555;}

   ul.topnav li.icon {display: none;}

   @media screen and (max-width:680px) {
     ul.topnav li {display: none;}
     ul.topnav li.icon {
        display: inline-block;
      }
    }

    @media screen and (max-width:680px) {
      ul.topnav.responsive {position: relative;}
      ul.topnav.responsive li.icon {
        position: absolute;
        right: 0;
        top: 0;
      }
      ul.topnav.responsive li {
        float: none;
        display: inline;
      }
      ul.topnav.responsive li a {
        display: block;
        text-align: left;
      }
    }
    </style>
    <ul class="topnav" id="myTopnav">
        <li><a class="active" href="#home">Home</a></li>
        <li><a href="#gallery">Gallery</a></li>
        <li><a href="/contact">Contact</a></li>
        <li><a href="#extra">Extra</a></li>
        <li class="icon"><a href="javascript:void(0);" onclick="myFunction()" style="font-size:15px;">☰ Menu ☰</a></li>
    </ul>
    <script>
    function myFunction() {
        var x = document.getElementById("myTopnav");
        if (x.className === "topnav") {
            x.className += " responsive";
        } else {
            x.className = "topnav";
        }
    }
    </script>

```

Here is an image of the issue:

Notice both the underline, and the 'Doubled text'? Thats what Im trying to get rid of. Thank you in advance.

# Answer
> 0 votes
For the text-decoration, try to use !important attribute.

For that "doubled text", you need to use text-shadow: none.

If text-decoration still doesn't work, you can try border-bottom: none for that line, too.

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


# Question
Title: CKEditor placeholder text doesn't work (config.js)
I'm trying to add placeholder text to my ckeditor screen like for example `Type here ...` . You can do this with the configuration helper plugin.

I've placed the ckeditor library in `sites/all/libries`. I've pasted the plugin in `sites/all/libraries/ckeditor/plugins`. Then I've added the following code to my **config.js** (in ckeditor folder).

```
CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';
    config.extraPlugins='confighelper';
    config.placeholder = 'Type here...';
};

```

But this doesn't work. The **config.js** isn't added to my page when there's a ckeditor. The code is also not in **ckeditor.js** (which is loaded on the page, I thought that the plugin maybe added it to the file).

I've also tried to add the code to my **script.js** which is **always** loaded like this:

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.my_custom_behavior = {
      attach: function(context, settings) {
        CKEDITOR.editorConfig = function( config ) {
          // Define changes to default configuration here. For example:
          // config.language = 'fr';
          // config.uiColor = '#AADC6E';
          config.extraPlugins='confighelper';
          config.placeholder = 'Type here...';
        };
      }
    };
})(jQuery, Drupal, this, this.document);

```

But still no result... . I'm using `CKEditor 4.4.2.1567b48` . Text format is filtered html. The ckeditor works but I can't add any plugins (I would also like youtube plugin). Also cleared my cache a couple of times.

Am I doing something wrong?

# Answer
> 1 votes
A solution that avoids patching the wysiwyg module is the following:

You can use the hook `hook_wysiwyg_plugin($editor, $version)` that wysiwyg offers, in order to add the ckeditor plugin, as follows:

```
function custom_wysiwyg_plugin($editor, $version) {
  $plugins = array();
  switch ($editor) {
    case 'ckeditor':
      $plugins['confighelper'] = array(
        'extensions' => array('confighelper' => t('Configuration Helper')),
        'url' => 'http://ckeditor.com/addon/confighelper',
        'load' => TRUE,
        'internal' => TRUE,
      );
      break;
  }
  return $plugins;
}

```

Then, go to the wysiwig profile edit page and enable the Configuration Helper plugin.

After that, placeholder text will be shown in the wysiwyg ckeditor.

# Answer
> 0 votes
I'm assuming you are using wysiwyg with ckeditor.

The problem is that wysiwyg pass the configuration to the editor, in our case ckeditor, based on the options selected on the wysiwyg profile in use.

The solution i found sure it's not the best buts works for me. It's about modifying the wysiwyg file thats sets the configuration for ckeditor.

Open `site/all/modules/wysiwyg/editors/ckeditor.inc` and find the function `wysiwyg_ckeditor_settings`, then, before the code implode the $extra\_plugins array add your extra plugins.

before:

```
if (!empty($extra_plugins)) {
  $settings['extraPlugins'] = implode(',', $extra_plugins);
}

```

add:

```
$extra_plugins[] = 'confighelper';

```

result:

```
$extra_plugins[] = 'confighelper';
if (!empty($extra_plugins)) {
  $settings['extraPlugins'] = implode(',', $extra_plugins);
}

```

Hope it helps.

---
Tags: 7, javascript, wysiwyg
---


title: Unable to Edit Main Navigation Drupal 8

text:
# Question
Title: Unable to Edit Main Navigation Drupal 8
I installed a custom theme called StartupGrowth. At the moment, I am trying to edit the main navigation. When I go to Structure-\>Menus-\>Main Navigation and disable the unneeded entries, they do not disappear from the navigation. However, if I add a new entry to the menu, it does appear. What's more, when I attempt to delete the entry added by me, it persists in the navigation just like the other ones.

What am I missing? Is there another place for editing this menu? Or does this sound like a bug in the theme itself?

# Answer
> 1 votes
It's kinda hard to test for the ones not having this theme.

Looking at the demo for the theme I can see it is using Superfish module to display this menu.

So, after removing the menu element try to flush the cache (from /admin/config/development/performance). If still doesn't work, go check on Structure-\>Blocks and see the superfish block... click on configure and be sure it is using the same menu. You have more settings in there, and you can look into the module (Superfish) settings, too.

---
Tags: theming, blocks, navigation
---


# Question
Title: Get result view with formatter programmattically
Example a view with show fields:

I want retrive array result like this:

```
[
  [title,
   date_start
   data_end
   ...
  ]
]

```

# Answer
Use `$view->result` to get the filtered rows, `$view-field` for the fields, on which you can use the methods `getValue()` for the field value and `render()` for the formatted field as render array.

An example:

```
use Drupal\views\Views;

  $values = [];
  $view = views::getview('view_example');
  if ($view) {
    $view->execute();
    foreach ($view->result as $rid => $row) {
      foreach ($view->field as $fid => $field ) {
        $values[$rid][$fid . '-value'] = $field->getValue($row);
        $values[$rid][$fid . '-render'] = $field->render($row);
      }
    }
  }

```
> 2 votes

# Answer
You can use the field "global text" and add all fields inside of this field for show all fields that you have in one field

I hope can help you
> 0 votes

# Answer
Does this work?

1. Exclude all the fields from display except the last one.
2. Be sure to have the Token Module installed and enabled.
3. Rewrite the output of the last field with the tokens of the needed fields and your array formatting: `[[title],...]` The available patterns should be visible below.
4. Adjust the output to your needs and through the rewrite of the last field with the tokens or the formatting of the excluded fields (perhaps necessary for the format of dates and strings).
> 0 votes

---
Tags: views, 8
---


# Question
Title: Views - Protect user-assigned content from direct url access
I'd like to create a restricted area from scratch using views.

## What I'd like to achieve:

* The admin creates a photo album and assigns it to a photographer
* A photographer is able to log into the site, and see a list of albums that are assigned to them
* The photographer can upload photos to the album
* If a non logged user tries to access the album by typing its url, they get rejected
* Ideally, photos (the files themselves) that are in an album are also protected, I know that file access restriction is a complex subject, but I'm okay with a sort of proxy-page that would then redirect to the file with an unguessable url, or a solution of this type.

## Where I am so far:

* **Create a user role** Photographer
* **Create a content type** album with fields:
    + Photographer (user reference, role=photographer)
    + Photos (file, number of values unlimited)
* **Create a view** to list content type=album, with a **contextual filter** on the Photographer field that defaults *to current user id* when not provided in the url. So that a logged photographer only sees their own albums. That works fine.

## My problem:

* Anyone can enter an album's url and access it directly \[solved\]
* Anyone can enter a photo's url and download it \[solved\]

I've built this on drupal 8 but can also use drupal 7 and other modules. Any help would be very much appreciated!

---

### Update:

I think I found part of the answer. Using private directory with the files module: https://www.drupal.org/documentation/modules/file. According to the docs:

> For example: you have created a new content type with a file field which stores files in your site's private file directory. Next you create a node from this new content type and attach two new files. When the node is published links to both attached files are visible and anyone who can view the node may download the files. Now, if you unpublish the node, all attached files become inaccessible for download even if you use the direct link to the files that worked when the node was published.

# Answer
So I ended up using Drupal ACL Module which allows to grant access to a node to a group or user. This way, if one tries to access the node by entering its url, they get rejected: https://www.drupal.org/project/acl

I also made use of Drupal protected node to allow node access via password without being logged: https://www.drupal.org/project/protected\_node

And I implemented a few Rules with drupal rules: https://www.drupal.org/project/rules
> 0 votes

# Answer
Have a look at the Group module which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also.

The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources
> 1 votes

---
Tags: users, views, files
---


title: Questions about Blocks and Menus

text:
# Question
Title: Questions about Blocks and Menus
I'm new to Drupal, so bare with me...

I created a menu that I placed inside the Sidebar First Region.

1st question: I was able to place my menu in the Sidebar First Region by going to the blocks page "admin/structure/block". Is a menu seen as a block, since i am able to assign a region for a menu inside the BLOCKS page ? or is just the name of the page misleading, since it can take care of both blocks and menus ?

2nd question: How can i import/export a menu that has a bunch of links inside it ? i want to export it from local to staging and prod. Features doesnt seem to work? i found menu Block and menu\_import to say to be able to do that, but is there another easier or better way ?

Any other suggestions and tips are more than welcomed...

Thanks

# Answer
> 1 votes
1. A menu is not a block, it's just a collection of links... but the core menu module from Drupal renders the menu as a block to be easier for you to place it in the page and change its location.
2. There are multiple ways to export or import a menu. Yes, features module is one of them, but for a beginner I would suggest a module only for this, it should be easier. You can try this module.

---
Tags: blocks, importing-exporting, features
---


# Question
Title: Menu on mobile phone - How to directly show second level of menu?
Following configuration: Drupal 7, tb corpal theme, superfish menu

For mobile phones I get a menu as shown in the image. If I press the menu icon (1, red on image) I get first the "Main menu" level (2, red on image). After pressing "Main menu" the menu expands and one gets to the desired next level.

What do I have to change to get directly to the "second level" after "Main menu" level?

# Answer
You can force the desired behavior via CSS or via Javascript (jQuery). For instance, check with jQuery if main menu is displayed on mobile. If so, then display its children, too. The CSS way would work if "main menu" is displayed by adding a class. If so, then you can, from CSS, display the second level when that class is present.
> 0 votes

---
Tags: routes, theming
---


title: How to translate Views exposed filters?

text:
# Question
Title: How to translate Views exposed filters?
I know you can translate a views title pretty easy as answered here: How do I translate a view page title?

Unfortunately I can't find a way to translate exposed filters buttons and labels properly. Using Drupal's `User interface translation` does never index those strings. Is there any known way (other than preprocessing the view to display translatable markup programmatically)?

# Answer
> 6 votes
Follow the procedure in the linked answer, which is, install the module *Configuration Translation* and add a translation to your view. Then you'll find these translation options:

**EXPOSED FORM**

**FILTERS**

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


# Question
Title: Fatal Error: Call to undefined function in a drush backup module
I am getting a weird error when attempting to use Drush.

> Fatal error: Call to undefined function `variable_get()` in /home/1000/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc on line 29
> Drush command terminated abnormally due to an unrecoverable error.
> Error: Call to undefined function `variable_get()` in /home/1000/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc, line 29

I have disabled and removed the xmlsitemap module, but it looks like it is referencing some weird backup version of the module.

# Answer
The function `variable_get` doesn't exist in Drupal 8. I suggest just removing `~/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc` or moving `~/.drush/backups` to `~/.drushbackups` if you can control this.

Your problem is probably caused by the fact that you are putting the backup inside the `~/.drush` directory and Drush is parsing code/files in that directory.
> 1 votes

---
Tags: drush, xml-sitemap
---


title: Overriding views fields in twig

text:
# Question
Title: Overriding views fields in twig
I want to override the default `views-view-fields.html.twig` so that I can display specific fields in a bootstrap layout, e.g.

```
<div class="col-sm-3">{{ fields.field_name_1 }}</div>
<div class="col-sm-6">{{ fields.field_name_2 }}</div>
<div class="col-sm-3">{{ fields.field_name_3 }}</div>

```

We have all this important code in that file that gets repeated for each field in the loop: -

```
{{ field.separator }}
{%- if field.wrapper_element -%}
  <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
{%- endif %}
{%- if field.label -%}
  {%- if field.label_element -%}
    <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
  {%- else -%}
    {{ field.label }}{{ field.label_suffix }}
  {%- endif %}
{%- endif %}
{%- if field.element_type -%}
  <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
{%- else -%}
  {{ field.content }}
{%- endif %}
{%- if field.wrapper_element -%}
  </{{ field.wrapper_element }}>
{%- endif %}

```

So I want to avoid having to repeat this over and over for each field that I manually arrange. What's the best approach here? I tried overriding the `views-view-field.html.twig` files but I can't seem to get to the same variables.

What's the best approach?

Thanks :-)

# Answer
> 0 votes
I have a similar issue! However, **I am able to print specific field values in `view-view-field.html.twig` by using the syntax `{{ view.field.[filed_name].original_value}}`.<br>In my cause it was `{{ view.field.title.original_value}}`.**

The issue I have is the each title is coming up 4 times! I don;t know how to fix. I also overrode `views-view-fields.html.twig` to add my own `HTML wrapper` outside the loop:

```
<div class="col-md-3 col-sm-3 col-xs-12">
    <div class="box box-white teaser-box">
      {% for field in fields -%}
        {{ field.separator }}
        {%- if field.wrapper_element -%}
          <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
        {%- endif %}
        {%- if field.label -%}
          {%- if field.label_element -%}
            <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
          {%- else -%}
            {{ field.label }}{{ field.label_suffix }}
          {%- endif %}
        {%- endif %}
        {%- if field.element_type -%}
          <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
        {%- else -%}
          {{ field.content }}
        {%- endif %}
        {%- if field.wrapper_element -%}
          </{{ field.wrapper_element }}>
        {%- endif %}
      {%- endfor %}
    </div>
</div>

```

which is rendering well on the page, but I cannot get rid of multiple title issue. Any suggestion would be greatly appreciated.

Here is a screenshot of how my page looks now:

---
Tags: views, theming
---


# Question
Title: How do i increase length of existed link title field in Drupal 8?
I want to increase the length of existed link title field. As matter of fact already have data in that field and don't want to lose.

Any suggestion? How can I do that nicely in Drupal 8. thanks

# Answer
What you can do is this:

1. Create new link field
2. Update configs, like form display, views etc to use new field.
3. Migrate all the data to the new field, in an update hook. Example code could look like this (Assuming link field is on a node)

```
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'node_type');
foreach ($nodes as $node) {
  $node->new_field = $node->old_field;
  $node->save();
}

```
4. Delete old field.
5. Done

Alternately you can update field field, manually update the SQL tables etc, but this is quite tricky to do properly. If you want to go down this road you should take a look at the `entityDefinitionUpdateManager`.
> 1 votes

# Answer
Because you have already added data in that field, Drupal won't let you modify the length. So, I would suggest you to go directly into your database and change the length from there.
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: How to export Group module entities with the Features module?
I'm trying to find a way in D7 to export groups created with the Group module using the Features module. I have managed to export Group Types and Group Roles, but haven't found a way of doing the same with Groups.

I need to do this to create an initial set of groups when the feature is enabled.

Any help greatly appreciated!

# Answer
Have a look at the UUID Features Integration module, which provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. It depends on the UUID and Features module. Some more info aboout this module(from its Community documentation):

> Drupal's core entities are supported by default within the UUID module, but if you want to export content contained within ***custom entities***, you will have to implement UUID support using their API.

The challenge with the UUID Features Integration module is that its documentation is not complete (yet). So for adding UUID Features support for custom content entities (such as ***Groups***), refer to the module's includes/ folder and use one of the existing implementations as an example.

2 more documentation issues that may be of some help also:
> 0 votes

---
Tags: 7, features, group
---


title: Drupal Local and Dev Database

text:
# Question
Title: Drupal Local and Dev Database
I have a Drupal Environment that deploys to GitHub as well as my server. The only issue is I have local database credentials and server database credentials. For now when I do my merge/push, I have to manually change the settings file to make sure I don't connect to the server db and make local changes.

Is there a way to connect to a local database when appropriate and a server database any other time. I tried to use a different connection in the settings.local.php file, but it didn't seem to work.

# Answer
in your settings.php, uncomment

```
# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

```

so it looks like this:

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

```

then in the same directory edit the settings.local.php to have your local settings.

Then add settings.local.php to your .gitignore file

That way, you can keep local settings that differ from the settings on dev.

So your dev server would have it's own unique settings.local.php file that differs from your local settings.local.php file.

If you need to check your database settings, you can add this at the bottom of settings.php

```
dump($databases); die();

```

You should see your correct settings (you can do this on both your local and your dev site to verify, then remove the dump command once you have verified.
> 6 votes

---
Tags: 8, database, configuration
---


# Question
Title: How to set #value to the form item from HTML data-*?
In product.tpl.php I have a code like this:

```
<div class="paint-order" data-pid="<?php print $node->field_product_ref['und'][0]['product_id']; ?>">

```

With JQuery I can get this product\_id with this code:

```
var paint_id = new Number($('.paint-order').data('pid'));

```

I create ctools popup form, and want to fill #value of form element

```
$form = array();
$form['form_wrapper']['buy_art_buy_one_click_product_id'] = array(
  '#type' => 'value',
  '#value' => (string) htmlspecialchars(insert ['product_id'] here),
);

```

What I must to use instead of 'insert \['product\_id'\] here' to get value of data (or other) HTML-attribute?

# Answer
> 1 votes
I solved this task with `Drupal.behaviors` in js-file

like that:

```
Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
        var paint_id = new Number($('.paint-order').data('pid'));
        $(context).find("[name='mymodule_product_id']").val(paint_id);

    }
}

```

---
Tags: forms, ajax, chaos-tool-suite
---


# Question
Title: How to make the node author's email show up as a replacement token in a Rules Action?
I have set up a rule that is as follows:

* **Rules Event**: After saving new content of type Article.
* **Rules Conditions**: User has role(s), with role = Authenticated user.
* **Rules Actions**: Send mail to all users of a role, with role = Administrator.

When anyone adds an article to the site, all the admins are notified and I have used token replacements for the email fields like so:

* **Mail Subject:** \[node:author\] has just created a piece of content entitled "\[node:title\]"
* **Message Body:**

\[node:author\] has just created a piece of content entitled "\[node:title\]"

You can see the article here and proof read: \[node:edit-url\]

The article is here: \[node:url\]

This all works perfectly, however I want to also add the author of the node into this email so that any of the admins can email this person if they need to. I cannot work out how to get the author's email into the email body as it doesn't seem to show up in replacement patterns.

Anyone any idea how I can achieve this?

# Answer
> 1 votes
It is not listed among the replacement tokens, but you can use the \[node:author:mail\] token.

# Answer
> 1 votes
The Rules module is great, but it also has its hidden features ... ***Yes*** the "*token for the eMail Id of the node author*" is available to use it in the Rules Action (as in this question here). However you won't find it by simply expanding the typical "**`REPLACEMENT PATTERNS`**"-link that show up by default.

Instead, whenever you're looking for some token that at first doesn't seem to be available, you should try to use the `Switch to data selection` button as in this screenprint:

Then select "`node...(Created content)`" from the **Data selector** selection list (or if you know part of what you're looking for just start typing "`node:`"). After doing so, the list of possible values (= tokens starting with "`node:`") will change and start to show (dozens of) other values such as:

* `node:nid (Node ID)`
* `node:type (Content Type)`
* `node:author... (Node Author)`
* `node:comment (Comments allowed)`
* `node:comments... (Comments)`

In the above list, note the ones that have a "`...`": those are the ones that, after you select any of them, will bring up yet another list of tokens that start with what you selected. So if you select "`node:author... (Node Author)`", it'll show (many) other values (some with yet another "`...`"), such as:

* `node:author:uid (User ID)`
* `node:author:name (Name)`
* `node:author:mail (Email)`
* `node:author:roles... (User roles)`

So there you are: using the drill-down approach as shown above, `node:author:mail (Email)` is what you're looking for. All that's needed now, is to select it from this list. Though in this case there is no more *Label* and *Description* for the token, you only have what's shown between "`(`" and "`)`" to decide about which token to select.

PS: If you don't find what you're looking for (after using the `Switch to data selection` button), you can always return to the previous display by using the `Switch to the direct input mode` button.

---
Tags: rules, emails, tokens
---


# Question
Title: How to hide node by Role similar to the Hide Block by Role module?
Does anyone know of a module similar to the "Hide Block by Role" module, but for nodes?

The scenario I'm looking to achieve is:

* User 1 has Role A and Role B
* User 2 has Role A and Role C

I need to be able to create a node and limit access to Role A and Role B, but also hide/block it for Role C. So, User 1 would see the node but User 2 would not. Currently, because User 2 has Role A, he is able to see the page which is why I need something similar to "Hide Block By Role".

I'm currently using the Content Access module to control access.

# Answer
> 1 votes
Rules (the module) is your friend ... Here is a prototype of a rule (in Rules export format) that you could use (assuming that the Role ID (`rid`) for Role B is "`4`", adapt the value of this `rid` to fit your case):

```
{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "node\/123",
              "node\/456"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "access_denied" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

After you enable the above rule, you can grant `Access (view)` permission to the nodes "`node/123`" and "`node/456`" for users with role A (using the Content Access module). That will already prevent access to these nodes for any user who does not have that role A.

The above rule will ensure that users who do not have role B, will NOT be able to actually "view" these nodes. Instead they'll get a message starting with "*Access to the content located at ...*" (change this message to whatever fits).

---
Tags: 7, users
---


# Question
Title: How to create a rule to email all users who bookmarked the author of new content?
I have the Rules and Flag modules installed. I want other users to be notified of flagged user new content.

I made 2 rules:

1. To add the author of content to bookmarks of user:
2. To send an e-mail notification when bookmarked (flagged) user created new article:

But it sends an e-mail only to the user who created the article.

What am I doing wrong?

# Answer
As i can see in your `Actions` \- Send mail - `To:[site:current-user-mail]`. You need to create action `Send mail` and chose 'Send mail to all users of role\` - and chose roles for which you want to send mail.
> 1 votes

# Answer
### Mistakes in your current rules

The Rules Action in your 2nd rule is ***to send an e-mail only to `[site:current-user-mail]`***.

Since this rule is using Rules Event "After saving new content", the user who is actually saving that new content will receive that eMail. But, that user is also `[site:current-user-mail]`. So your rule "works as implemented", though that is obviously not what you want.

Moreover, you are only sending an eMail to only 1 user, instead of some type of list of users, i.e. all users who bookmarked (flagged) the author.

### How to get it to work

To make this work you may want to give it a try to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* Load the VBO list that you want to be processed.
* Add a loop to perform a Rules Action, for each row contained in your Views results.

Some more details about the VBO-view you'd have to create for this:

* The view should list all users who have bookmarked (flagged) the author or the newly saved node.
* It should include an appropriate filter for the userid of the node author.
* It should have exactly 1 result (row) for each user to be eMailed.
* One of the columns should be the eMail Id (I don't see other columns needed for this to work).

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

---
Tags: rules, flags, notifications
---


title: Why aren't the radio buttons rendered?

text:
# Question
Title: Why aren't the radio buttons rendered?
According to the documentation for `Radios`, the following code should output a group of radio buttons.

```
$form['settings']['active'] = array(
  '#type' => 'radios',
  '#title' => $this->t('Poll status'),
  '#default_value' => 1,
  '#options' => array(0 => $this->t('Closed'), 1 => $this->t('Active')),
);

```

However, when I use this code, I get an error.

```
public function radioComponent () {
  $form['posting_settings']['comment_preview'] = array(
    '#type' => 'radios',
    '#title' => t('Preview comment'),
    '#default_value' => '1',
    '#options' => array(t('Optional'), t('Required')),
  );

  return $form;
}

```

> Notice: Undefined index: #title\_display in Drupal\Core\Render\Element\Radios::preRenderCompositeFormElement() (line 20 of core\lib\Drupal\Core\Render\Element\CompositeFormElementTrait.php).

> Notice: Undefined index: #id in Drupal\Core\Render\Element\Radios::preRenderCompositeFormElement() (line 30 of core\lib\Drupal\Core\Render\Element\CompositeFormElementTrait.php).

Even when I use the following code, the radio buttons aren't rendered.

```
public function radioComponent () {
  $form['posting_settings']['comment_preview'] = array(
    '#type' => 'radios',
    '#title' => t('Preview comment'),
    '#default_value' => '1',
    '#options' => array(t('Optional'), t('Required')),
    '#id' => 'al1',
    '#title_display' =>'title',
  );

  return $form;
}

```

Does anyone know why the radios don't render?

# Answer
if you look at `/core/lib/Drupal/Core/Render/Element/Radios.php` you'll see it's not a render element, but a form element.

You can't use it without putting it in a form. If you search the code base for **extends FormBase**, you'll see many examples of forms that you can start from in building your own form, many of them quite simple.

For example: `/core/modules/system/tests/modules/form_test/src/Form/FormTestProgrammaticForm.php`
> 5 votes

---
Tags: forms, 8
---


# Question
Title: How can I stop full page HTML from being cached?
I am having an issue with my whole page's HTML being cached. This is getting in the way of some dynamic block content that is based off of a user preference value (both authenticated and anonymous users).

I have located the cache entry in the cache\_render table of the DB and it has a CID of:

```
http://dev-mysite.pantheonsite.io/:html

```

(this would be the entry for the front page) I do have the block that builds this dynamic content configured with cache settings:

```
[#cache]['contexts'] = ['session', 'user'];
[#cache]['max-age'] = 0;

```

I am only having this caching issue when code is push to the Pantheon servers, local development environments with default cache config settings do not have this issue.

# Answer
> 10 votes
(Anyonymous) Page cache can not be controlled by max-age or contexts. You need to call \Drupal::service('page\_cache\_kill\_switch')-\>trigger(); to prevent that kind of caching.

However, if it is a block that is displayed on all pages, then that becomes pretty pointless to even try and you could uninstall the page\_cache module completely.

---
Tags: 8, caching
---


# Question
Title: Stuck developing a new library module for "vminpoly". "Drupal.behaviors" confusion
I think this could be really useful to the masses. I've so far not found a alternative. If you know of one, please do advise.

My use case is having a banner with a height of 85% of the viewport. The new vh, vw and vmin length units in CSS are great for this. Except they don't work in all browsers and devices.

The vminpoly library looks like a great solution. At window resize time, it generates CSS code for the 'px' equivalents and appends it in a 'style' element at the end of the 'head' element. The generated code respects media queries.

On their demo the JS part of the source code, in the footer, looks like this:

```
<script type="text/javascript">
      if (!Array.prototype.filter)
      {
        Array.prototype.filter = function(fun /*, thisp*/)
        {
          var len = this.length;
          if (typeof fun != "function")
            throw new TypeError();

          var res = new Array();
          var thisp = arguments[1];
          for (var i = 0; i < len; i++)
          {
            if (i in this)
            {
              var val = this[i]; // in case fun mutates this
              if (fun.call(thisp, val, i, this))
                res.push(val);
            }
          }

          return res;
        };
      }
    </script>
    <script src="tokenizer.js"></script>
    <script src="parser.js"></script>
    <script src="vminpoly.js"></script>

```

So being as there isn't much to the module and in the interest of being complete, here are my files:

vminpoly.info

```
name = Vminpoly
description = Adds the vminpoly javascript plugin. It adds support to allow the use of vw,vh/vmin units in your theme.
core = 7.x
dependencies[] = libraries

```

vminpoly.module

```
<?php

/**
 * Implements hook_libraries_info().
 */
function vminpoly_libraries_info() {
  $libraries = array();
  $libraries['vminpoly'] = array(
    'name' => 'Vminpoly',
    'vendor url' => 'https://github.com/saabi/vminpoly',
    'download url' => 'https://github.com/saabi/vminpoly',
    'version callback' => 'short_circuit_version',
    'files' => array(
      'js' => array(
        'tokenizer.js',
        'parser.js',
        'vminpoly.js',
      ),
    ),
  );

  return $libraries;
}

/**
* Short-circuit the version argument.
*/
function short_circuit_version() {
  return TRUE;
}

/**
* Load all files
*/
drupal_add_js('if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; }', array('type' => 'inline'));
$name = 'vminpoly';
libraries_load($name);

```

I'm sure this will be of help to others, maybe even you.

The question is what is wrong with it. I'm pretty confident (famous last words) that everything is as it should be, except the vminpolydrupal.js file. I'm sure its my lack of understanding when it comes to behaviours and tbh JS generally. I feel as though "context" needs to be added to their code snippet somewhere.

I'm out of my comfort zone and learning. Please help...

# Answer
So I had a few problems with this. First of all my .module file defined a library because that felt like the proper way to do it. However I received errors in the console and needless to say that it didn't work. After Googling the error I found out that it happens when everything is in the head.

So I removed the library implementation. Then the script itself didn't work. Again after searching on Google I found a fork of it where the guy had fixed those errors. This can be found at: https://github.com/gfaceless/vminpoly

I created a directory called lib, then placed parse-css.js & vminpoly.js in it.

My .module file became:

```
<?php

/**
* Load all files / JS
*/

drupal_add_js('if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; }', array('type' => 'inline', 'scope' => 'footer'));
drupal_add_js(drupal_get_path('module', 'vminpoly') . '/lib/parse-css.js', array('scope' => 'footer'));
drupal_add_js(drupal_get_path('module', 'vminpoly') . '/lib/vminpoly.js', array('scope' => 'footer'));

```

Also removed `dependencies[] = libraries` from the .info. Lastly, for me it didn't kick in unless I aggregated my CSS files.

Hope this helps others. Now my vh, vw and vmin length units work across browsers. Happy days!
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Update field collection programatically - backend different to frontend
I know there are other questions similar to this, but I'm having a specific problem. I'm trying to programmatically update a field collection (from it's fid only). This appears to work when printing out the values on the frontend, but when editing the node that the field collection is attached to, the fields within the collection are empty, but the collection itself is there.

```
// Unset and start afresh
unset($node->field_composition[LANGUAGE_NONE]);

foreach($fids as $fid){
  $comp = entity_load_single('field_collection_item', array($fid));
  $comp->field_chemical[LANGUAGE_NONE][0]['target_id'] = $id; // These values are derived elsewhere and are correct
  $comp->field_weight[LANGUAGE_NONE][0]['value'] = $value; // These values are derived elsewhere and are correct
  $comp->save(TRUE);
  $node->field_composition[LANGUAGE_NONE][] = array('value' => $comp->item_id);
}

node_save($node);

```

I assume the problem is to do with revisions - as the data is correctly saved somewhere - else it wouldn't appear on the front end. How to solve this?

# Answer
Well, as always happens I found the answer just after I posted the question:

```
// Unset and start afresh
unset($node->field_composition[LANGUAGE_NONE]);

foreach($fids as $fid){
  $comp = entity_load_single('field_collection_item', array($fid));
  $comp->field_chemical[LANGUAGE_NONE][0]['target_id'] = $id; // These values are derived elsewhere and are correct
  $comp->field_weight[LANGUAGE_NONE][0]['value'] = $value; // These values are derived elsewhere and are correct
  $comp->save(TRUE);
  $node->field_composition[LANGUAGE_NONE][] = array(
    'value' => $comp->item_id,
    'revision_id' => $comp->revision_id // ADDED REVISION ID HERE!
  );
}

node_save($node);

```
> 1 votes

---
Tags: entities
---


# Question
Title: Is there a way to suppress warnings on the D8 Status Report page?
On my D8 status report (admin/reports/status) I have warnings about an issue I might wish to ignore. Is there any way to suppress the warnings on that report page once I have seen them and made my decision?

If it matters, the warnings are about using a CDN instead of installing libraries locally with YAML Form, which produces a wall of ten yellow warning rows in my Status Report. If we decide to continue using the CDNs instead of installing, we'd like to not see those warnings taking over so much real estate on the Status Report page in the future.

# Answer
Unfortunately there is no hook\_requirements\_alter yet. As a workaround you may override system manager service which is responsible for invoking that hook.

*src/SystemManager.php*

```
namespace Drupal\example;

use Drupal\system\SystemManager as DefaultSystemManager;

/**
 * System Manager Service.
 */
class SystemManager extends DefaultSystemManager {

  /**
   * {@inheritdoc}
   */
  public function listRequirements() {
    // Suppress some unwanted warnings on Status report page.
    return array_filter(parent::listRequirements(), function ($requirement) {
      return $requirement['title'] != t('The message about CDN.');
    });
  }

}

```

*src/ExampleServiceProvider.php*

```
namespace Drupal\example;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Overrides the system manager service to suppress some warnings.
 */
class ExampleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $container->getDefinition('system.manager')
      ->setClass('Drupal\example\SystemManager');
  }

}

```
> 2 votes

# Answer
The controller for this route gathers up all the data reported by `hook_requirements()` from the `SystemManager` service method `listRequirements()` which is used to build its theme array.

There's no entry point into that process through the Drupal API's except through the theme layer. A module could evoke `hook_preprocess_status_report()` to alter the data in `$requirements` variable used to render the page.

This method would require you to alter the markup to provide UI element to capture the preference, store it, then use it to remove it from the `$requirements` array in future requests.

```
function MYMODULE_preprocess_status_report(&$variables) {
  // @TODO: processing logic for $variables['requirements']
}

```
> 1 votes

---
Tags: status-messages, log-messages
---


title: How do I create table in custom module

text:
# Question
Title: How do I create table in custom module
In Drupal 7 we used to use `hook_schema()` in the .install file to create a table. I believe that, in Drupal 8, you can do that as well, but I was under the impression that you should create .yml files with your schema.

What's the method for creating tables in Drupal 8?

# Answer
> 12 votes
`hook_schema()` is still used from Drupal 8 modules to create custom database tables used from the module. Even the User and the Node modules implement it, although `user_schema()` and `node_schema()` don't define the schema for the respective entities, which are created in a different way.

The configuration schema is not used to create custom database tables a module uses, but describes the structure of configuration files. The PDF file found in the documentation I linked makes clear the relation between a configuration file and its schema.

>

Content entities don't use `hook_schema()`; Drupal creates the database table for them basing on the base fields the content entity class defines.

Which method to use depends on what the module defines. It's up to the module define a content entity, a configuration entity, or just use a custom table. A module could even use all of them.

# Answer
> 13 votes
You can use hook install to create your own tables, if you really want to, although Drupal has many other more out-of-the-box solutions. But if you do want to roll your own, there's an example module, called dbtng\_example, in the examples module: https://www.drupal.org/project/examples, complete with routing for adding and removing your custom database entries.

I'd recommend installing it and trying it out, then you can use that as a basis for creating your own database table in Drupal 8.

Another approach to consider is to create a config entity or a content entity.

If you use the drupal command line tool there's even a command for generating these "drupal generate:entity:config", and "drupal generate:entity:content".

Also in the examples module, there is config\_entity\_example and content\_entity\_example.

From https://www.previousnext.com.au/blog/understanding-drupal-8s-config-entities: "The main difference between content and config entities is how they are stored and (at the moment) config entities are not fieldable".

There are some other more out of the box solutions, such as the config\_pages module that allow you to easily spin up places to store data on your site: https://www.drupal.org/project/config\_pages

We recently used these for one off landing pages, by creating a controller and route. This has a huge advantage over a custom table as you can easily add new fields and you can use data types such as images and entity references easily, you can also set field formatters, and load the data formatted using the config\_pages entity view builder.

---
Tags: 8, database
---


# Question
Title: How to get a list of Users as values for a select list field?
How do I get a list of users of a specified role to populate a select list in `node/add/*` ?

For example when creating a piece of content I want a field "Select Your Moderator of Choice" and the options are a list of all users with the role moderator.

# Answer
You will want to install a module that allows you to reference a user. A popular choice is entityreference.

With Entity Reference you can create a view of User's with a display type of Entity Reference. You can then add a filter to your view to only show users with the role that you are interested in.

Then you can setup a new field on your content type of the type, reference. Within that fields settings you can specify your view to be used as the mode for "Entity Selection".

You only need to setup the view if you want to limit the users that are selectable. If any user would be valid for your field, Entity Reference has some built in modes for entity selection that makes the process even easier.
> 0 votes

# Answer
For Drupal 8 - You can add a new field to whatever content type you want to capture the User.

Add a User Reference Field

Set the number values allowed

Set the filter to **User Role** and specify the role:
> 0 votes

# Answer
### Step 1

To have such a list of users that can be referenced, you should ***first*** (repeat: ***first***) create a view (with the Views module) to create a list of all the users that are allowed to be selected. And the display type of such view must be an *Entity Reference* display.

### Step 2

Your select list field (to select from a filtered list of users) should be a field that looks like so:

* Field Name = Anything you want, eg `field_users_list`.
* Field Type = Entity Reference, using these additional settings for it:

+ *Target type* = `user`
    + *Number of values* = `1` (probably, though something like "unlimited may do as well).
    + "Mode" (within "entity selection") = `Views: Filter by an entity reference view`. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an *Entity Reference* display, or add such a display to an existing view. In your case, you should select the view created in "Step 1".
    + Pick any of the other options to define this field as you see fit.
> 0 votes

---
Tags: 7, users
---


title: twig for loop access value using array

text:
# Question
Title: twig for loop access value using array
i have a for loop

```
{% for row in rows %}
    {{ row.content }}
{% endfor %}

```

will print out like this

```
<div> one </div>
<div> two </div>
<div> three </div>
<div> ... </div>

```

but what i want to is access the values using a key so i can pull the values individually so i can do some thing like this

```
<div class="container">
    <div> one </div>
</div>

<div class="second-container">
    <div> one </div>
</div>

<div class="anyclassname">
    <div> one </div>
</div>

```

basically print the value anywhere i want on a div of my choice. Is it possible ?? please help

this is for a views template

# Answer
In views-view.html.twig is not appropriate to style your row and fields.

To style them first you need override template "views\_view\_'format\_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).

Something like:

```
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}
  <h2> {{row.content['#node'].getTitle()}} </h2> {# access fields #}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

```

For style fields its better override field template.

For example field--node--body--article.html.twig:

```
{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}
        <div{{ attributes }}>{{ item.content }}</div>
    {% elseif mode == 'teaser' %}
        <p{{ attributes }}>{{ item.content }}</p>
    {% endif %}
  {% endfor %}
{% else %}
  <div{{ attributes }}>
    <div{{ title_attributes }}>{{ label }}</div>
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
  </div>
{% endif %}

```

source : In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content?

http://twig.sensiolabs.org/doc/tags/for.html
> 1 votes

# Answer
The fastest/easiest solution is to click on the field, then click on **Re-Write Results**

Use the replacement pattern for your field, and put something like this:

```
<div class="container">
    <div> {{ field_name }} </div>
</div>

<div class="second-container">
    <div> {{ field_name }} </div>
</div>

<div class="anyclassname">
    <div> {{ field_name }} </div>
</div>

```

Alternatively, you could create a **views-view-fields--\[view-name\]--\[machine-name\].html.twig** file and put the same code there.

---

If your field in question, has unlimited values:

* Click in your field and under **Multiple field settings**, *uncheck* the `Display all values in the same row` box.

---

> its a views page with three fields... // 2 image and a text -- all of this needs to me printed on the same div..

Then in your template file put:

```
<div class="container">
{{ fields.field_company_color_scheme.content }}
{{ fields.field_port_landing_feature.content }}
{{ fields.field_com.content }}
</div>

```
> 1 votes

# Answer
SO this is what i've come up with

so instead of using

```
{% for row in rows %}
    {{ row.content }}
{% endfor %}

```

what i did was completely remove the for loop and used this instead

```
<div class= red > {{ rows[0] . content}} </div>
<div class= yellow > {{ rows[1] . content}} </div>
<div class= blue > {{ rows[2] . content}} </div>
<div class= green > {{ rows[3] . content}} </div>

```

this way i can also control how many items are displayed and give a div name of your choice or within another div.

now the question remains on how to take apart the

```
  {{ rows[0] . content}}

```

the array within the {{ content }} part so they can be further broken apart... any Idea ???
> 0 votes

---
Tags: views, theming, 8
---


title: How to define column css in views?

text:
# Question
Title: How to define column css in views?
How to define column css in views?

I testing a theme. I tried edit the css from CSS class one-half to one-fourth. The layout changes successfully from half column to fourth column.

I wondered how the CSS define.

I looked into the views but can't find the css added (one-half)

# Answer
> 1 votes
Click here and check if it was added as a row class.

Else, look under Advanced

If nothing is there, check your theme's templates folder. They probably created a template file (.tpl.php or .html.twig) for the view.

Lastly, if still nothing, check inside your theme's folder for template.php or theme-name.theme

---
Tags: views, theming
---


# Question
Title: Placing user login and user menu at the bottom right when this is not supported by the theme
I'm new at Drupal and am building a site with the Bootstrap theme, and i would like to place the user login and user menu in the lower right corner. Unfortunately there is no region for that, there is just the footer region which covers the whole width of the screen

What is the best way for me to add the user login and user menu to this area?

This would have been a problem if i just wanted to place the user login and user menu below, because when setting contents of the blocks they are placed vertically on top of each other. But in my case this wouldn't look good, i would need the stacking to be done horizontally instead of vertically

I can think of two different approaches:

1. Modifying the bootstrap theme so that there is a region in the lower right
2. Modifying the code of the footer to include the content of the "user login" and "user menu" blocks (maybe using this as a guide)
3. Maybe using the panels module?
4. Somehow getting the stacking to be done horizontally rather than vertically

Which of these would you recommend? Are there other approaches that are better?

It's important that the site is easy to maintain long-term and that we can continue to use the auto-update for the bootstrap theme

Grateful for any suggestions!

# Answer
Never directly use the Bootstrap theme, create a subtheme from one of the starterkits inside your theme folder (they have readme files inside the starterkits with more info and relevant links depending on which method you prefer to use), and do all your work in the subtheme. This way you can auto-update the bootstrap theme, without loosing all your customisations.

Next step would be to create your own region (for example Footer right) in the info file of your subtheme:

```
;;;;;;;;;;;;;;;;;;;;;
;; Regions
;;;;;;;;;;;;;;;;;;;;;

regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'

regions[footer_right]   = 'Footer right'

regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

```

Next create the region in your page.tmpl.php file. You should override the one used in the Bootstrap theme, with a duplicate you make in your subtheme: YOUR\_SUBTHEME/templates/system/page.tpl.php. (Copy the file you have in YOUR\_SUBTHEME/bootstrap/system/page.tpl.php)

Go to the footer section in this page.tpl.php file, it should look somewhat like this:

```
<?php if (!empty($page['footer'])): ?>
  <footer class="footer <?php print $container_class; ?>">
   <div class="container">
    <?php print render($page['footer']); ?>
   </div>
  </footer>
<?php endif; ?>

```

And add your new region where you would like it to go (for instance like this), and use the Bootstrap markup to align your content to the right:

```
<?php if (!empty($page['footer'])): ?>
  <footer class="footer <?php print $container_class; ?>">

   <?php if (!empty($page['footer_right'])): ?>
    <div class="container">
     <div class="col-xs-6 col-xs-offset-6 col-sm-4 col-sm-offset-8">
      <?php print render($page['footer_right']); ?>
     </div>
    </div>
   <?php endif; ?>

   <div class="container">
    <?php print render($page['footer']); ?>
   </div>
  </footer>
<?php endif; ?>

```

Make sure to clear your sites cache when you're doing changes to template files like these. If all is fine, your new region should appear in "structure \> blocks", and you should be able to add your login blocks to it.
> 1 votes

---
Tags: 7, theming
---