title: How to add custom HTML to node content?

text:
# Question
Title: How to add custom HTML to node content?
I'm new to Drupal coming from Wordpress, but I was able to put a site up&running. Theming is easy in WP, but I have not figured that out in D7.

I have a Content Type and the node-content output HTML as below. But I wanted to add custom html in-between section of the node-content:

```
<div class="node-content">
    <div class="section field field-name-field-xxx ">
    ....
    </div>
    <!--need to add My Custom HTML here-->
    <div class="section field field-name-field-yyy ">
    ....
    </div>
</div>

```

I have searched online but I am not getting the basic instructions how to proceed. Presently I'm using a child theme of Zircon.

Any help?

# Answer
> 1 votes
Create a custom template file node--type.tpl.php where `type` is the machine name of your content type.

Place it in your theme's templates folder `/sites/all/themes/YOURTHEME/templates` and clear/flush the cache to see changes.

Ex: Article content type: **node--article.tpl.php**

```
<?php print render($content['field_xxx']); ?>

// custom html goes here

<?php print render($content['field_yyy']); ?>

```

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


# Question
Title: How to get all parent menu items' titles of the current node?
I know I can load the node's menu item like so:

```
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

```

But to use a menu structure in a breadcrumb I need to load all parent menu items. I feel like the menu service provides such a function but I dont get anything out of the documentation. This here seems pretty mighty but it really lacks documentation.

Edit: I've already came this far:

```
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

if (is_array($menu_link) && count($menu_link)) {
  $menu_link = reset($menu_link);
  if ($menu_link->getParent()) {
    $parents = $menu_link_manager->getParentIds($menu_link->getParent());
    dpm($parents);
  }
}

```

and it gives me:

```
Array
(
  [menu_link_content:2fd24ddd-19e2-4e8f-9764-839b3f51139e] => menu_link_content:2fd24ddd-19e2-4e8f-9764-839b3f51139e
  [menu_link_content:e30b827f-bc67-4892-b23f-28b23188ffd4] => menu_link_content:e30b827f-bc67-4892-b23f-28b23188ffd4
)

```

Is there an easy way to get those titles?

# Answer
> 10 votes
Even shorter using the MenuActiveTrailInterface.

```
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$currentPluginId = $menu_link->getPluginId();
$trailIds = $this->menuActiveTrail->getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    $breadcrumb->addLink(
      new Link(
        $menu_link_manager->createInstance($value)->getTitle(),
        $menu_link_manager->createInstance($value)->getUrlObject()
      )
    );
  }
}

```

# Answer
> 7 votes
In case it help anyone I used a combination of Alex's solutions to write a function that returns the parent menu item for the current node.

```
function mymodule_get_parent_menu_title() {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');

  $node_id = \Drupal::routeMatch()->getRawParameter('node');
  if ($node_id) {
    $menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
  }
  else {
    return '';
  }

  if (is_array($menu_link) && count($menu_link)) {
    $menu_link = reset($menu_link);
    if ($menu_link->getParent()) {
      $parents = $menu_link_manager->getParentIds($menu_link->getParent());
      $parent = reset(array_reverse($parents));
      $title = $menu_link_manager->createInstance($parent)->getTitle();

      return $title;
    }
  }

  return '';
}

```

# Answer
> 0 votes
So, this code works but I doubt that this is the most performant way of doing it...

```
$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

if (is_array($menu_link) && count($menu_link)) {
  $menu_link = reset($menu_link);
  if ($menu_link->getParent()) {
    $parents = $menu_link_manager->getParentIds($menu_link->getParent());
    if (is_array($parents) && count($parents)) {
      $_parents = array();
      foreach ($parents as $key => $uuid) {
        $uuid_parts = explode(':', $uuid);
        $_parents[] = array_pop($uuid_parts);
      }

      $mlc_ids = \Drupal::database()
        ->select('menu_link_content', 'mlc')
        ->fields('mlc', ['id'])
        ->condition('uuid', $_parents, 'IN')
        ->execute()
        ->fetchCol();

      if (is_array($mlc_ids) && count($mlc_ids)) {
        $titles = \Drupal::database()
          ->select('menu_link_content_data', 'mlcd')
          ->fields('mlcd', ['title', 'link__uri'])
          ->condition('id', $mlc_ids, 'IN')
          ->execute()
          ->fetchAllKeyed();

        foreach ($titles as $title => $entityUri) {
          $breadcrumb->addLink(new Link($title, Url::fromUri($entityUri)));
        }
      }
    }
  }
}

```

edit: but this does not even add menu items that do not come from nodes (for instance from views). See my other answer!

# Answer
> 0 votes
Alex, your previous code works well, thanks !

For making it works with views or other routes, you have to use :

```
  $route_name = \Drupal::service('current_route_match')->getRouteName();

```

instead of using the node's route

Something like

```
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');

  $node_id = \Drupal::routeMatch()->getRawParameter('node');

  if ($node_id) {
    $menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
  }
  else {
    $route_name = \Drupal::service('current_route_match')->getRouteName();
    $menu_link = $menu_link_manager->loadLinksByRoute($route_name);
  }

```

---
Tags: 8
---


# Question
Title: How to open Fontello Icons in new tab or window?
Coding/CSS/HTML is not my area of forte at all. I've figured out that this (more or less) is how to make an external link open in a new window or tab. I'm working on a website that uses Fontello Icons for social media links and I'd like those links to open in a new tab/window so the individual would be able to keep a tab open with my website. Any and all help is appreciated!

# Answer
> 1 votes
The short answer would be to add a target="\_blank" parameter into your anchor tag. Something like:

```
<a href="example.com/url" target="_blank">&fontello_icon_here;</a>

```

The long answer depends on your context. I hope this helps! If it doesn't please update your question with specifics of what you're trying to accomplish.

---
Tags: navigation
---


title: How to make live node preview?

text:
# Question
Title: How to make live node preview?
I need an instant preview of what an entire node will look like before getting published. Ideally preview gets updated by every change user makes to the form., probably in an iframe beside the form.

The closest I can get is using Page Preview Module, but I need it without the context of a fully rendered page and without having to click preview button.

# Answer
Have you looked at the Spark distribution?

Rather than placing the preview next to the form as you propose, the Quick Edit module (in-place editor) allows you to edit certain fields while they're still in their original context. The Responsive Theme Preview might also be useful to you.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to pass a custom object from a page to another page through a route or other means?
I want to be able to pass a custom object of type `FormMode` through a route or any other way.

My `custom.routing.yml` file is:

```
custom.page:
  path: '/custom/{model}'
  defaults:
    _controller: '\Drupal\custom\Controller\CustomController::page'
    model: ''
  requirements:
    _permission: 'administer site configuration'

```

My `FormModel` class looks like:

```
class FormModel {
  public $name;
  public $area;

  function __construct($name, $area) {
    $this->name = $name;
    $this->area = $area;
  }

```

I create an instance of the object and use Drupal URL function like shown below:

```
$model = new FormModel('name', 'area');

Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model));

```

but Drupal throws an error saying Drupal cannot convert a object to a string which I understand it cant convert object to string.

What would be the best practice to pass a object through a route or pass object created from a form into a controller? I dont want to create an entity as I would then need to update the database with the new fields.

Thanks

# Answer
> 5 votes
You are passing the object, but you need to pass the object ID. So you will change this:

```
Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model));

```

To this:

```
Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model->id()));

```

Note that your model object will need to have a public id() method that returns the ID for this to work. This will send the ID that is passed in place of {model} to the callback.

If you want the callback function (the controller) to receive a loaded object rather than just the ID, you'll need to do a few things. The first is to add options to your route:

```
custom.page:
  path: '/custom/{model}'
  defaults:
    _controller: '\Drupal\custom\Controller\CustomController::page'
    model: ''
  requirements:
    _permission: 'administer site configuration'
  options:
    parameters:
      model:
        type: model

```

Then you'll need to set up a new route in services.yml:

```
services:
  model:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

```

And you'll need to create the class (`Drupal\mymodule\ParamConverter\MyModuleParamConverter`) that does the conversion from ID to object. This class needs to implement ParamConverterInterface:

```
namespace Drupal\mymodule\ParamConverter;

use Drupal\Core\ParamConverter\ParamConverterInterface;
use Symfony\Component\Routing\Route;

class MyModuleParamConverter implements ParamConverterInterface {
  public function convert($value, $definition, $name, array $defaults) {
    // Create your Model object here (not shown) then return it:
    return $model;
  }

  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'model');
  }

```

}

You can read more about parameter upcasting here: https://www.drupal.org/docs/8/api/routing-system/parameter-upcasting-in-routes

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


# Question
Title: Conditionally output by content type using Twig
I want to theme the display of a Views based on the Content type. In my attempts to do that, I’ve created the views showing All Content Types. I’ve added all the fields I need, and also included a Content: Type field. It is this field that I am trying to use for conditionally formatting the output (if it’s a Blog content type use this html and for all other content types use a different html).

This is what I have tried so far but that condition is not triggering at all

I have created a views-view-fields--myexample.html.twig

```
{% if fields.type.content == 'blog' %}
<div class="blog-content views-row">
  <div class="showcase" style="background-color: {{ fields.field_color.content }};">

</div>
{% else %}

<div class="other-content views-row">
   <div class="showcase">
   {{ fields.title.content}}
   {{ fields.field_image.content }}
   </div>
</div>
{% endif %}

```

# Answer
> 2 votes
Probably because `{{ fields.type.content }}` = `<div class="something">blog</div>`

so try

```
{% if fields.type.content|striptags == {{ 'blog'|t }} %}

```

If you do not want to have to use `|striptags` you could strip the markup from the Views UI.

Also, do not check mark `Exclude from display` in configure field, because if you do this your template file will not have access to that field.

Side note: you forgot to close the div in line 3.

---

Alternatively

```
{% if row._entity.gettype == 'content_type_machine_name' %}

```

<sub> alternate method credit: 4K4 </sub>

---
Tags: views, 8
---


# Question
Title: How to Send an email with the list of products ordered in its body?
I created a rule and a component, to send an email to my customers 7 days after their orders. This email asks them to leave a comment on the products they have purchased.

My problem: I can not retrieve the list of products in the email. With `[order:commerce_line_items]`, the e-mail displays "No order items found".

Here is the export of my rule :

```
{ "rules_schedule_follow_up_email" : {
    "LABEL" : "Schedule follow-up email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "processing" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_send_follow_up_email",
          "date" : "now",
          "identifier" : "Follow-up email for [commerce-order:order-id]",
          "param_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

```

Here is the export of my component :

```
{ "rules_send_follow_up_email" : {
    "LABEL" : "Send follow-up email",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "order" : { "label" : "Order", "type" : "commerce_order" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : "[order:mail]",
          "subject" : "Votre avis nous int\u00e9resse",
          "message" : "[order:owner],\r\n\r\n\r\nvous recevez ce courriel car vous avez r\u00e9cemment fait un achat sur notre site. Nous aimerions avoir votre avis sur les produits que vous avez command\u00e9.\r\nC\u0027est simple et rapide, il vous suffit de cliquez sur les liens ci-dessous :\r\n\r\n[order:view-url]\r\n\r\n[order:commerce_line_items]\r\n\r\nMerci pour votre retour d\u2019exp\u00e9rience. Nous appr\u00e9cions le temps que vous prenez et nous l\u0027utiliserons activement pour am\u00e9liorer notre boutique. \r\n\r\n\r\nCordialement,\r\nL\u0027\u00e9quipe [site:name]\r\n[site:url]\r\n\r\nPour rester inform\u00e9 des nouveaut\u00e9s et b\u00e9n\u00e9ficier de nos offres promotionnelles, suivez-nous sur :\r\nhttps:\/\/www.facebook.com\/S1biosecom\r\nhttps:\/\/twitter.com\/S1biosecom\r\nhttps:\/\/plus.google.com\/+S1biosecom\r\nhttps:\/\/www.pinterest.com\/S1biosecom\r\n\r\nPS : ceci est un mail automatique, merci de ne pas y r\u00e9pondre.",
          "language" : [ "order:owner:language" ]
        }
      }
    ]
  }
}

```

I want to display in my email, the links to the product pages ordered by my client. How can I do so?

# Answer
> 0 votes
If what you're looking for (= the list of products) is not available, then just (a) make it available first and (b) wait with your `Schedule Rules Component` action (to send an eMail) 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 Rules Action to schedule the Rules Component. Say you name the variable `prod_list_var_for_email_body`.
2. Add a loop to iterate over the list of links to the product pages. Within that loop, for each iteration, prepend or append the value for each `list_item` to that variable `prod_list_var_for_email_body` (see where we're going???).
3. Make sure that the `Schedule Rules Component` action is your last Rules Action, after the loop completed. And finetune the details (configuration) of your Rules Action to `Schedule Rules Component`. 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?***

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


# Question
Title: Field is translatable, but field instance is not
When exporting configuration for a node type with fields with Drupal 8.2, I noticed that `translatable: true` is set in `field.storage.node.my_field.yml`, but `translatable: false` is set in `field.field.node.living_word_comment.my_field.yml`. `my_field` is of type `Text (plain)`, i.e. `string` in the YAML file.

**What does it mean for a field to be translatable, while the instance is not?** It doesn't make sense to me.

Disclaimer: I'm not sure whether phrases like "field" and "field instance" are still applicable in Drupal 8, or whether that is just *7-speak*.

# Answer
Every node field has one storage setting. Here the field is configured how it is stored in the database, field type, single or multi value, or translatable or not. This settings can't be changed after the field is set up and filled with data. It's shared among all content types.

The field can be used in multiple content types. In each content type it can be configured to be translatable. (Option "Users may translate this field"). This setting can be changed any time and without data loss.

If you want the field to be translatable, you need both options set, in the field storage and in the content type where the field is used.

If you use the UI, then you don't have to worry about this, because Drupal sets the storage settings the first time you place a field in a content type.
> 3 votes

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


# Question
Title: Render a region e.g page.sidebar_first in views-view.html.twig
Is it possible to render a region e.g `sidebar_first` in a views twig-file `views-view.html.twig`?

# Answer
Not the region itself, but you can render the blocks with Twig Tweak, so simply add the blocks that are in that region to your template file.

> Twig Tweak module provides a Twig extension with some useful functions and filters that can improve development experience.
>
> ```
> {# The block with this ID should be configured on "admin/structure/block" page. #}
>   <dt>Block:</dt>
>   <dd>{{ drupal_block('bartik_powered') }}</dd>
>
> ```
> 4 votes

# Answer
There is not a Drupal way to do this. Normally it's the other way, you put views in regions (via block layout). You would need to code this yourself by replicating how core fills regions with blocks:

```
$blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));
// Sort ‘em
uasort($blocks, 'Drupal\block\Entity\Block::sort');
// Capture viewable blocks and their settings to $build
$build = array();
foreach ($blocks as $key => $block) {
  if ($block->access('view')) {
    $build[$key] = entity_view($block, 'block');
  }
}
// Add build to region
$variables[$region] = $build;

```

Source:

https://atendesigngroup.com/blog/making-region-content-available-node-templates-drupal-8
> 2 votes

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


# Question
Title: Permissions deselected, but user can still edit content
Reproduce:

1. Create new content type with uid:1
2. In `admin/people/permissions` you can see that permissions are not given to Administrator role, they are deselected/unticked by default for the new content type.
3. E.g. create new user and give him Administrator permissions.
4. The new Administrator user (non-uid:1) can still edit/create/delete the new content type contents although the permissions are deselected?

How's that?

# Answer
> 2 votes
You need disabled option "view, edit, delete any content". If this option is checked, next options not used.

---
Tags: 7, users
---


# Question
Title: Prevent a "default value" checkbox being created with entity?
I have a boolean field associated with my custom entity. The field itself is hidden in the entity form however when an instance of my entity is created a field record is generated with the default value. This is not the case for a text field i have, where if the field is hidden the field record is not created.

Basically this creation of a default boolean field is messing up my views further down the line.

How can i prevent a default value boolean field being autogenerated when hidden?

Thanks Mathew

# Answer
I am sure there are other (better )ways but the way i got around this issue, which fundamentally was about not having the default turn up in my views further down the line, was to implement a hook on hook\_views\_pre\_view and show/hide the fields as i wanted:

```
function mymod_views_pre_view(ViewExecutable $view, $display_id, array &$args)
{
  ...
  $fields[$field_name]['exclude'] = TRUE;
}

```

worked for me hope it helps someone else.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: remove fivestar rating from $print['content'] in print module
I installed the print module. But in the print view, the fivestar rating of the node is shown. How can I remove it? It seems to be in `$print['content']`. Any help appreciated.

# Answer

> 1 votes

---
Tags: 7, rating
---


# Question
Title: How to restrict direct access to the nodes?
How to restrict direct access to the nodes but just allow views to access the required field of the particular node type?

For example in Views Slideshow we are sliding the image field that belongs to particular node type. But we don't want search engines to access & visitors to access the nodes belong to that node type.

Any suggestions?

# Answer
> If we unpublish nodes added by user1 they wont be editable by any other user even if the user have the rights to edit the content of that content type.

**Restrict Node Page View** seems a better way to restrict the direct access to any nodes of specific content type.

Usage is also fairly simple you just need to enable this module and configure the permissions for the nodes which are directly accessible as normal.

http://drupal.org/project/restrict\_node\_page\_view

From the project page:

> Have you ever used a slideshow nodetype that you need to be published but don't want the node be accessible by itself using then node/XXX path? This module is for you!
>
> With this module you can disable direct access to node pages (node/XXX) based on nodetypes and permissions.
>
> Enable the module and don't forget to configure your permissions.
> 3 votes

# Answer
A simple solution would be to not publish the nodes you don't want to be accessible. Views can still pull the data from those nodes.
> 12 votes

# Answer
An other module who do the same thing but with more functionalities.

**Rabbit Hole**

Maintainers of this project ask to "Restrict Node Page View" Maintainer to merge projects in issues.

Advantages against "Restrict Node Page View" :

* Same main functionality on node but extensible to users/files/taxonomy terms
* Can be used in your module
* Can be global to content type or on every content
* See more on project page...

Disadvantage against "Restrict Node Page View" :

* More code so possibly less effective (need tests, not proved)
> 2 votes

# Answer
you should use `node_access()`, there are certain options that you can easily implement using `hook_node_access()`. Implementing `node_access()` allows you to make a decision as to who can access a node and who can create, delete, edit, or update such a node. Views, however, can still pull data from these nodes whatsoever.

hook\_node\_access(), node\_access()
> 1 votes

# Answer
Inspired by https://www.drupal.org/project/restrict\_node\_page\_view you might write a small module yourself:

```
/**
 * Implements hook_node_access()
 */
function MYMODULE_node_access($node, $op, $account) {

  // Default checks
  if (!is_object($node)) {
    return NODE_ACCESS_IGNORE;
  }

  $type = is_string($node) ? $node : $node->type;

  if($op == 'view' && arg(0) == 'node' && arg(1) === $node->nid) {

    // Restrict access to full MYTYPE node for anon users
    if ($type == 'MYTYPE' && user_is_anonymous()) {
      return NODE_ACCESS_DENY;
    }
  }
  // Default
  return NODE_ACCESS_IGNORE;
}

```
> 0 votes

# Answer
Using the Rules module you can implement a rule that looks similar to this:

```
{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, direct access to URLs like [site:current-page:url] is not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

The above rule does not (yet) take into account to only apply the "action" for selected roles only (eg so that admins can still use these paths to view a node). But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add ...

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment (e.g the "Sorry, ..." message to be shown).
> 0 votes

---
Tags: 7, nodes, users, views
---


# Question
Title: Generate drupalSettings in Ajax Callback
I'm returning a form with #ajax functionality in an Ajax response. The form is properly loaded into the page, however it is not #ajaxified, as the drupalSettings are not being returned. In D7, we could generate the JS settings AKA Drupal.settings using the following code:

```
$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
    $settings .= ');</script>';
}

```

I'm trying to find the D8 equivalent of this code, but not having much success. At the moment I'm returning a JsonResponse from my ajax callback, but I'm thinking I probably need to return an AjaxResponse. What I can't figure out is how to pass my generated form to the AjaxResponse, in order for it to return the settings along with the HTML for the form.

# Answer
Well, I'm answering my own question. The secret is to use BubbleableMetadata. Here is my code explaining what I did and how it happened. Here is my entire controller response that generates the JSON for the response:

```
 public function ajax_callback($type)
 {
    // Retrieve the form
    $form = \Drupal::service('form_builder')->getForm('Drupal\path\to\Form');

    // Render the form
    $rendered_form = render($form);

    // Get the data from BubbleMetaData
    $data = BubbleableMetadata::createFromRenderArray($form);
    // Retrieve the attachments from the $data
    $attachments = $data->getAttachments();

    // Generate the settings to be sent back with the ajax response
    if(!empty($attachments['drupalSettings']))
    {
        $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
        $settings .= Json::encode($attachments['drupalSettings']);
        $settings .= ');</script>';
    }

    // Send back the rendered form along with the settings
    $response = [
        'content' => $rendered_form . $settings,
        'status' => TRUE,
        'type' => $type,
    ];

    // Return the data as a JsonResponse
    return new JsonResponse($response);
}

```
> 3 votes

# Answer
You can attach the settings to the section of the array you return in the ajax callback:

```
$form['section']['#attached']['drupalSettings']['mysettings'] = ...
return $form['section'];

```

If you use an html insert command like replace or a dialog command you can do the same for the content you use in this command.

ajax.js will reattach drupal behaviors and settings after it receives the ajax response.
> 1 votes

---
Tags: 8, javascript, ajax
---


# Question
Title: Memcache and form cache - is specfiying database for form cache still necessary?
In Drupal 7, a typical setup for Memcache API and Integration was to add this into your settings.php:

```
  $conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;

```

Note the importance of the form cache being told to still use the database.

For Drupal 8, the README says you only add:

```
  $settings['cache']['default'] = 'cache.backend.memcache';

```

Is there any need to leverage the database for forms in Drupal 8? What line would you add?

# Answer
> 6 votes
Drupal 8 does not have a `{cache_form}` table; in-progress `$form_state` got moved to the key-value store. The KV store for forms defaults to the database (there are core classes to support database and memory for KV). And the KV store and cache backends are different concepts in Drupal 8 (the former is for persistent data with expiration, the later is for ephemeral data with expiration), so you should be fine.

---
Tags: 8, forms, caching
---


# Question
Title: How to enable endpoint without RESTUI module?
I've created a rest Plugin that returns some data at `/api/custom/{nid}`.

Drupal core provides four modules that together can handle RESTful API, these are: Serialization, RESTful Web Services, HTTP Basic Authentication, HAL. I can't find any information how do I enable custom (or even build-in) API endpoint without restui module.

So the question is:

* Is there a way to enable custom rest resource without restui module? If so, how?
* Is there a way to enable build-in rest resources without restui module? If so, how?

# Answer
Ok, I finally found out how to enable an endpoint to be accessible without RESTUI module. This gives more flexibility to keep everything in code and one custom module.

**This instructions applies to Drupal \> 8.2 only.**

First you need to know how to create a custom rest resource, which can be found here or here.

So, let's say we have a custom module named 'custom\_rest' that contains REST plugin resource. Module returns only a single node json data. The structure of the module looks like this:

```
|custom_rest
|--|config
|  --|optional
|      --rest.resource.custom_rest_resource.yml
|--|src
|  |--Plugin
|     |--rest
|        |--resource
|           --CustomRestResource.php
|--custom_rest.info.yml
|--custom_rest.module

```

The most important files for us are:

```
 -  CustomRestResource.php
 -  rest.resource.custom_rest_resource.yml

```

CustomRestResource.php is a plugin with the custom rest resource. My get method looks like this:

```
  public function get($nid) {
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }
    $data = node_load($nid);
    return new ResourceResponse($data);
  }

```

This method returns a json node structure for an existing node. That's it, it's just for testing purposes only. It can do anything you want.

As for the enabling an endpoint it needs an extra yml file that should be located in:

```
/custom_rest/config/optional/rest.resource.custom_rest_resource.yml

```

The contents of the rest.resource.custom\_rest\_resource.yml file for this particular endpoint looks like this:

```
langcode: en
status: true
dependencies:
  module:
    - custom_rest
    - hal
    - serialization
    - user
id: custom_rest_resource
plugin_id: custom_rest_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - hal_json
      - json
      - xml
    supported_auth:
      - cookie

```

Of course, the name of the file, dependencies, id, plugin\_id, configuration should be adjusted to your needs.

If you have all of this and you will enable the module this endpoint should be accessible in browser or any app that handles http requests (postman, etc.).

Notice that this yml file won't be triggered if you already enabled the module. If you've added this file after module enable, you should uninstall the module and enable it again.
> 4 votes

# Answer
The other option is to use Views. It gives you a lot more options.

Below are few links where you can see some basic examples:
> 0 votes

---
Tags: 8
---


title: Enabling text editor on statuses form

text:
# Question
Title: Enabling text editor on statuses form
I was looking to use a text editor with statuses. Statuses is neither a Node nor an Entity. I searched a lot and found a simple solution. I just has to replace `'#type' => 'textarea',` with `'#type' => 'text_format',` in statuses/includes/utitlity/statuses.form.inc file. It converted it to a text format enabled textarea, **but there are few problems**.

1. Ckeditor is not respecting the character limit set by the module, so I found maxlength module and added `'#maxlength_js' => TRUE,` but it does not make the default work. Instead it adds a separate character counter. The markitup library is respecting this, but I want to use ckeditor as I think it is the best editor. **How to overcome it?**
2. The form is now scrollable after enabling ckeditor. I want to disable scrolling. The resizeable was already set to FALSE in the module, but ckeditor is not respecting it. **How to solve it?**
3. How to hide paragraph counter and word counter? I have not enabled it from settings. I was there by default.

Here is the SnapShot of the statuses form.

Code was added like this: Only 2 modifications were made to the code, the rest is the original code of the module.

```
$form['fbss-status'] = array(
    '#type' => 'text_format',
    '#rows' => variable_get('statuses_box_rows', 2),
    '#maxlength_js' => TRUE,
    '#maxlength' => 140,
    // 508 compliance: add a label, but visually hide it
    '#title' => t('Status'),
    '#title_display' => 'invisible',
    '#default_value' => $default,
    '#attributes' => array('class' => array('statuses-text', 'statuses-text-main')),
    '#resizable' => FALSE,
    '#prefix' => '<div class="statuses-textarea-wrapper">',
    '#suffix' => '</div>',
    '#weight' => -40,
  );

```

# Answer
> 1 votes
Regarding your 2nd and 3rd questions, you could try this answer here: https://drupal.stackexchange.com/a/62407/12701

Instead of hacking the statuses module, you should create your own module and use hook\_form\_alter() like this:

```
/**
 * Implements hook_form_alter().
 * Adding WYSIWYG editor to statuses
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'statuses_box':
      $form['fbss-status']['#type'] = 'text_format';
      $form['fbss-status']['#format'] = 'filtered_html';
      break;
    case 'fbss_comments_edit':
      $form['status-comment-edit']['#type'] = 'text_format';
      $form['status-comment-edit']['#format'] = 'filtered_html';
      break;
  }
  if (substr($form_id, 0, strlen('fbss_comments_box')) === 'fbss_comments_box') {
    $form['status-comment']['#type'] = 'text_format';
    $form['status-comment']['#format'] = 'filtered_html';
  }
}

```

---
Tags: 7, forms, wysiwyg
---


title: View field with JavaScript code in it

text:
# Question
Title: View field with JavaScript code in it
I have content type which has text field. Each node has its own javascript code which is set in to the text field. Text field is PHP Code format.

When I add this field to Views block site load ONLY the javascript in that text field. Whole other drupal content is not loaded. When I remove this field from views then site works normally.

This script works on full node but not in the Views. What can cause this? What ways to fix it?

Script is from Tradedoubler (third party advert) :

```
<script type="text/javascript">
  var uri = 'http://url.com' + new String (Math.random()).substring (2, 11);
  document.write('<sc'+'ript type="text/javascript" src="'+uri+'" charset=""></sc'+'ript>');
</script>

```

# Answer
> 0 votes
Try using the Views PHP module. First, make the field with the javascript be excluded from the display (check the box for this, don't delete the field). Then add a php field to the view, and then have it print the field with the javascript via the replacement pattern. You can also use PHP to manipulate it, write more javacript, etc. This is the only way I have found to add javascript to view rows.

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


title: Rating system - Five star problem

text:
# Question
Title: Rating system - Five star problem
I tried to use 2 modules, FiveStar and Rate to put rating system on a new custom content I created but neither worked.

When I try to put FiveStar in a field of my content it shows me this error:

I don't know why but if I don't put any star on default rating it won't work.. So I have to put my products since they are created all by default with some rank (from 1 to 5 stars or 10 if I change the number or stars they can have)for this to work and that's kind of bad..

I wanted my products to come with no evaluation/rating when they are created.

EDIT:
Now with the rate module I manage to do this, but I now how I change from thumps up/down to stars (from the module or a costumized ones) ?

# Answer
I recommend using the Votingapi Widgets module based on the Voting API in D8, it works and does the same as Fivestar.

Some more details about this module (from its project page):

> A flexible field based Voting System based on Voting API.
>
> You need Drupal Version \>= 8.2.3. (Multiple form instances on a page).

**Be aware**: only an alfa3 release for D8 as of right now.
> 2 votes

---
Tags: 8, entities, rating
---


title: Error when updating modules with Drush

text:
# Question
Title: Error when updating modules with Drush
Iv managed to install Drush to the site on Go Daddy shared hosting(thanks to the greate tutorial!). Simple commands run without any errors, but when I try:

```
drush pm-update ctools

```

It returns:

```
    -bash-3.2$ drush pm-update ctools
The external command could not be executed due to an application error.                                                                                [error]
                                                                                [error]

<br />
<b>Parse error</b>:  syntax error, unexpected '{' in <b>/home/content/XXX/XXX/drush/includes/environment.inc</b> on line <b>518</b><br />
, code: <em class="placeholder">255</em>)
Update information last refreshed: Wed, 04/18/2012 - 06:11

Update status information on all installed and enabled Drupal projects:
 Name                                                   Installed version     Proposed version  Status
 Address Field (addressfield)                           7.x-1.0-beta2         7.x-1.0-beta2     Up to date
     Administration menu (admin_menu)                       7.x-3.0-rc1           7.x-3.0-rc1       Up to date

    ...

Security updates will be made to the following projects: Chaos tool suite (ctools) [ctools-7.x-1.x-dev]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n):

```

The code of the line 518 in environment.inc

is

```
517      try {
518      $db = new PDO($constr, $creds['user'], $creds['pass']);
519      $db = null;
520     }

```

Drupal is 7.12, Drush 5.1

What can be the reason of this error?

Also In hosting cotnrol panel site is on PHP 5.3 But php -v returns 5.2.17 is it ok?

# Answer
> 1 votes
This is a common issue in the Drush queue on drupal.org and the consensus is that its related to your version of PHP that runs in client mode versus the version running on your web server, ex. http://drupal.org/node/1402120 or http://drupal.org/node/436968. Of course, some of these were related to PHP 5 vs PHP 4 issues and you're just one version behind on the client but it may help to alias your php version as explained here:

```
echo 'export PATH="$HOME/packages/bin:$PATH"' > .bash_profile
mkdir -p packages/bin
ln -s /usr/local/php5/bin/php packages/bin/php

```

Patrick Kenny is right though that this parse error won't affect your upgrade in the end.

# Answer
> 0 votes
We had a similar problem on a machine. The reason was that the php running on cli did not have some extensions installed. In our case it were the extensions `gd`, `xml` and `SimpleXML`.

We solved that by installing the packages via `apt-get install php5.6-gd`and `apt-get install php5.6-xml`.

---
Tags: 7, drush
---


# Question
Title: No one can login and access denied message
The site worked till yesterday and just now it's behaving strangely.

* ~~The site is **not** created with features, an archive dump including the code and database is copied to server, and the old installation is replaced with the new one manually (unfortunately).~~ Now it is irrelavant also happening on local server.
* No caching module is installed. Session API is not also installed.
* Theme is set to 'seven' (core admin theme, just in case).
* The watchdog does not contain any error, warning or info except the usual "session opened for user xyz";
* The settings file does not contain any special cookie directive. It never did.
* The site is running on php 5.6, Apache 2.2, CentOS 6. PHP is running as fast-cgi. Same as always.
* It's Drupal 7.

I go to example.com/user/login, enter username and password, the form is submitted successfully, the page is redirected to example.com/user/%uid (tried both uid 1 and other users). and boom! I get an *access denied*. And the user is not logged in.

If I truncate the **sessions** table with `truncate table sessions` I can log in once and once only, with any user. Then again no one can log-in not even uid 1.

Also with a password reset link (using the command `drush uli` I can log in with no problem).

I disabled *all* contrib modules and theme, but the same problem persists.

What is causing such problems with sessions? any ideas?

# Answer
The problem was ip\_geoloc module. It was messing up $\_SESSION variable, a solution is given on the issue queue (for now!) and the module author agrees with it. It's highly probable that it is happening because of a mis-configuration by me. The user was successfully logged in but immediately their session was invalidated. Somehow disabling it was not enough and it's directory had to be moved out of Drupal root. I am 100% sure not any of it's functions or APIs are used anywhere else. Maybe some cache problem?

### Lesson learned:

When having signing-in problem, try to check the $\_SESSION variable **on the server** using devel and it's helper functions (e.g dpm, dsm, dd, ... or as a last resort var\_export) and not with you google/firefox developers console.

This is the third time I'm facing this strange behavior and the first time I was able to fix. If you are having this problem, try to follow this checklist:

### Ask yourself:

* Does truncating the *sessions* table fix the problem?
* Does *forcing a change for user password* fix the problem?
* Have you added any particular configuration to your *settings.php*? e.g base\_url, cookie\_domain, ...
* Does *UID 0* exist in your database (i.e anonymous user)?
* Is any *redirection* module installed? search404, redirect, global\_redirect,...
* Do you have a *custom module* enabled?
* Is there any problems with your *theme*?
* Do you have any path altering modules, e.g path\_alias?
* Do you have any module changing the log-in behavior? e.g logintoboggan
* Have you enabled any caching module? e.g authcache, memcache, session\_cache, boost, varnish, ...
* Do you have any access control module enabled? e.g workbench, content\_access, acl, og\_access, ...
* And finally, have you enabled any module which changes the user $\_SESSION? e.g session\_api, session\_cache, ip\_geoloc, ...

### Places to look / Things to do

* Look at drupals watchdog messages. If you can not log-in, use drush watchdog-show --tail to see what's happening.
* If running apache and mod-php, look in apache's error log, usually at /var/log/apache/error\_log for \*nix systems.
* If running php-fpm, see the php-fpm log, make sure there is no communication problem with php daemon, such as headers are not lost. if you see no error log try running your site with drush/php internal server. the command is `drush rs` or `drush rs the.ip.goes.here:thePort`
* make a fullbackup, disable all modules with this command AFTER making a full backup (you can make a backup with `drush ard` or just database `drush sql-dump > db.sql` or use backup\_migrate module)
`drush dis -y $(drush pml --no-core --status=enabled --pipe)` -\> this command only works in \*nix systems I don't know the direct translation for windows.
* Set your default theme to something... safe! such as seven or garland. If you can not log-in use this drush commands:
`drush en seven && drush vset theme_default seven`;
* Monitor $\_SESSION variable with any debugging tool, see if it's content are correct, ok, healthy.
* For all the processes and daemons involved in serving a request (nginx, php-fpm, apache, varnish...) make sure they all have write access to their tmp directory.

Good luck debugging!
> 15 votes

# Answer
What worked for me was enabling and configuring the `$cookie_domain` variable in settings.php (because I have a site that can be accessed by 2 different domains).

Pay attention to the comment before this variable! The domain name must start with a period. EX:

`$cookie_domain = '.example.com';`

Good luck!
> 4 votes

---
Tags: 7, users, sessions
---


title: Access denied error after login

text:
# Question
Title: Access denied error after login
When i log in to drupal doesn't matter with any account either admin or normal user. I get error Access Denied. I then again try to login and it works fine. What is that problem? My theme was shipped with its own drupal so i guess they might have done some thing wrong.

I feel some session issue because my error messages on drupal valiation forms also occurs one page delayed. So if a submit a invalid form the page post back and hight light the fields with red color but don't show any message. When i go to any other page the error message dive comes up. This happens on both front end and admin panel forms.

Update: I forgot to mention that i am using a custom template for user login page.

Here is the code for my user login template. I am not sure if this is causing issue or something else.

```
<?php
     // we aren't getting messages, get them manually
            if (isset($_SESSION['messages'])) {
                echo '<div class="messages">';
                foreach($_SESSION['messages'] as $type=>$messages) {
                    echo "<p class=\"$type\">".implode("</p><p class=\"$type\">", $messages)."</p>";
                }
                echo '</div>';
                unset($_SESSION['messages']);
            }
?>
<h1>Login</h1>
<div class="qualia-user-login-form-wrapper">
  <?php print drupal_render_children($form) ?>
</div>

```

Updatd Part: I found the culprit i.e my own module

Actually i got the problem. But coudln't find the work around. I have a custom module that redirects user to paypal when he is creating account on my site. I put the `$form` and `$form_state` values in session and when the user return back from paypal i pass both variables to `user_register_submit` function to resume the process of creating account. For this purpose i have to put `@session_start()` at the start of my module file. This works fine in case of my paypal process. But because of `sesion_start()` my login flow is disturbed. What can i do to resolve this issue as i need session to hold form and form state

# Answer
What worked for me was enabling and configuring the `$cookie_domain` variable in settings.php (because I have a site that can be accessed by 2 different domains).

Pay attention to the comment before this variable! The domain name must start with a period. EX:

`$cookie_domain = '.example.com';`

Good luck!
> 2 votes

# Answer
Try rebuilding the site's permissions. Goto Reports -\> Status Report. About half way down the page you'll find a link to rebuild permissions.
> 0 votes

---
Tags: 7, theming, users, sessions
---


# Question
Title: How to extend the basic user object upon installation?
I need to build a module to handle Users profiles, and need to extend automatically the basic Drupal user object upon installation. For Drupal 7 I found a way with:

```
field_create_field($field);

```

But this function is not available in Drupal 8, BTW totally noob on Drupal, Learning while working on it.

# Answer
Fields, like most other things, are configuration (entities) now.

That means you don't have to write code to create them, you can simply create them in the UI, then export them through the Configuration management UI and put the relevant files into your `config/install` folder. Drupal will automatically import all your configuration from that folder.

Note that a field commonly consists of 4 parts:

1. The field storage, a file named `field.storage.user.yourfieldname.yml` (or node, comment,... for other entity types). This defines the field and storage relevant configuration.
2. The field, a file named `field.field.user.user.yourfieldname.yml` (user is special because there is only one bundle, for nodes, it would e.g. be node.article). This defines that a field is available on a specific bundle and includes configuration like the label.
3. One or multiple form displays, for example named `core.entity_form_display.user.default.yml`. User by default has two form modes, default and register. Node by default has only one. This stores the widget configuration for the field.
4. One or multiple view displays, for example `core.entity_view_display.user.default.yml`. This stores the formatter information for a specific view mode.

The first two files can just be copied to your `config/install` folder. The other two are bit more complicated, because they contain the widget/formatter configuration for all fields of that entity type, bundle and form/view display combination. So in the case of user for example, you do need a bit of code to add the configuration to the existing form/view display. See node\_add\_body\_field() for example code. You can get the exact settings from the exported files.

If you own the bundle, for example, if your module defines a node type with a numer of fields, you can also just add those form/view displays to the configuration folder.
> 13 votes

# Answer
You may also use Drupal console to create fields. Which is less effort, than the above.
> 0 votes

---
Tags: users, 8
---


# Question
Title: How to use Simple hierarchical select on a view starting at second level taxonomy?
I am using the Simple hierarchical select on a view for a an exposed taxonomy term, but I want the first level of the taxonomy to be preselected, so that the user can only choose the second and third levels.
I tried to do this by adding jquery to change the first element, but it doesn't load the second level taxonomy then.

Is there a parameter in this module so I can preselect the first level taxonomy term and not let the user change that?

# Answer
I made a patch to allow you to choose the parent taxonomy at a level lower than the root. I will post a link to it soon . If anyone wants to ask me about it in the meantime please write to me.
> 0 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: How to set Disqus Share link to window.location.pathname + window.location.search?
Version Disqus 8.x-1.0-rc3
Drupal 8.2.5

I have a page that is built up of multiple nodes using **Twig Tweaks**. One of the nodes has the **Disqus comment** field. Module runs smoothly and everything, however, the **Share** url is to the node/#### instead of the page.

**Tried the following but to no avail:**

1. Updated the Disqus field's default identifier to **\[current-page:url\]**.
2. Overrode the node's Disque identifier manually on /node/####/edit page
3. Tried modifying `modules/disqus/js/disqus.js` (w/drush cr), so that

```
disqus_title = document.title;
disqus_identifier = window.location.pathname + window.location.search;

```

I thought #2 would work above, but it still is tied to the entity's node id. The **Share** link always goes to /node/####.

Any assistance in this matter would be greatly appreciated.

EDIT: Just noticed that \[current-page:url\] does not include the search portion of the url. The URL looks like **/something/node-title-text-here?page=5**

# Answer
So the solution was to add my own Javascript file and just clear the drupal settings for disqus like this:

1. Added Javascript file to `modules/custom/MYMODULE/MYMODULE.libraries.yml`

```
disqus-overrides:
  version: VERSION
  js:
    js/disqus_overrides.js: {}
  dependencies:
    - core/drupalSettings

```
2. Created a new file in `modules/custom/MYMODULE/js/disqus_overrides.js`

drupalSettings\['disqus'\]\['identifier'\] = ''; drupalSettings\['disqus'\]\['title'\] = ''; drupalSettings\['disqus'\]\['url'\] = '';

3. Then force this file to be loaded on every page load in `modules/custom/MYMODULE/MYMODULE.module` (this could be optimized to only load on those pages with the Disqus comment field, but I don't know how yet):

function MYMODULE\_page\_attachments(array &$attachments) { $attachments\['#attached'\]\['library'\]\[\] = 'MYMODULE/disqus-overrides'; }
> 0 votes

---
Tags: 8, comments
---


# Question
Title: When adding Custom Blocks the weight is changed for the rest of the blocks
We are using custom blocks very extensively. We are also using block visibility groups and Domain Access. At this point when we make a new block it changes the weight of many of the other blocks at what seems to be random intervals.

Has anyone else had this issue?

# Answer
If you have blocks that have the same weight, that may trigger a bug where your blocks get shifted. At least, this is something I have experienced with views filters in D7, and I found a bug report here regarding a similar weight issue in D8 with taxonomy terms: https://www.drupal.org/node/941266

Ensure you are able to see the numerical weights of the blocks, and make sure they all have distinct weights.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: Drupal multi site 404s, sub directory site subpages going to default site
We have a strange set of errors going on with a dev (and stage) version of our drupal multisite. We have some sub directory sites, and some sites server up on different urls. One URL is an internal one to the Host. The other is an external one (that goes through a firewall).

The essence of the problem is this

* the sub directory site homepage displays fine, but any sub pages you click through to come up as 404s -- the 404 that is thrown is on the default site. This happens with sub directory sites on both URLs (external and internal).
* I am unable to access site pages using index.php?q=
* Some pages that get served up properly, are still showing up as a 404. This doesn't seem consistent on all sites, but it seems weird to begin with.

What I know

* The .htaccess is being used by the sites
* ModRewrite is on.
* At our request, the ISP put some restrictions on one of the URLs.
* The same structure works fine on our production site (minus the restricted URL)
* sites.php is working fine, so far as I can tell.

What are the things that we could still have configured wrong (our hosting company is equally perplexed)? The problem seems to coincide with locking down the internal URL (to be only visible to VPN).

For now, I can share this URL: http://contentdev.sierraclub.org/coal Click on a sub link. Compare to http://content.sierraclub.org/coal

Any ideas would be very much appreciated.

# Answer
You didn't mention anything about sites.php, so I'm going to guess that's where the problem resides.

Google it: https://www.google.com/#q=drupal+multisite+sites.php
D7 example: https://api.drupal.org/api/drupal/sites!example.sites.php/7.x
D8 example: https://api.drupal.org/api/drupal/sites!example.sites.php/8.2.x

Please post your sites.php file if you're unable to fix the issue after taking a look.
> 0 votes

---
Tags: multi-sites, subsites
---


# Question
Title: Submit is not working for contact form which was embedded by AJAX
I'm trying to add contact form with AJAX callback, called from another form. Form is embedding as well, but when I submit it only page is reloading and form doesn't send any data (in my case it's a contact form, and I can't see any created contact message in backoffice after submitting).

```
function somemodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['somefield']['widget']['#ajax'] = [
    'callback' => 'somemodule_form_conditional_ajax',
    'method' => 'html',
    'wrapper' => 'form-conditional-ajax-wrapper',
    'event' => 'change',
  ];
  $form['#suffix'] = '<div id="form-conditional-ajax-wrapper"></div>'

}

function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $output = \Drupal::service('entity.form_builder')->getForm($contact_message);
  }

  return $output;
}

```

# Answer
I just had this issue myself. Try this:

```
use Drupal\Component\Serialization\Json;
use Drupal\Core\Render\BubbleableMetadata;

function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $form = \Drupal::service('entity.form_builder')->getForm($contact_message);
    $output = render($form);

    $data = BubbleableMetadata::createFromRenderArray($form);
    $attachments = $data->getAttachments();
    $settings = '';
    if(!empty($attachments['drupalSettings'])) {
      $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
      $settings .= Json::encode($attachments['drupalSettings']);
      $settings .= ');</script>';
    }

    $output .= $settings;
  }

  return $output;
}

```

The only thing I'm unsure about is if the $output requires an array - what I've given you is a string. So it may not work.
> 1 votes

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


# Question
Title: Get paths of files attached to the node from field name
How can I get the paths (URLs) of files attached to the node from field name in Drupal 8?

I tried using Drupal 7's `node_load()`, but that does not return paths of the files:

```
$node = \Drupal::routeMatch()->getParameter('node');
$node = node_load($node->id());
var_dump($node);

```

# Answer
> 5 votes
You can get it like this:

`$file_uri = $node->field_machine_name->entity->getFileUri();`

If your field allows for more than 1 value, then:

```
$file_uris = array();
foreach ($node->field_machine_name as $value) {
  if ($value->entity) {
    $file_uris[] = $value->entity->getFileUri();
  }
}

```

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


# Question
Title: Grouping content by Years (For eg Archive 2014-2015 or Archive 2014-16)
I want to group my content type to group by years in views, for example `Archive 2014-2015` or `Archive 2014-16`. How can I get this groupings?

```
Archive 2013-2014
-COntent 1
-Content 2
-Content 3

Archive 2015-2016
-COntent 1
-Content 2
-Content 3

```

# Answer
> 0 votes
The key challenge you'll face here is that neither Views nor Date modules provide aggregation options for date-based fields.

This can be solved by using the Views Date Format SQL module. It adds a nice little check-box that allows you to group dates by a custom formatted string, as shown in this example also:

In the above example, the **custom date format** is set to "M Y" (which translates to Oct 2015 for example), and the box for "Use SQL to format Date" was checked. This is the only configuration needed.

---
Tags: 7, views, datetime
---


# Question
Title: How to send e-mail to node author 1w before date field in node?
I've got a content type with date fields. What I'd like to do is send a reminder e-mail to the post author one week before the value of the date field, with the rules module, or in another way. How would you go about this?

# Answer
# Requirements

Rules, Rules UI, Rules Scheduler, Date, and Date API modules

### Add date field

Go to your content types Manage Fields and add a field of type Date.

I called mine `Deadline`, machine name: field\_deadline

## Create a Rule

Action: After saving new content Type: Article

This is all you have to do for now, will get back to this rule later.

# Create a component

Component Plugin: Rule

**Component action**

* Add action of **`Fetch Entity by Property`**

* Add action **`Send Mail`**

**To:** `[author-email:0]`

# Edit your Rule now

* Add action of **`Schedule component evaluation`**. In SCHEDULED EVALUATION DATE click on the grey `switch to data selection` button. (not visible in screenshot since I already click it)

---

# Testing

Go to the components tab and click on schedule

You'll need to click those grey `switch to ...`  buttons to get it to look like mine.

Put a node ID in the last one.

---

### Important

Your e-mail will get sent once the time has been reached, but **also once cron runs**. So if your cron runs once a day, it may not get sent until the day after, so you may need to adjust your cron to run more often.

You might want to use Ultimate Cron so you can schedule specific crons to run at different intervals, instead of running everything every x minutes, days, hours.
> 2 votes

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


# Question
Title: Manage/Assign Roles to Users Other than Administrators
I was asked to create a module that allows a user with the specific role to assign roles to other users w/no 'administer user' permissions or not an administrator. The user must not be allowed to edit info about the users with 'administer user' permission/admin.

How can I do this? Do I have to create a custom module for this? Is it possible to use Views module for this?

# Answer
> 2 votes
**NOTE:** Since Drupal 6 is un-supported now (check announcement), you won't get a module which still have the D6 version actively supported. Also don't expect the module to be supported for any issues.

You can check the Role Delegation module, which allow users to set user roles to other user. Following is the module description from module page:

> This module allows site administrators to grant specific roles the authority to assign selected roles to users, without them needing the administer permissions permission.

The last release of this module for Drupal 6 version was made available on 9 Dec 2010, you can download it from here.

---
Tags: 6, users
---


# Question
Title: Irreversible error when trying to upload image (too big) in a clone
In all of my node types I have several image fields. If I delete one image and then uploads a new one and then repeats this for a second and third image field, all works as expected.

BUT if I do this same thing in a clone of the node, WITHOUT saving the new node first, I get this message:

> Irreversible error, Uploaded file probably exceeds the maximum file size limit (2 mb), supported by this server

(something like that, translated from my language), directly when I hit the delete button for the second image. Before I even try to upload this second image.

The workaround for the time being is to save the clone first and then delete the old images and upload the new ones.

But what is this? I have never seen this behaviour before. My Drupal version is 7.52 and I use the Node clone module, version 7.x-1.0, together with the Node clone tab module, version 7.x-1.1.

# Answer
> 1 votes
What module are you using to clone a node? I recommend the Replicate module A workaround on your case now would be to alter the replicate functionality for the replication of image fields. You can clear the images field in code or copy the files yourself.

Here is an example for the replicate module to copy the images so your nodes don't use the same images because then you have unwanted behaviour on delete of one of the nodes (deletes the images):

```
/*
 * Implements hook_replicate_field_FIELD_TYPE().
 */
function replicate_custom_replicate_field_image(&$replica, $entity_type, $field_name) {
   // List of affected fields.
   $fields_list = array(
     'field_xxxx' => 'contenttype1',
     'field_xxxxx' => 'contenttype2',
     'field_xxxxxx' => 'contenttype3',
     'field_xxxxxxx' => 'contenttype4',
     'field_xxxxxxxx' => 'contenttype5',
   );

   if (in_array($field_name,  array_keys($fields_list))) {
     // Fetch field instance info.
     $field_instance = field_info_instance($entity_type, $field_name,           $fields_list[$field_name]);
     // Build destination path.
     $destination_path = 'public://' . $field_instance['settings']['file_directory'];
     foreach ($replica->{$field_name} as $language => $field) {
       foreach ($field as $key => $value) {
         // Fid can't be empty.
         if (!empty($value['fid'])) {
           $new_file = file_copy((object) $value, $destination_path);
           $replica->{$field_name}[$language][$key] = (array) $new_file;
         }
       }
     }
   }
 }

```

---
Tags: 7, files
---


# Question
Title: How do I push module update in a cached production environment?
I don't manage to update Flag module in remote server, while it worked like a charm on local environment. The stage site **is cached with Zend opcache**, Apcu, Varnish and Redis. I suspected Opcache was faultier but no way to get it work.

**The steps I did (local dev) :**

* `drush up flag -y`
* `drush cc all`. Tested flag features, OK.
* Commited & pushed files to stage on a flag branch

**The steps then on remote server :**

* `git checkout flag`
* Reset Opcache various times (thanks to this great Opcache GUI)
* Saved database
* Ran `update.php`, which returned

```
flag module
7300 - Rebuild the class registry due to classes moving files.
7301 - Rename {flag_content} table to {flagging} and {flags} table to {flag}.
7302 - Rename database columns on the {flag} table.
7303 - Rename database columns on the {flagging} table.
7304 - Rename database columns on the {flag_counts} table.
7305 - Convert flag roles to permissions.
7306 - Convert flag view modes settings.

```
* Ran *Apply pending updates*, which retunred *An unrecoverable error has occurred, Ajax error, http status 200*, followed by 4 notices. These notices are known, but caused no update crash on local site.
* if I go to the "error page", I'm sent back to Review updates page.

If I try to visit dblog, I have this fatal php error : `Class 'flag_flag' not found in profiles/commons/modules/contrib/flag/flag.module on line 1948`. But if I check the remote files, I can find that class in `profiles/commons/modules/contrib/flag/includes/flag/flag_flag.inc` .

I invalidated that file namely in Opcache and invalidate full Opcache. I also checked in `varnish.vcl` that `update.php` is in the list of bypassed URL.

Then after a while, Varnish finds backend server is not responding and boom : *Error 503 Backend fetch failed*, ending restarting php5-fpm...

To be honest, I understand about nothing anymore, "*eating my hat*" or "*banging my head*" or how would you say that ? Help really welcome !

# Answer
> 1 votes
Short answer : **make extensive use of drush** !

This was quite straightforward and successful, though I'm still not really sure if I have to empty both opcache and Varnish. This would be a huge performance hint on production server. IMO the best would be to invalidate only the changed files in opcache and voilà ?

**Steps I did (local dev) :**

* `drush up flag -y`
* `drush cc all`
* tested flag features, OK.
* commited & pushed files to stage on a flag branch

**The steps then on remote server :**

* `git checkout flag`
* `varnishadm -T 127.0.0.1:6082 -S /etc/varnish/secret` (enter Varnish Cli)
* `varnish> ban req.http.host ~ dev.example.com && req.url ~ .` (clear varnish cache)
* reset Opcache with Opcache GUI
* `drush updb`
* `drush rr` (optional in that case since this was performed in `flag_update_7300`)

---
Tags: 7, caching, updating
---


title: Remove "Generator" meta tag?

text:
# Question
Title: Remove "Generator" meta tag?
How can I remove the *Generator* meta-tag in Drupal 8?

```
<meta name="Generator" content="Drupal 8 (https://www.drupal.org)" />

```

Can this be done with few lines of code?

# Answer
Basing on the patch provided in Remove Generator META tag & X-Generator for Drupal 8 version! this is the code that would achieve that.

```
/**
 * Implements hook_page_attachments_alter().
 */
function HOOK_page_attachments_alter(array &$attachments) {
  foreach ($attachments['#attached']['html_head'] as $key => $attachment) {
    if ($attachment[1] == 'system_meta_generator') {
      unset($attachments['#attached']['html_head'][$key]);
    }
  }
}

```
> 18 votes

---
Tags: 8, meta-tags
---


title: Get the alt for the image on views twig

text:
# Question
Title: Get the alt for the image on views twig
I've got an image field, in which I'm showing the image using url by setting the relationship for that field on 'Advanced' tab to get the url of the field.

I'm getting the url of the field as

```
{% set image = file_url(fields.uri.content|striptags|trim) %}
    <div class="mob"><img src="{{ image }}" class="testimonial-mob-img" alt="" /></div>

```

I would like to know how to get the alt of the image on `views-view-fields-view-machine-name.html.twig`.

# Answer
> 5 votes
A simple solution is to add `image` again as a field and Rewrite Results:

Now in your template:

```
... alt="{{ fields.field_image_1.content|striptags }}" ...

```

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


# Question
Title: How to stop Watchdog from logging "DEBUG" errors?
I get this error in my logs a lot:

```
Deprecated function: Methods with the same name as their class will not be constructors in a future version of PHP; views_many_to_one_helper has a deprecated constructor in require_once() (line 127 of C:\...\sites\all\modules\contrib\ctools\ctools.module).

```

This is really not important to me and I don't want it filling up watchdog. Is there any easy way to tell Watchdog to not log these errors? Where can I change which errors get logged by watchdog?

# Answer
> 1 votes
The Drupal watchdog includes the errors raised by PHP, such as the one you mention.

It might be possible to use hook\_watchdog to filter out certain errors. However, it seems easier to change the PHP error level on your `settings.php` file, so that PHP does not complain about your ctools module.

---
Tags: 7, log-messages
---


# Question
Title: How to add classes to BODY tag dynamically based on page path/depth?
How to add classes to the body tag dynamically such as this example below?

-Home
-Cities
--Melbourne `<body class="melbourne">`
---Theme Parks `<body class="melbourne theme_parks">`
---Restaurants `<body class="melbourne restaurants">`
--New York `<body class="new_york">`
---Theme Parks `<body class="new_york theme_parks">`
---Restaurants `<body class="new_york restaurants">`
-Contact Us `<body class="contact_us">`

Drupal newbie here and without programming background. Therefore, I'd much appreciate if you could be as detailed as possible when sharing a solution.

# Answer
To expound on Nikhil Mohan's answer, you can implement `template_preprocess_html()` inside your theme's template.php file. Read the documentation on Overriding Themable Output to understand the basics of what is going on here.

Within this function, you have access to the variable `$vars['classes_array']`, which holds a list of classes that will be applied to the HTML `<body>` tag on the page.

Unfortunately, information about the current page's location in the menu is not immediately available. You could use `menu_get_item()` and then `menu_get_ancestors()` to get this information, but that is a lot of processing power for something that we can probably get to with a simpiler approach.

Assuming you are using the pathauto module to automatically create semantic paths for your content pages based on the menu path (i.e., your Melbourne Theme Parks page would have the path 'melbourne/theme\_parks') you can use the page's path to create the classes you are looking for:

```
function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

```

That's it. Drupal will now look at the path alias of the current page and add a class to the `<body>` tag for each chunk of the path alias.
> 37 votes

# Answer
You can make use of `template_preprocess_html`, which Preprocess variables for html.tpl.php

See also html.tpl.php

> Default theme implementation to display the basic html structure of a single Drupal page
> 1 votes

# Answer
Here is the module to add classes on body tag based on role or pages.

Common Body Class
> 1 votes

# Answer
Created the Body Classes Drupal module to assist with this. Feel free to create issues to add more body class integration points.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do you display fields created via the File Entity settings configuration?
I'm using the File Entity module, and it lets me modify the configuration settings, adding a few fields to a file type, but I can't seem to figure out how to get the custom fields I created to show up in the add content screen. Only the Alt text and Title values show up. What am I missing?

# Answer
> 1 votes
The fields aren't on the add content screen they are on the add file screen (because they are fields on the file entity).

So if you add files via the file/add page you can fill out those fields.

The media module has a feature so that when you upload a file to a node then it pops up the edit form to edit the fields on that file.

So you upload the file then fill out the extra file fields in a 2 step process and then save the node.

# Answer
> 2 votes
I was also looking for that functionality, and found this module does exactly that: File Entity Inline

> This module aims to provide the ability to edit File entities inline, as part of another form (such as nodes). This should enable the ability for reusable and site-wide editing of file properties, such as description, alt text, captions, bylines, etc.

# Answer
> 2 votes
In Drupal 8 you can archive this with core elements/modules.

1. activate the core module file\_entity
2. in your file type settings /admin/structure/file-types/manage/image add the extra fields a user should be able to use
3. in your contenttype (admin/structure/types/manage/CONTENTTYPE/form-display) choose the Widget "Editable file" for your image field

If you create a new node, you will be able to edit the extra fields of your image in a popup after clicking "Edit"

# Answer
> 0 votes
In Structure \> Content Types choose another widget for the image field from 'Image' to 'Media selector'. This will provide a better way to input and edit all the fields provided by File Entity.

---
Tags: 7, nodes, entities
---


title: Node with 450+ fields, server timeout

text:
# Question
Title: Node with 450+ fields, server timeout
I have a node with 450-500 fields which I have already splitted in small forms that are being load via ajax.

Anyway, when I get the node form before splitting it, the function `_field_invoke` (at `field.attach.inc`) is taking such a long time that makes the server return a timeout. I'm working in a 1 core 2.2MHz 3.5 GB

Is there any way to speed on this function? Otherwise, what alternatives do I have to speed on the load of a form with 450-500 fields?

**EDIT (@Neograph734 comment)**

We have a main form with 30 fields, most of them y-n that are used to select sub-forms. The form started to grow as the project was going on, and ended with 10 sub-forms form 30 to 50 fields each one.

We tried to split into different nodes and content types, but we could not find any viable solution: it must be a single document with digital signatures on each form that must be sync one each other, and the whole document follows a status that enables signatures to certain users (when a user has signed every signature field in all sub-forms, then the next user can start to sign). But in fact this is not the question here, as even if there were a better solution, we have no budget now to refactor the whole project, so we have to deal with a form of ~450 fields.

Right now we have rewritten `drupal_build_form` functionality to store every prepared sub-form in the cache and load them via ajax. So when a user requests the complete node, we give them the whole node but just the first 30 fields are rendered. We provide empty hidden `<div>`'s that will be filled via javascript with corresponding sub-forms, on demand.

Basically we keep the forms obtained after `drupal_retrieve_form`, `drupal_prepare_form` and `drupal_process_form` on the cache, but we assign a known `cid` and we store it via `cache_set`, so later on we can recover them, remove the fields that we don't want to render, render it and deliver it via ajax. In this way we do not render the whole form at once, but we do it on demand.

At first time we tried to remove the fields that were not going to be used by the user, but we found that we could not submit the form: Drupal said that there were missing fields (when a node is saved, the form must be submitted with all fields, even if they are with an empty value, otherwise it raises an error on node save).

So basically what we are doing is:

* Node load (get via browser or ajax) -\> look in `cache_form` table if we find pre-cached form or sub-form, their `cid` are like `form_form-petra_node_form-p0`, `form_form-petra_node_form-pa`, etc... and `form_state_form-petra_node_form-p0` and so on.
* If we find the pre-cached form, we load it and pass it through `drupal_prepare_form`, we remove not caching keys (`form_state_keys_no_cache()`) and then `drupal_process_form`. This is mostly the same as `drupal_build_form` does. Then we save the new form to `cache_form` (with `cache_set`, an expire time of 3 hours and a random generated `cid` as it would do `drupal_build_form`) in order to recover it later in post phase. If this is a sub-form, we merge the rendered sub-form with the parent one obtained via browser get (ajax is in charge of doing so).
* If the form is not there, we prepare it from scratch and save it to `cache_form` as pre-prepared form with expire = 0. Then we follow the same way described just before. This will nearly never happen, as we have installed a cron task that runs once a day and checks if the pre-prepared forms are there or not, and if not, the job prepares them.
* If it is a post, we recover the cached form with `form_get_cache` and we process it with `drupal_process_form`

So basically we have rewritten `drupal_build_form` in order to have "static pre-cached forms". This increased speed significatively but right now we are trying to achieve F1 speed with this system.

# Answer
> 2 votes
I doubt that with some many fields for a single node you'll be able to "*speed up that function*". However, whenever time (and budget?) permits, you should consider what's mentioned in the (illuminating) article titled "Relativity Model for Drupal". This is an introduction to it (quoted from this linked page):

> The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:
>
> * Data architecture and data modeling merging as a single step through a documentation procedure.
> * Customized user interfaces that cater to individual workflows throughout permission roles.
> * Multi-level relational data structures that relate to other multi-level relational structures.
> * Mimicking the concept of database joins within Drupal's UI's.
> * Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

Note the ***speed*** in the last item above ...

The *small handful of modules* (cfr. the last bullet) is like so (apart from Drupal core):

This same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".

---
Tags: 7, nodes, entities
---


# Question
Title: How to add class to embedded Paragraphs field-items?
I have a Paragraph field embedded on a node type. The Paragraph field type allows for many different Paragraph Bundles to be inserted into the node.

My mark up currently displays as (Drupal 7 zen Theme):

```
<div class="paragraphs-items paragraphs-items-field-paragraphs paragraphs-items-field-paragraphs-full paragraphs-items-full">

```

How can I add a class after each field-paragraphs? I would want to do this so that each Bundle has it's own class.

I've tried the following in my themes template file but it adds a class around the entire field and not on each Bundle:

```
    function mytheme_preprocess_paragraphs_items(&$vars, $hook) {

  // This will remove all the current classes
  $vars['classes_array'] = "";

  // You can now add the classes you want in this array
  $vars['classes_array'][] = "myclass";
}

```

# Answer
### Drupal 7

You *should* be able to copy this function into your `template.php` file of your theme:

```
/**
 * Process variables for paragraphs-items.tpl.php
 */
function mytheme_preprocess_paragraphs_items(&$variables, $hook) {
  $variables['view_mode'] = $variables['element']['#view_mode'];
  $variables['field_name'] = $variables['element']['#field_name'];

  $variables['content'] = $variables['element']['#children'];

  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name'] . '-' . $variables['view_mode']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['view_mode']);

  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'];
  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'] . '__' . $variables['view_mode'];

  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

```

You should also be able to do this for individual item:

```
/**
 * Process variables for paragraphs-item.tpl.php
 */
function mytheme_preprocess_paragraphs_item(&$variables, $hook) {
  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

```

After adding this function, clear the cache so it is registered. You can then check if either one are being called by adding a breakpoint or `print 'called'; exit;` if you do not have something like XDebug installed.

Note how the second function is `paragraphs_item` and not `paragraphs_items`. Both of these are defined as theme hooks in paragraphs.module.

You can even do this as well:

```
/**
 * Implements hook_preprocess_entity().
 * @param $variables
 */
function mytheme_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item' && $variables['elements']['#bundle'] == 'your_bundle') {
    $variables['classes_array'][] = 'your-class';
  }
}

```
> 2 votes

---
Tags: 7, theming, paragraphs
---


title: Link value not updating after 'Save'

text:
# Question
Title: Link value not updating after 'Save'
I've got a content type that has a link field in it. I added this link: ' https://wwwdev.ebi.ac.uk/interpro/' and saved. Then I realised this was an old address. It should have been 'https://www.ebi.ac.uk/interpro/' so I went back in, added the new address, and saved again. But the value didn't change! It was still showing 'https://wwwdev.ebi.ac.uk/interpro/'. Here's what I've done:

* Flushed the Drupal caches
* Flushed the browser cache
* Tried in a new private/incognito window in another browser
* Checked the database - it has the correct value, not the one showing on the page
* Tried another url in the link field (like 'www.google.com') and that works fine
* I put the correct address back in the field and it shows as the wrong address, even though the wrong address doesn't exist in the database.
* Tried adding the correct address to the body field and it was transformed to the wrong address!
* In 'Manage display' I tried the different settings for the link field. 'Domain as link' resulted in the right domain showing in the link text ('www.ebi.ac.uk') but with the link 'https://wwwdev.ebi.ac.uk/interpro/' in the `href` attribute.

Does anyone know what might be happening? I'm not using Conditional Fields, incidentally.

# Answer
> 0 votes
Okay, I fixed this. It was a legacy script in html.tpl.php. What I should have tried in my debugging was to switch theme. That would have at least narrowed it down to the theme layer.

---
Tags: navigation
---


# Question
Title: Multi instance Drupal on single server. Is SSO possible to be implemented?
may I know if we can configure single sign on , on a single server that have 2 Drupal instance running in parallel?

# Answer
I see that this answer is late but, yes. I am setting that up now but still working through some config.

1. I created a D7 installation called auth.local.domain.com (these are currently only on my dev machine). For this instance I installed oauth2\_server and openid\_connect\_sso modules
2. I created a separate D7 installation called client1.local.domain.com. Here I installed the openid\_connect and openid\_connect\_sso modules.
3. I installed 9 more sub-sites (client2 - client9) under Client 1, using drush.
4. I used Drush to enable the openid\_connect and openid\_connect\_sso for all sub-sites.
5. I added all 11 of the sites to my Apache config (I am using MAMP Pro on Mac) and tested them.
6. I had some config to do on on the auth site relating to each client site and to each sub-site for the SSO.

I am using https://drupalcommerce.org/blog/32567/using-openid-connect-single-sign-drupal as my general guide for setup and configuration of the modules as well as https://www.youtube.com/watch?v=3K-2IfC8lpg but the multi-site part I figured out myself.
> 0 votes

---
Tags: authentication-authorization
---


title: How do I modify the CSS in webform?

text:
# Question
Title: How do I modify the CSS in webform?
I made a booking form using Webform. How do I modify the CSS? Where do I find the CSS file of the webform?

The CSS files in Drupal look nothing like in Vanilla CSS. I'm bit lost there. I would just like to reduce the width of my rows or change how the date-picker looks like. Or to display my rows in two columns.

I don't want to touch the PHP files too much either, hence why I found the answers about this topic on this forum not satisfying.

# Answer
You'll find the .css files in your theme directory, usually `sites/all/themes/THEME_NAME/css`.

To see easily in which line of which css file is the rule you'd like to change, you can go to `admin/config/development/performance` and un-tick *Aggregate and compress css files* checkbox.

Then with Firebug or similar development tool you'll be able to explore the css.

Check also if there's a *sass* or *less* folder in the same directory. In that case, you would have to edit the relevant *scss/less* files instead of the css ones, and make sure your editor is well configured to compile them to css.

You can explore scss files with the help of FireCompass addd-on and less ones with FireLESS.

## EDIT

As underlined by Beebee comment, if the css you'd like to override are into a module css file, such as webform's css, don't edit that file, but override it in your own theme's css file.
> 2 votes

---
Tags: theming
---


# Question
Title: How to remove all the divs inside the $widget of a views exposed filter?
I need to remove all the divs inside the $widget of a views exposed filter. I need only the single form fields without any html around it.

I don't know PHP.

Any suggestions?

# Answer
> 1 votes
Go to the modules directory and look for the 'views' module.

There is a 'theme' folder within this.

In the theme folder, copy the 'views-exposed-form.tpl.php' file to your theme.

You can then edit the template as you require.

Note, when you copy a file like this you will want to clear caches for this to work.

\*****UPDATE\*****

To edit specific components of the form I suggest you override the following function in your themes template.php file.

```
template_preprocess_views_exposed_form(&$vars)

```

This can also be found in the views module folder 'theme.inc'.

# Answer
> 1 votes
All you need to do is simple override your own theme page for the expose filter views/theme/views-exposed-form.tpl.php to you theme template folder e.g.

views-exposed-form--view\_name--machine\_name.tpl.php

Example: views-exposed-form--latest\_nodes--page.tpl.php

and remove which you wold like to or adding your own.

# Answer
> -2 votes
You can also do easy css tricks :

```
.class-of-elements-you-want-to-hide {
   display: none;
}

```

---
Tags: 7, theming, views
---


# Question
Title: Print an object value from a twig template?
The below object, named 'profile' is available to me in a twig template. I can dump the variables with `{{ dump(profile) }}`. How do I print the 'created' timestamp? I've tried every variation of code I can think of.

# Answer
> 1 votes
You can get the created value from the entity `profile`:

```
{{ profile.created.value }}

```

or formatted:

```
   {{ profile.created.value|format_date('long') }}

```

---
Tags: theming, 8
---


# Question
Title: How to add collapsible help text to a form?
I would like to add some collapsible text underneath my comment forms. Preferably, users can click a small icon, which reveals the help text. After reading https://stackoverflow.com/a/8405715/2625920, I already added a paragraph at the desired position:

```
function MYTHEME_form_comment_form_alter(&$form, &$form_state) {
  $form['markup'] = array(
    '#markup' => t('<p>Here is some very useful text.</p>'),
    '#weight' => -1,
  );
}

```

(Actually, it surprised me that this works, since `#markup` is not ticked for forms in the Form API Reference...) Unfortunately, simply adding

```
'#collapsible' => TRUE,
'#collapsed' => TRUE,

```

to the array does not work (which is expected according to the Form API Reference). Any suggestions?

# Answer
> 1 votes
What about putting it into a fieldset ?

```
$form['fieldset'] = array(
 '#title' => 'title',
 '#type' => 'fieldset',
 '#collapsible' => TRUE,
 '#description' => 'desc',
);

$form['fieldset']['some_text'] = array(
  '#markup' => '<p>Here is some very useful text.</p>',
  '#weight' => -1,
);

```

---
Tags: 7, forms
---


# Question
Title: Pods created after the first try to load the private files using the same path as the first one
I'm currently working on deploying Drupal8 on Openshift to achieve horizontal scaling, but I hit a problem.

On a single pod (ie: "server" running drupal"), everything seems to be ok so far. But when I'm deploying a new pod, it tries to load the private files (/sites/default/files) using the same path as the first pod.

I guess it's because something is cached in the DB since "Clearing all cache" fixes it.

Is there something in the configs I can do to prevent this behaviour ? And do you think of something I should be warned about when trying to achieve horizontal scaling ?

# Answer
> 0 votes
Posting my comment as an answer.

sites/default/files needs to be on a shared file system so that Drupal can work correctly. This contains uploaded and generated files (e.g. CSS/JS).

If you do this, you probably want to move twig to a local temporary folder, see Can I change the location of the cached Twig templates?. Note that you then need to take care of emptying that folder on all servers when you do a deployment (Unless you do something really special, this cache only needs to be updated when you change your template files).

---
Tags: 8
---


# Question
Title: How to make a rule select all users of a role?
I have a certain content type in which I have a user entity reference select list that is invisible to users/editors.

The idea is that the creator of the request has to choose a role of employees to who he sends this node, and then the other users can either accept or reject it, and only if ALL employees reject, the node would actually go to a rejected state, unlike the usual way of working with workbench.

To do this, I have the invisible user-entity reference field. Now I want to achieve the following:

1. When creating the node, after save, I want the reference field to automatically select all the users of the chosen role
2. By clicking a button 'reject', I want to remove the current user from the selected list.
3. When no users are selected, the node gets rejected.

Option 2 & 3 are easily done with rules. However, phase 1 is where I'm struggling. So I have the complete list of users, but now I have to "select" them, which I can do with rules by using "add to list". However, the selector only gives me the options "entities" and "site", in which site only includes "current-user", "current-page" and "feed-node".

How can I make it select all users of a certain roles?

# Answer
> 1 votes
It appears to me that there is a straight forward solution to have your rule process *all those users of a certain role* (as in your question): you could an approach to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* load the VBO list of users that you want to be processed (= those users of a certain role).
* add a loop to perform a Rules Action, probably similar to the rule you already have in place, for each user contained in your Views results.

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

# Answer
> 0 votes
Would "Fetch entities by property" work? You could select all users of role and add them to the list.

There is another option of doing a custom action. Just query the database for users with the right role, and then add those results to the field. It's been a while since I have done that, but I believe it requires a join to get it to work properly.

---
Tags: rules, entities, users, workbench
---


# Question
Title: How to remove all nodes authored by users when their role changes?
I have two roles on my site: Standard and Premium. Standard users are able to upgrade to Premium accounts. When this happens, I would like to deleted all content that the Standard users has authored.

Can this be achieved with Rules? Or, is there a different way?

# Answer
You could use the Rules API to define a custom action that gets triggered whenever your users upgrade their accounts. In your custom action you could have a SQL query that searches all that users' content and deletes it.

For how to invoke a Rule programatically see this other DA answer: programmatically-execute-an-action-set-rules-module
> 0 votes

# Answer
Yes this can be done with the Rules module. Here is a summary of what you'll need to get it to work:

1. Keep track of all node IDs of a user that still need to be deleted later on (after the user upgrades). For this add an entity reference to the user's profile (multiple values allowed). And each time such a node get's authored (as in your question), you need to add the reference to that node as an extra value in this entity reference field (= **Rule 1**). So basically this is the "queue" of nodes for a user that need "post processing" after the user upgrades. It is will serve as your entry point starting from the user's id to "access (find) the exact node ids again later on".
2. Create a rules component (= **Rule 2**, though of type "component") with parameter just a "node id". All this Rules component has to do, is to "delete" the node indicated in the parameter. But you can add any Rules "Conditions" also if you'd need any (already now or later on if requirements change).
3. Create a rule (= **Rule 3**) containing a *Loop* that should be triggered after the user upgrades. The goal of this rule is to loop over each of the nodes in the reference field from Step 1, and in each iteration of that loop you use an action which is to invoke the Rule Component as detailed in Step 2 (and which uses the node id as a parameter).

# Video tutorials

If you're not familiar (enough/yet) with using *Loops* in rules, then watch the video about List and loops.

For a video that is fairly similar to what's needed in step 2 and step 3, refer to the 2nd video (= Solution video) about Creating multiple back links. Some more details about how your scenario slightly differs from what is shown in that solution video:

* You are creating an entity reference **to** nodes also, but **from** a user (not a node).
* You only need the first parameter (= *Node to link to*) in your Rules component (you don't need the 2nd parameter).

***Easy, no?*** ... and no custom code involved.
> 0 votes

---
Tags: rules, users
---