# Question
Title: Permissions/access caching per node and per user
UPDATE: Narrowing this a bit. I need to, for either (a) all nodes of a given type or (b) all nodes on a specified list of node id's or (c) all users on a list of iser id's, clear the cached permissions because, due to changes not necessarily made on a given node, a user's access permission may have changed.

I have built and published a module (Access by Reference) that grants update access to nodes based on edit permissions on nodes referenced in the target node.

I am concerned that the module will not work as intended if permissions cache interferes with recognizing changes made elsewhere (eg, rights to the referenced node are changed)

What I would like to do is clear permissions caches relating to particular nodes and/or particular users or roles. I've been studying the Cache Contexts for several days but the light bulb has not yet lit. I'd appreciate some guidance.

# Answer
> 2 votes
Access results can store cache metadata like cache tags and cache contexts. As a shortcut `AccessResult` has two specific methods to apply the correct cache metadata. Different membership in roles or a modified role results in a different set of permissions, use `cachePerPermissions()` to add a cache context for the hashed permissions. The second method is for the cache context of the current user `cachePerUser()`.

If you get field data from a node or user, add `addCacheableDependency($node)` or `addCacheableDependency($user)`.

See this example from the node module:

*core/modules/node/node.module, line 938*

```
function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node
    ->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account
        ->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()
          ->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account
          ->hasPermission('edit own ' . $type . ' content', $account) && $account
          ->id() == $node
          ->getOwnerId())
          ->cachePerPermissions()
          ->cachePerUser()
          ->addCacheableDependency($node);
      }

```

---
Tags: 8, users, caching
---


# Question
Title: How to get my Back To Site button to point to the correct location?
I recently logged out of my Drupal 8 site to see the pages not obscured by the admin menu.

I then logged back in (/user/login) and, to my surprise, it sent me to /user/1.

When I tried to click the "Go To Site" link - it sends me BACK to /user/1.

I did nothing out of the ordinary except log out.

How do I get my `Back To Site` button to point to the correct location (`mydomain.com/`) again?

# Answer
You're just stating facts, that is how Drupal works. If you log in, you go to your profile site by default. That might not make sense for most sites, but that's what it does by default, there modules that allow you to change it.

And "Back to Site" takes you back you the last non-admin page you were on. If you are on the homepage, it will point you back to that. Again, that's a feature, not a bug
> 4 votes

# Answer
This is very confusing, even for people that knows Drupal. The problem is with usability. You wouldn't expect that the same button will take you to different places. Sometimes it take you to the home, some times to your user profile.

To avoid frustrations, I'm removing it from my projects using the following code on a custom module:

```
/**
 * Implements hook_toolbar_alter().
 */
function mymodulename_toolbar_alter(&$items) {
  // Remove the "Back to site" button from toolbar because it has a confusing logic.
  unset($items['home']);
}

```
> 0 votes

---
Tags: 8, users
---


# Question
Title: Change field requirements on validation?
I am new to Drupal so forgive my newb question.

I am trying to remove the required true from a form field if a user clicks on a certain button so i tried to do it via form validaiton:

```
$form['#validate'][] = 'my_from_after_build'; //Calls function

function canvas_from_after_build($form, &$form_state) {
  echo "this is the form after building";
  $form['field_title_tag_list_article']['widget'][0]['#required'] = FALSE;
  return $form;
}

```

but it still gives a "this field is required" error.

# Answer
The validation function in the Form API is meant to evaluate the user input and report the errors back to the user if any.

You could change your logic in this way to facilitate your implementation: \- The field \_field\_title\_tag\_list\_article\_ is not required by default \- In the validation function, you would check whether the value of a second field (i.e. \_field\_validate\_titles\_) is set to a given value (i.e. \_field\_validate\_titles\_ == 'needs validation').

It would look something like this:

```
if ($form_state['values']['field_validate_titles'] == 'needs validation' &&
  empty($form_state['values']['field_title_tag_list_article'])) {
  form_set_error('field_title_tag_list_article', t('The title tags are required.'));
}

```

You could download the *Drupal Examples* modules and install the \_form\_example\_ module, then check the example number 6.

**Advice for new users**

In general, I suggest you browse the examples so that you are familiar with this handy reference.

Quite often, you will find that someone else had the same problem before. Sometimes, there is a community contributed module that solves your problem.

In your particular case, the *conditional fields* module could help you accomplish your goal without having to write a single line of code:
> 0 votes

---
Tags: forms
---


# Question
Title: LimeSurvey RemoteControl JSON_RPC API from Drupal
Has anyone used LimeSurvey's RemoteControl JSON\_RPC API PHP script from Drupal to connect to LimeSurvey in a different server?

I have tried the PHP Example in https://manual.limesurvey.org/RemoteControl\_2\_API#Example\_and\_helper in my local instance to export a survey responses and it works perfectly fine.

I have now copied the script to my Drupal folder (installed library jsonrpcphp through composer) in a Test server and trying to connect to Limesurvey in a different Test server; and I am unable to get the connection right.

I have updated the filename, base URLs, username and passwords for the Test instances. Not sure If it is something to do with "https" in the URL? URL for Local instance was "http". Because the script breaks at get\_session\_key line.

Any help with this will be appreciated! Please drop a comment if more info is required.

# Answer
> 0 votes
SSL certificate in the Lime Survey test server was expired. Renewed the SSL cert.

---
Tags: 7
---


title: Programmatically render a view as HTML

text:
# Question
Title: Programmatically render a view as HTML
I am using a custom function. In a button click i want to display view page. Here i want to render my view programatically in html format. How can i do that?

This is my jquery code:

```
$('.view-all-content').click(function () {

  $.post("/callajax", {
    'action': 'get_data_from_view',

  }, function (data) {

    console.log(data)

    // if (data == "gg") {
    //    console.log("suc")
    // }

    $(".view-all-content-result").html(data);

  });

});

```

In my function.php

```
function get_data_from_view() {

  $view = \Drupal::service('renderer')->render(views_embed_view('article_list', 'page_5'));

  // Other code ...

  echo $view;
}

```

# Answer
> 3 votes
Try this

```
\Drupal::service('renderer')->render(views_embed_view('VIEWSID', 'DISPLAYID'));

```

# Answer
> 2 votes
You try install module Twig Tweak render block view twig

```
{{ drupal_view('who_s_new', 'block_1') }}

```

render block set arguments

```
{{ drupal_view('products_by_category', 'block_1', tid) }}

```

You can see it https://www.drupal.org/docs/8/modules/twig-tweak/twig-tweak-and-views

---
Tags: views, 8
---


title: Forum should just show up in groups

text:
# Question
Title: Forum should just show up in groups
I would like to have, on my Drupal 8 site, a forum that can be visited only by the members of the group XY; all the other users should not see the forum.

In the permissions I can't find one for viewing the content of the forum. How can I do that?

# Answer
I solved the problem with the module Forum Access.

> This module changes your forum administration page to allow you to set forums private. You can control what user roles can view, edit, delete, and post to each forum. You can also give each forum a list of users who have administrative access on that forum (AKA moderators).
> 1 votes

---
Tags: organic-groups
---


# Question
Title: Why are my search results not showing when I input any body text?
Why my search result not showing when I input any body text ?

Are search results based on node title only?

I am creating a multilingual site with French and English languages.

Users should be able to search results by entering any text of a node whether its body text, taxonomy, subtitle and so on.

# Answer
Core search indexes titles and body content but in order to actually be able to search the nodes have to be indexed.

Search indexes nodes on batches and each batch starts on a cron run. You can run cron manually by going to your `/admin/reports/status` but ideally you want to setup a cronjob to do this for you automatically.

Search admin page (`admin/config/search/pages`) reports on what percentage of the nodes have been indexed.

Only after the search admin page says you have 100% of the nodes indexed you can be sure that what you search can be found.
> 2 votes

---
Tags: 8, search
---


# Question
Title: How can I avoid wrapping my block into <div> tags?
I have created a custom block

```
/**
 * @Block(
 *   id = "block_text",
 *   admin_label = @Translation("Text"),
 *   category = @Translation("Text"),
 * )
 */

```

And here is a `build()` function

```
/**
 * {@inheritdoc}
 */
public function build() {

  return [
    '#type' => 'markup',
    '#markup' => $render,
    '#cache' => [
      'max-age' => 0
    ],
  ];

}

```

On the page my block is wrapped into

```
<div id="block_text"> </div> tags

```

Could you please tell me, how can I avoid this wrapping?

# Answer
I think you should copy `block.html.twig` (perhaps from /core/themes/classy/block/block.html.twig) in your custom module/theme and make it work for your specific block by naming it `block--BLOCKID.html.twig` and remove the outer `<div>` from this twig file.

Alternativelly you can create a custom template
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Where is the the full tokens list for a site?
In the Metatag module UI it uses tokens but only shows a small list of tokens that are relative to the site information rather than the full content tokens which it can use, in D7 there was an admin token page so you can check values.

Where is this in Drupal 8?

# Answer
I see its one of those things that you once you know.

Enable modules:

Navigate to the page: `/admin/help/token`.
> 16 votes

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


# Question
Title: Deployment strategy for servers on internal network
I am following composer based workflow for Drupal 8, in which I commit only custom code and use `composer install` to install it on another environment.

However, on new workflow, the dev, test, staging instances are on Internal network, with no access to Internet (due to security reasons).

Can you suggest a deployment strategy to use in this scenario, so that I don't have to commit the whole files in git repository, as is.

**PS:** I am ok with something like Acquia pipelines, where things are 'compiled' into a branch, which is used for deployment. But using that is ruled out, as the code can't be sent to outside because of security concerns.

# Answer
The correct way is to use Acquia BLT. It generates a deployment artifact, which can be deployed anywhere.

So that the composer will stay in local and the deployment artifact can be committed to a different branch for deployment, with all the dependencies.
> 1 votes

---
Tags: 8, composer, deployment
---


# Question
Title: How to add a new webform submission formatter for the webform components
I'm just wondering how to add a new option to the webform submission formatters for a specific element? is it driven by the field API?

# Answer
What you have in that list are date formats. You can manage those, including adding new ones, at /admin/config/regional/date-time.
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Create new child field collection programmatically
I have 2 field collections (Parent and child)

* Parent Field collection: Test Student Info
machine name: field\_test\_student\_info
* Child Field collection: Marks
machine name: field\_marks

In parent field collection have 1 field:

* Field1: Student Name
machine name: field\_student\_name

In child field collection have 2 fields:

* Field1: English Marks
machine name: field\_eng\_marks
* Field2: History Marks
Machine name: field\_history\_marks

I have set field setting "unlimited" to child field collection (Marks). I just want to add new child field collection item programmatically. I have tried below code but it's showing me error:

```
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\field_collection\Entity\FieldCollectionItem;

function CreateChildFC() {
  $node = \Drupal\node\Entity\Node::load(770);
  $load = FieldCollectionItem::load(207); // Loading child FC from parent FC i.e Marks
  $field_collection_items = $load->field_marks;
  $field_collection_item = FieldCollectionItem::create(
   [
    'field_name' => 'field_marks',
   ]
   );
  $field_collection_item->setHostEntity($node);
  $field_collection_item->set('field_eng_marks', '89');
  $field_collection_item->set('field_history_marks', '75');
  $load->field_marks[] = ['field_collection_item' =>   $field_collection_item];
  $node->save();
}

```

**Error**
The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to \_field\_collection\_field\_item\_list\_full() must implement interface Drupal\Core\Field\FieldItemListInterface, null given, called in /site/modules/contrib/field\_collection/src/Entity/FieldCollectionItem.php on line 333 in \_field\_collection\_field\_item\_list\_full() (line 151 of modules/contrib/field\_collection/field\_collection.module).

# Answer
> 2 votes
You try the code:

```
<?php
use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;

[.....]

  $node = Node::load(7);
  $field_collection_item = FieldCollectionItem::create(
    [
      'field_name' => 'field_test_student_info',
    ]
  );

  $field_collection_item->set('field_student_name', 'Student Name');

  $field_mark_collection = FieldCollectionItem::create(['field_name' => 'field_marks']);
  $field_mark_collection->set('field_english_marks', '1231');
  $field_mark_collection->set('field_history_marks', '123');
  $field_collection_item->field_marks[] = ['field_collection_item' => $field_mark_collection];
  $node->field_test_student_info = ['field_collection_item' => $field_collection_item];
  $field_collection_item->setHostEntity($node);
  $node->save();

```

You need create new collection field `FieldCollectionItem::create(['field_name' => 'field_marks'])`

You can set value to the file child in field parent collection, it is same you when set value field collection in node, here you dont's need set `setHostEntity`, it will understand is the `field_collection_item`

As the code above I also checked it, and it worked.

You can refer to it here

Goodluck

---
Tags: 8, entities
---


# Question
Title: How can I change a file field description?
How can I change the file field description without altering a module file?

The function I would like to modify is `theme_file_upload_help()`.

# Answer
I have accomplished similar by using a hook\_form\_alter() in a custom module and altering the field's `#description` property.
> 0 votes

# Answer
If it's a theme function you want to override, then the way to do that is to write a function called `mytheme_file_upload_help` (if your theme is called `mytheme`).

so in your `mytheme/template.php` file:

```
function mytheme_file_upload_help($variables) {
   ... your code here
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Features installed with profile are overridden
We are using workbench with the subpermissions module. We have created two features which set custom permissions for workbench and for subpermissions. If we install the workbench feature and then the subpermissions feature, both features show as Default and not overwritten. If we install these two features last with a profile, both features show as overridden and the permissions are not correctly set. Any idea why this is happening and how would we investigate?

thanks

# Answer
Apparently things in a profile info file are loaded before things in a profile install file. I moved the two features from the info file into the install file and put them last. After a new site install, the features were not overridden and worked as expected.
> 0 votes

---
Tags: 7, users, workbench
---


title: Open inline link in modal/colorbox

text:
# Question
Title: Open inline link in modal/colorbox
I have the colorbox module installed so I assume there's a way to do this with it, but I've had no success. Pretty much what I'd like to do within the WYSIWYG editor is have a link to an external website open up in a colorbox modal. I have forms hosted on a third party website, so instead of having users leave my site, I'd like the ability to have them just see that external form in the colorbox.

How do I achieve such a thing? I've tried adding the `colorbox-node` class to no success and also tried creating my own class and then in a custom js file have the following code:

```
 (function($){
    $(".custom-class").colorbox({iframe:true, width:"80%", height:"80%"});
 }(jQuery));

```

The above code fails when I inspect it with the following error: `TypeError: $(...).colorbox is not a function`.

I'm also using a bootstrap sub-theme but I don't think the modal component would be of any use, would it?

# Answer
You just need to make sure the library is added to the request.

For example, to include the library on every page:

```
function THEME_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'colorbox/colorbox';
}

```
> 1 votes

---
Tags: 8, wysiwyg
---


title: Adding a class to a region

text:
# Question
Title: Adding a class to a region
I am working on my theme in Drupal 8 and I want to add a class to my header div. I tried adding this to the region.vars.php file.

```
if ($region === 'header') {
  $variables[header]['class'][] = 'navbar-right';
}

```

It's not working, though. This is the complete region.vars.php file.

```
<?php
/**
 * @file
 * region.vars.php
 */

use Drupal\Core\Template\Attribute;

/**
 * Implements hook_preprocess_region().
 */
function bootstrap_preprocess_region(&$variables) {
  $region = $variables['elements']['#region'];
  $variables['region'] = $region;
  $variables['content'] = $variables['elements']['#children'];

  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Content region.
  if ($region === 'content') {
    // @todo is this actually used properly?
    $variables['theme_hook_suggestions'][] = 'region__no_wrapper';
  }
  // Help region.
  elseif ($region === 'help' && !empty($variables['content'])) {
    $content = $variables['content'];
    $variables['content'] = array(
      'icon' => array(
        '#markup' => _bootstrap_icon('question-sign'),
      ),
      'content' => array(
        '#markup' => $content,
      ),
    );
    $variables['attributes']['class'][] = 'alert';
    $variables['attributes']['class'][] = 'alert-info';
    $variables['attributes']['class'][] = 'messages';
    $variables['attributes']['class'][] = 'info';
  }

  // Support for "well" classes in regions.
  static $wells;
  if (!isset($wells)) {
    foreach (system_region_list($theme) as $name => $title) {
      $wells[$name] = bootstrap_setting('region_well-' . $name);
    }
  }
  if (!empty($wells[$region])) {
    $variables['attributes']['class'][] = $wells[$region];
  }

   if ($region === 'header') {
    $variables[header]['class'][] = 'navbar-right';
  }

}

```

I got most of this code from the Drupal 8 bootstrap theme. Everything else is working.

# Answer
What I normally do for all my themes is to add the missing `region region-name` class to each region by implementing `hook_preproccess_HOOK()` in `MYTHEME.theme`.

```
/**
 * Implements template_preprocess_region().
 */
function MYTHEME_preprocess_region(&$variables) {
  // Add missing region CSS classes.
  $variables['attributes']['class'][] = 'region';

  if (isset($variables['region']) && !empty($variables['region'])) {
    $variables['attributes']['class'][] = 'region-' . str_replace('_', '-', $variables['region']);
  }
}

```
> 3 votes

# Answer
Using `$variables['attributes']['class'][] = 'navbar-right';` adds the class to the div wrapping the region. I added it in the .theme file (former template.php in D7).
> 0 votes

# Answer
In Drupal 8, there is a .theme file inside your themes/\[theme-name\] directory. You can write your preprocess there, where you can check for the content type of the node and other fields.

For your case, you can pass the content type in a variable as in the following code.

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

if (isset($node)) {
  $entity = entity_load('node', $node->nid->value);
  if ($entity) {
    $type = $entity->get('type')->getValue();
    $variables['content_type'] = $type;
  }
}

```

This variable will be available for you in your *page.html.twig* file (the page template).

Already there is `page.header`, which indicates the header of the page. You can insert the `<div>` markup around `page.header`.

```
{%if content_type == 'articles' %}
  <div class='extra-header-class'>{{ page.header }}</div>
{% else %}
  {{ page.header }}
{% endif %}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Drush 7 @self picks configuration from aliases.drushrc.php randomly
I'm trying to index Search API Solr using Drush 7 on platform environments, but the `drush search-api-index` command is failing for a very strange reason.

There are clues of the problem below, but I'm not sure what to do next to figure this out. This issue has me very stumped.

## 1. I've configured platform.sh-specific drushrc.php file, which sets up the --uri option correctly.

```
web@server:~/www$ drush st
 Drupal version                  :  7.59
 Site URI                        :  https://mysite.us-2.platformsh.site/
 Database driver                 :  mysql
 Database hostname               :  database.internal
 Database port                   :  3306
 Database username               :  user
 Database name                   :  main
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  mysite_theme
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php5/cli/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /app/.global/vendor/drush/drush/drush.php
 Drush version                   :  7.4.0
 Drush temp directory            :  /tmp
 Drush configuration             :  /app/www/sites/all/drush/drushrc.php
 Drush alias files               :  /app/www/sites/all/drush/aliases.drushrc.php
 Install profile                 :  mysite
 Drupal root                     :  /app/www
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  /app/private
 Temporary file directory path   :  /app/tmp

```

## 2. Drush DOES list the search api indexes correctly.

```
web@server:~/www$ drush search-api-list
 Id  Name                 Index                Server                     Type          Status    Limit
 1   Default node index   default_node_index   (none)                     Content       disabled  50
 34  Location Search      location_search      Solr Server (Platform.sh)  Content       enabled   50
 35  Page manager pages   page_manager_pages   Solr Server (Platform.sh)  Page manager  enabled   50
 36  Site General Search  site_general_search  Solr Server (Platform.sh)  Content       enabled   50
 37  Bookplates           bookplates           Solr Server (Platform.sh)  Content       enabled   50
 38  Staff Directory      staff_directory      Solr Server (Platform.sh)  Content       disabled  50

web@server:~/www$ drush search-api-status
 Id  Index                % Complete  Indexed  Total
 1   Default node index   -           0        0
 34  Location Search      0%          0        2187
 35  Page manager pages   0%          0        13
 36  Site General Search  0%          0        2187
 37  Bookplates           0%          0        2199
 38  Staff Directory      -           0        0

```

## 3. HOWEVER, trying to reindex with drush fails

```
web@server:~/www$ drush search-api-index
The index Default node index is up to date.                                                                                [ok]
Indexing a maximum number of 2187 items (50 items per batch run) for the index Location Search.                                                    [ok]
Command batch-process needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this  [error]
command.
The drush command 'batch-process 19730' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working
database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

```

## 4. A clue as to what is wrong is then given, with the WRONG db creds and site uri!

```
Drush was attempting to connect to:
 Drupal version         :  7.59
 Site URI               :  mysite.local
 Database driver        :  mysql
 Database hostname      :  mysite.local
 Database port          :  3306
 Database username      :  mysite
 Database name          :  mysite
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /app/.global/vendor/drush/drush/drush.php
 Drush version          :  7.4.0
 Drush temp directory   :  /tmp
 Drush configuration    :  /app/www/sites/all/drush/drushrc.php
 Drush alias files      :  /app/www/sites/all/drush/aliases.drushrc.php
 Drupal root            :  /app/www
 Site path              :  sites/default

```

## 5. How are the wrong parameters being passed?

It's almost as if it is passing the wrong parameters or a default drush alias to the index task from somewhere, but where? I've scanned the code for "mysite.local":

```
web@server:~/www$ grep -r mysite.local .
./sites/all/drush/aliases.drushrc.php:$aliases['mysite.local'] = array(
./sites/all/drush/aliases.drushrc.php:  'uri' => 'mysite.local',
./sites/all/drush/drushrc.php.example:$options['uri'] = 'http://mysite.local';
./sites/all/modules/custom/powell_res/powell_res.module:    if ( $_SERVER['HTTP_HOST']=='localhost' || $_SERVER['HTTP_HOST']=='mysite.local') {
./sites/all/modules/custom/rc_res/rc_res.module:    if ( $_SERVER['HTTP_HOST']=='localhost' || $_SERVER['HTTP_HOST']=='mysite.local') {
./sites/default/local.settings.php:      'host' => 'mysite.local',
./sites/default/settings.php:  'mysite.local' => 'local.settings.php',

```

I would think that the only relevant locations from above are ./sites/all/drush/aliases.drushrc.php, ./sites/all/drush/drushrc.php.example, and ./sites/default/local.settings.php. Neither of the later two should be included at runtime from drush cli. The contents of my ./sites/default/settings.php only include local.settings.php if `uri = mysite.local`. This leaves only aliases.drushrc.php. **Could a default alias of `@mysite.local` somehow be passed under the covers?**

FWIW, I also looked for possible hard-coded drush command-specific config options to the search-api-index command placed in another file but couldnt turn up anything useful. There is a ./sites/all/drush/drushrc\_shared.php file but this file doesn't appear to be loaded, nor does it contain any relevant command-specific settings or even a --uri option.

## 6. Debugging with `-vvv --debug`

From the output below, The first half of the command runs fine, but then at some point after it finds the drush command file for search\_api\_index, it internally runs another drush command via "Backend invoke", with the wrong settings.

```
    web@server:~/www$ drush search-api-index -vvv --debug
    Drush preflight prepare loaded autoloader at                         [preflight]
    /app/.global/vendor/autoload.php [0 sec, 2.6 MB]
    Starting Drush preflight. [0 sec, 2.6 MB]                                                                                [preflight]
    Cache HIT cid: 7.4.0-commandfiles-0-2cc326a65c41fdab5fcf2c6cb9fb2c3b [0.01 sec, 2.66 MB]                                                               [debug]
    Loading drushrc "/app/www/sites/all/drush/drushrc.php" into "drupal" scope. [0.03 sec, 4.66 MB]                                                    [bootstrap]
    Bootstrap to phase 0. [0.08 sec, 6.65 MB]                                                                                [bootstrap]
    Bootstrap to phase 5. [0.08 sec, 6.65 MB]                                                                                [bootstrap]
    Drush bootstrap phase : bootstrap_drupal_root() [0.09 sec, 7.03 MB]                                                                                [bootstrap]
    Loading drushrc "/app/www/sites/all/drush/drushrc.php" into "drupal" scope. [0.09 sec, 7.03 MB]                                                    [bootstrap]
    Initialized Drupal 7.59 root directory at /app/www [0.09 sec, 7.03 MB]                                                                             [bootstrap]
    Find command files for phase 1 (max=5) [0.09 sec, 5.06 MB]                                                                                [debug]
    Cache HIT cid: 7.4.0-commandfiles-1-05d40856b788e54ca64b35c99a2c1fd7 [0.09 sec, 5.06 MB]                                                               [debug]
    Drush bootstrap phase : bootstrap_drupal_site() [0.09 sec, 5.07 MB]                                                                                [bootstrap]
    Initialized Drupal site mysite.us-2.platformsh.site at sites/default [0.09 sec, 5.07 MB]                     [bootstrap]
    Find command files for phase 2 (max=5) [0.09 sec, 5.07 MB]                                                                                [debug]
    Cache HIT cid: 7.4.0-commandfiles-2-f17fc6bdab2f74278df75194ca483893 [0.09 sec, 5.07 MB]                                                               [debug]
    Drush bootstrap phase : bootstrap_drupal_configuration() [0.1 sec, 5.3 MB]                                                                         [bootstrap]
    Find command files for phase 3 (max=5) [0.1 sec, 5.34 MB]                                                                                [debug]
    sql-query: SELECT 1; [0.1 sec, 5.45 MB]                                                                                [notice]
    Executing: mysql --defaults-extra-file=/tmp/drush_8YlZWK --database=main --host=database.internal --port=3306 --silent  < /tmp/drush_WhdxK8
      1
    sql-query: SHOW TABLES; [0.11 sec, 5.45 MB]                                                                                [notice]
    Executing: mysql --defaults-extra-file=/tmp/drush_I34QoZ --database=main --host=database.internal --port=3306 --silent  < /tmp/drush_INSUan
      [output redacted for brevity]
    Drush bootstrap phase : bootstrap_drupal_database() [0.14 sec, 5.54 MB]                                                                            [bootstrap]
    Successfully connected to the Drupal database. [0.15 sec, 6.07 MB]                                                                                [bootstrap]
    Find command files for phase 4 (max=5) [0.15 sec, 6.07 MB]                                                                                [debug]
    Drush bootstrap phase : bootstrap_drupal_full() [0.15 sec, 6.07 MB]                                                                                [bootstrap]
    Cache HIT cid: 7.4.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.45 sec, 40 MB]                                                                [debug]
    Find command files for phase 5 (max=5) [0.45 sec, 40 MB]                                                                                [debug]
    Cache HIT cid: 7.4.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.45 sec, 40.01 MB]                                                             [debug]
    Cache HIT cid: 7.4.0-commandfiles-5-30eb6a40e5b156e214df63a4a8fcfecc [0.45 sec, 40.06 MB]                                                              [debug]
    Bootstrap to phase 6. [0.51 sec, 44.05 MB]                                                                                [bootstrap]
    Drush bootstrap phase : bootstrap_drupal_login() [0.51 sec, 44.06 MB]                                                                              [bootstrap]
    Find command files for phase 6 (max=6) [0.54 sec, 41.45 MB]                                                                                [debug]
    Found command: search-api-index (commandfile=search_api) [0.54 sec, 41.45 MB]                                                                      [bootstrap]
    Calling hook drush_search_api_index [0.59 sec, 44.46 MB]                                                                                [debug]
    The index Default node index is up to date. [0.61 sec, 45.96 MB]                                                                                [ok]
    Indexing a maximum number of 2187 items (50 items per batch run) for the index Location Search. [0.61 sec, 45.96 MB]                               [ok]
    Cache HIT cid: 7.4.0-alias-path--0e94eb35635a057777b446898cdd620b [0.62 sec, 46.11 MB]                                                                 [debug]
    Backend invoke: /usr/bin/php /app/.global/vendor/drush/drush/drush.php --php=/usr/bin/php  --backend=2 --user=0 --verbose --debug --root=/app/www    [command]
    --uri=mysite.local  batch-process 19738 2>&1 [0.62 sec, 46.13 MB]
    /usr/bin/php /app/.global/vendor/drush/drush/drush.php --php=/usr/bin/php  --backend=2 --user=0 --verbose --debug --root=/app/www                     [notice]
    --uri=mysite.local  batch-process 19738 2>&1 [0.62 sec, 46.13 MB]

```

## 7. I've found a related issue #1550575, but it claims to have been fixed for 6 years.

## 8. Drush @self alias is being weird.

If I run `drush st` the output is correct (see #1 above). If I run `drush @self st` I get the WRONG db creds and site uri values:

```
web@server:~/www$ drush @self st
 Drupal version         :  7.59
 Site URI               :  mysite.local
 Database driver        :  mysql
 Database hostname      :  mysite.local
 Database port          :  3306
 Database username      :  mysite
 Database name          :  mysite
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /app/.global/vendor/drush/drush/drush.php
 Drush version          :  7.4.0
 Drush temp directory   :  /tmp
 Drush configuration    :  /app/www/sites/all/drush/drushrc.php
 Drush alias files      :  /app/www/sites/all/drush/aliases.drushrc.php
 Drupal root            :  /app/www
 Site path              :  sites/default

```

## 9 drush sa @self randomly picks the wrong alias from aliases.settings.php

```
web@server:~/www$ drush sa @self
$aliases["mysite.local"] = array (
  'root' => '/app/www',
  'uri' => 'mysite.local',
  'path-aliases' =>
  array (
    '%dump' => '/app/db/local-20180830051250.sql',
  ),
  'command-specific' =>
  array (
    'sql-sync' =>
    array (
      'structure-tables-key' => 'custom',
      'structure-tables' =>
      array (
        'custom' =>
        array (
          0 => 'cache',
          1 => 'cache_block',
          2 => 'cache_bootstrap',
          3 => 'cache_field',
          4 => 'cache_filter',
          5 => 'cache_form',
          6 => 'cache_image',
          7 => 'cache_libraries',
          8 => 'cache_menu',
          9 => 'cache_page',
          10 => 'cache_path',
          11 => 'cache_search_api_solr',
          12 => 'cache_token',
          13 => 'cache_views',
          14 => 'cache_views_data',
          15 => 'history',
          16 => 'sessions',
          17 => 'watchdog',
        ),
      ),
    ),
    'rsync' =>
    array (
      'mode' => 'rlptDz',
    ),
  ),
  'target-command-specific' =>
  array (
    'sql-sync' =>
    array (
      'enable' =>
      array (
        0 => 'stage_file_proxy',
      ),
    ),
  ),
);

```

I suspected drush was picking the first alias defined from the `./sites/all/drush/aliases.drushrc.php` file, but when I added another different alias and changed the order, I confirmed that it does not do this. Thus, I don't understand why it decides to pull this specific one as the `@self`.

# Answer
> 1 votes
The only valid solution after discussing with greg anderson, drush maintainer, is to upgrade to Drush 8, where this issue seems to have been fixed.

---
Tags: 7, search, drush
---


title: Next in position of nodequeue in views

text:
# Question
Title: Next in position of nodequeue in views
I got A Drupal7 setup with module view and nodequeue. Now i want a pager on the bottom of my content-type that gets me to the next node of this type in my nodequeue position.

Now i found this Get next node in nodequeue when i googled it. But this solutions wont work for me.

# Answer
> 0 votes
I have done something like that with Custom Pagers module in the past.

I was hoping I could achieve the same thing with views and contextual filters but I can't figure it out.

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


title: How to split region block render?

text:
# Question
Title: How to split region block render?
Is it possible to split the rendering of the blocks in a region ? I have see this question Drupal 8 - How to split display the blocks separately in region.html.twig attempting to solve this by using `{{ elements.search}}` and I have tried it, but no success yet.

I also tried `{{ elements.children[0] }}` but this failed as well.

Is there a possible way of getting the array element out individually.

Many thanks

# Answer
> 1 votes
You can iterate through the blocks in this way:

```
{% for block_key, block in elements if block_key|first != '#' %}
  <b>{{ block_key }}: </b>
  {{ block }}
{% endfor %}

```

If you just need to know the blocks that are present in a given region, you could use this:

```
{{ dump(elements|keys) }}

```

Then you can print each block as:

```
{{ elements.key }}

```

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


# Question
Title: Clean URL pagination (rewrite ?page=parameter)
One of my client works with an SEO agency and they ask me to remove the pagination parameter `?page=x` (generated by the Views module) and rewrite it like this:

Before:

```
/my-page?page=1

```

After:

```
/my-page-1

```

Is there a way to do it with Drupal? I don't see any option in the view or in Pathauto to do this.

Is it possible to handle this with a custom module or should I work with `.htaccess` file?

I've tried the Clean Pagination module but you have to manually set pages where clean pagination should work and the module doesn't seem to work properly.

# Answer
> 4 votes
You should write a PathProcessor that implements:

* `Drupal\Core\PathProcessor\InboundPathProcessorInterface`
* `Drupal\Core\PathProcessor\OutboundPathProcessorInterface`

Example:

file: modules/custom/mymodule/src/PathProcessor/MymodulePathProcessor.php

```
namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;

class MymodulePathProcessor implements InboundPathProcessorInterface, OutboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    if (strpos($path, '/my-page-') !== 0) {
       return $path;
    }
    $page =  preg_replace("/^\/my-page-(\d+)/", '$1', $path);
      if (ctype_digit($page)) {
        \Drupal::request()->query->set('page', $page);
        return "/my-page";
    }
    else {
      \Drupal::request()->query->set('page', 0);
      return "/my-page";
    }
    return $path;
  }

  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($path === '/my-page' && isset($options['query']['page'])) {
      $page = $options['query']['page'];
      unset($options['query']['page']);
      return '/my-page-' . $page;
    }
    return $path;
  }

}

```

file: modules/custom/mymodule/mymodule.services.yml

```
services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
    tags:
    - { name: path_processor_outbound}
    - { name: path_processor_inbound}

```

We also need to do a custom alteration to the pager. For the full pager the links are not created as the usual *link render elements*, so they don't go through the `processOutboud`, instead the twig file (classy/templates/navigation/pager.html.twig) uses a custom format. The next hook function does the adjustment.

file: modules/custom/mymodule/mymodule.module

```
/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_pager().
 *
 * @param $variables
 */
function mymodule_preprocess_pager(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/my-page')
  foreach ($variables['items']['pages'] as &$page_link) {
    $page =  preg_replace("/^\?page=(\d+)/", '$1', $page_link['href']);
    $page_link['href'] = 'my-page-' . $page;
  }
}

```

---
Tags: 8, paging
---


title: Switch user session programmatically

text:
# Question
Title: Switch user session programmatically
I'm trying to switch user session thanks to Drupal Switch. I want to do this so that when I have a certain role, I can switch to another user account to check some data from the user i choose to switch.

My routing :

```
double_vue.page_double_vue:
    path: '/double-vue'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::doubleVue'
        _title: 'Double vue'
    requirements:
        _permission: 'access content'
double_vue.switched_user:
    path: '/double-vue/{userSwitchedID}'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::switchUser'
        _title: 'UserSwitched'
    requirements:
        _permission: 'access content'

```

My view :

```
<a class="btn btn-primary btn-xs" href="{{ path('double_vue.switched_user', { 'userSwitchedID': "15" }) }}">switch</a>

```

My function :

```
  public function switchUser($userSwitchedID){
    $accountSwitcher = \Drupal::service('account_switcher');
    $account = \Drupal\user\Entity\User::load($userSwitchedID);
    return $accountSwitcher->switchTo($account);
  }

```

When I click on my to link to switch to another user, I have this error in my logs :

> The controller must return a response (Object(Drupal\Core\Session\AccountSwitcher) given)

If I remove the return, I have this :

> The controller must return a response (null given)

How can I fix that so that I can switch to another user account ?

# Answer
So first, the account switcher is for a temporary switch in the same request, to execute a specific thing as another user, it can't be used for what you want.

What Masquerade does is a lot more complicated and I don't understand why you don't just use that. Masquerade automatically adds itself to the user operations, so if you build a view that lists your users with the operations field then you will have exactly what you want to do.

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

---
Tags: 8, users, sessions
---


title: Field permission for Administrator

text:
# Question
Title: Field permission for Administrator
How to disable this fields for Administator?

# Answer
> -1 votes
It should be administrator.

```
if (in_array('administrator', $account->getRoles())) {
  return AccessResult::forbidden();
}

```

# Answer
> 0 votes
Install Disable Field module and install. After installation go-to `admin/structure/types/manage/YOUR_CONTENT_TYPE/fields` and edit the desired field. In the bottom, you can see `DISABLE FIELD SETTINGS` open that and you can choose to disable option in `DISABLE THIS FIELD ON ADD CONTENT FORM?` and `DISABLE THIS FIELD ON EDIT CONTENT FORM?`. In that Select `Disable for certain roles` and choose administrator. After that save and that field will be disabled in ADD/EDIT based on your selection

---
Tags: 8
---


# Question
Title: Reset a form element value through AjaxResponse
I have an AjaxCallback which returns `AjaxResponse()`. I need to change some form element properties like (disabled to true, remove some css class etc which works). But I'm unable to reset the particular form input element value to null.

Something like this -

```
public function calbackfunc(array &$form, FormStateInterface $form_state) : AjaxResponse {

  $response = new AjaxResponse();

  $element = $form_state->getTriggeringElement();

  $element_value = $element['#value'];

  if ($element_value === 'hit') {
    $response->addCommand(new InvokeCommand('.hit-container input', 'attr', ['disabled', FALSE]));
    $response->addCommand(new InvokeCommand('.hit-container div', 'removeClass', ['form-disabled']));
    $response->addCommand(new InvokeCommand('.hit-container input', 'removeClass', ['error']));
    //apart from these steps I also want to set the input value to null.
   }

   return $response;
 }
}

```

This question is a follow up to the earlier question I've posted Form element replaced via Ajax callback doesn't seem to be submitting or the values are not appearing in buildForm .

I tried like this -

```
$response->addCommand(new InvokeCommand('.hit-container input', 'setValue', ['myfield', '']));

```

But no luck. Any help would be great. Thanks.

# Answer
> 1 votes
You can try the code below

```
$response->addCommand(new InvokeCommand('#field_id','val',['']));

```

The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

This command is implemented by Drupal.AjaxCommands.prototype.invoke() defined in misc/ajax.js.

Please see InvokeCommand

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


# Question
Title: Adding values to referential entity using REST API POST
I have 2 custom content type. One is movies and the other is actors. I am using REST API POST to add values into movies. Actor is a referential entity within movies. How do I add values into actors which are corresponding to a particular movie when I use POST?

An option that I am currently trying out is add multiple values into actors first and that POST will return a node id, use that node id value along POST values to movies. Is this the right approach?

# Answer
You can see the article about create Custom Rest Resources for POST

You can reference below code below

```
$node_actor = Node::create(
      ['type' => 'actor',// the content type
        'title' => 'Actor Name',
      ]
    );
   $actor_id = $node_actor->save();

```

After you can use `$actor_id` had node reference to movie

```
$node_movie = Node::create(
   ['type' => 'movie',// the content type
    'title' => 'Movie Name',
   ]
  );
  $node_movie->set('field_actor_ref',['target_id'=>$actor_id])
  $node_movie->save();

```
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How do I turn a select list into a radio button?
I have a `list text` field that I want to display as a series of radio buttons instead of a select (dropdown) list. In Drupal 7, I could change this on **Manage fields**. How can I do that in Drupal 8?

# Answer
step 1 : choose the field type is "list(text)".

step 2 : change the "Allowed number of values" as *limited* in **Field settings**

step 3 : change the "field widget" as *Check boxes/radio buttons* in **Manage form display**
> 4 votes

# Answer
This option moved. It is now under **Manage form display**, which is next to **Manage fields**.

You will also need the Options module (included in core) enabled.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: How do I add a custom field token to a default value?
I want to add node-field data into the web from block via tokes as with Webform 7.x-4.1 this should work.

But tokens from custom fields are not available in a webform(block) ?

`[node:title]` and `[node:author]` work but `[node:field_mycustumfield]` or `[node:field-mycustumfield]` does not work .

Any help appreciated!

# Answer
I know this was asked years ago, but if someone comes across this, here's the solution:

https://www.drupal.org/node/919760#comment-9973163

Node tokens in a Webform block refer to the Webform node, not the current node which the block is placed on. Currently, the Token module does not expose node tokens to the Webform block.

There is a patch in this thread which exposes tokens to the Webform block, and should do just what you need. Hopefully it will get committed to the Token module soon. :-)

As an alternative, you could also use https://www.drupal.org/project/token\_custom and create a custom token that exposes the field you need.
> 0 votes

# Answer
You can use function hook\_tokens

it is provide replacement values for placeholder tokens.

Example code:

```
function MYMODULE_token_info() {
  $info['tokens']['node']['title_first_letter'] = array(
    'name' => t('Title first letter'),
    'description' => t('Generates first letter of node title')
  );
  return $info;
}

function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'title_first_letter':
          $replacements[$original] = substr($node->title, 0, 1); // get first letter of the title here
          break;
      }
    }
  }
  return $replacements;
}

```
> 0 votes

---
Tags: 7, webforms, tokens
---


# Question
Title: Use an Address Field with 3 lines for the street
I'm working on an Entity where I created a field containing Address informations (like country, city and street).

The default Address Type in Drupal 8 supports only 2 lines for the street information. Is there a way to add an extra line?

# Answer
I found a (partial solution), but new ideas are always well welcomed. I used the field organization as third row and then I rearranged the weights of the fields in this way:

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'specific_add_form' || $form_id == 'specific_edit_form' ) {
        $form['field_address']['widget'][0]['address']['#after_build'][] = 'mymodule_weight_change';
    }

}

function mymodule_weight_change($element, $form_state) {
    $element['country_code']['#weight'] = -10;
    $element['address_line1']['#weight'] = -7;
    $element['address_line2']['#weight'] = -5;
    $element['organization']['#weight'] = -2;
    $element['postal_code']['#weight'] = 5;
    $element['locality']['#weight'] = 10;

    return $element;
}

```

Endly I put the css of the organization label as `display: none`.
> 1 votes

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


title: Adding onclick attribute to menu links

text:
# Question
Title: Adding onclick attribute to menu links
I'm trying to add the onclick attribute to some menu links in Drupal 8 in order to track conversions with Google.

Here's a tutorial for adding onclick events in Drupal 7 that uses the Menu Attributes module.

For Drupal 8, I looked at the Link attributes module and the Menu Link attributes module but these only allow you to add classes, not set the value for onclick.

# Answer
Seems Menu Item Extras is the way to go now. It makes menu items fieldable. And you probably also get the proper template suggestions already.

> Menu Item Extras provides extra fields for the Menu Items without using additional entities. This module is NOT an alternative of all Mega Menu modules - it is unique implementation of Drupal core’s Menu system. All fields are placed upon the Menu Item edit/add form and use core Menu link content entity for storing all data.
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: How can I override the field in my view?
I have a view for a content type with a number of fields. For one of the fields (List, text) (node\_field\_type) I would like to override the output result. It can be either type\_1 or type\_2 . In the database the type is stored in node\_field\_type table in field\_type\_value column.

So in the settings of the field under "Rewrite results" tab I picked "Override the output of this field with custom text"

```
<span class="tag-{{ field_node_type|lower }}"></span>

```

But it doesnt assign any class to html tag.
Could you please help me?

# Answer
> 2 votes
You need to have the field `field_node_type` called somewhere in your view to use it as a token in rewrite results for a field. Value that you're trying to use in rewrite results should be available within replacement patterns for the field you're trying to configure.

---
Tags: views, 8
---


title: Method to test if site has rss view

text:
# Question
Title: Method to test if site has rss view
Our group has a multi-site drupal-D7 installation -- approximately 70 sites -- we need to identify which site have an RSS view. I've been trying to find a signature in the databases' that we could search for to identify which ones have one or more. So far we've been unsuccessful. Is there a way, perhaps a drush command?

# Answer
> 1 votes
You can run the follow SQL command on the databases of the sites:

```
SELECT * FROM `views_display` WHERE `display_plugin` = 'feed'

```

Maybe you can use a script to loop through all the databases and get those with results

---
Tags: feeds
---


# Question
Title: How can I programmatically get the theme name?
In Drupal 8, is there a way to figure out what theme you are currently using in a module? I need to get the name programmatically within the code of a module.

# Answer
Using the theme manager is the proper Drupal 8 way of getting information about your theme.

```
\Drupal::service('theme.manager')->getActiveTheme()

```

*A general rule in drupal 8 is look for the manager (/handler) service.*

\** Note: as Neograph734 pointed out, `\Drupal::service('theme.manager')->getActiveTheme()` will return the active theme object. If you want to get the theme machine-name then use `\Drupal::service('theme.manager')->getActiveTheme()->getName()`
> 34 votes

# Answer
This will do it:

```
$config = \Drupal::config('system.theme');
print $config->get('default');

```

You can always use drush to explore your available configs:

```
drush config-list

```

and

```
drush config-list system

```

gave me a list:

```
...
system.rss
system.site
system.theme.global
system.theme
...

```

and then I could check with the following:

```
drush cget system.theme.global

```

and

```
drush cget system.theme

```

to finally find out that it holds a `default` property that was what you asked for.
> 6 votes

# Answer
1. if you want to get actual active theme name `administration theme` included Use :

```

 $activeThemeName = \Drupal::service('theme.manager')->getActiveTheme();

```
1. if you want your default selected theme `theme used in front` not `admistartion theme` Use :

```

 $defaultThemeName = \Drupal::config('system.theme')->get('default');

```
> 4 votes

---
Tags: 8
---


title: How to save file with custom form?

text:
# Question
Title: How to save file with custom form?
I try to use that script in my Drupal site https://tutorialzine.com/2013/05/mini-ajax-file-upload-form

I did not use drupal form api. I used my html same with that script.

I created 2 pages with hook\_menu.

On first page I use that script to upload files. That script sends files via ajax to 2. page. But I could not save files as managed file.

On second page I save datas as json to logs to see what i get in that file. That is an example json;

```
 {"name":"aa.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpWkCoI6","error":0,"size":8575}

```

How can I save files as managed file on second page?

# Answer
> 2 votes
I solved like that

```
$file_name = $file['name'];
$file_get = file_get_contents($file['tmp_name']);
$new_file = file_save_data($file_get, 'public://images/'.$file_name);

```

---
Tags: 7, forms, files
---


# Question
Title: How to remove status messages from admin theme?
I am working with Drupal 8. I have enabled "Seven" as admin theme. When I have added an image with high resolution I am getting 2 error messages at a time(screenshot). I want to hide "green" colored status message from this particular page. I have tried with `hook_page_attachments(array &$attachments)` in my custom module to include the css for admin theme.

But it is not working. How to solve this issue?

.

# Answer
> 2 votes
hook\_page\_attachments is not the correct hook. You want to implement hook\_preprocess\_HOOK, like the example below.

There are some caveats with this fix, especially if your site will be localized to other languages, see the comments within the code:

```
/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_status_messages().
 *
 * @param $variables
 */
function mymodule_preprocess_status_messages(&$variables) {
  if (isset($variables['message_list']['status'])) {
    $status_messages = $variables['message_list']['status'];
    $dummy_message_parameter_1 = '_parameter_1_';
    $dummy_message_parameters =       [
      '%dimensions' => $dummy_message_parameter_1,
      '%new_width' => 0,
      '%new_height' => 0,
    ];
    // The message could change eventually, but it is unlikely.
    // This logic *could brake* in a some language translations, if the %dimensions string is not the first parameter.
    $file_resize_message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.', $dummy_message_parameters);
    // $file_resize_message_start is the part of the message that won't vary.
    $file_resize_message_start =strtok((string)$file_resize_message, $dummy_message_parameter_1); ;
    foreach ($status_messages as $delta => $message) {
      if (strpos((string)$message, $file_resize_message_start) !== FALSE) {
        // The next commented line still leaves a green area
        // unset($variables['message_list']['status'][$delta]);
        // Removing all messages, the side effect is that you could be
        // missing on some relevant messages
        unset($variables['message_list']['status']);
      }
    }
  }
}

```

The message is set in the function `file_validate_image_resolution` at core/modules/file/file.module:447 (as of version 8.6.0-dev)

There is a good explanation about the hook implementation at Stack Overflow

# Answer
> 0 votes
I'd fix this with CSS. But maybe this specific message can't be targeted specifically. Although I'd definitely try that first.

And then have a look at Disable Messages.

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.
>
> Features
>
> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

---
Tags: 8, status-messages
---


# Question
Title: Is there a way to show the content right-to-left without manually changing CSS styles?
In a site where some of the pages are written using the Hebrew alphabet, I created a view that displays linked headings of nodes. The title is shown on the right, but the linked headings are on the left.

Is there a way to show a view right-to-left without manually changing CSS styles?

# Answer
> 2 votes
An alternative way so you don't have to change css all the time.

You can probably setup a generic RTL css rule in your theme (one time)

```
.rtl {
    direction: rtl;
}

```

and use this rule in each of your views under `advanced > css class` as you see fit.

**Alternatively** as Leymannx points out you can add `global text area` in the `header` of your view and add the following css

```
<style>.view {direction: rtl;}</style>

```

using `Full HTML` format as shown in the screenshots below

**NOTE:** `view` class is included in all views so this solution could potential affect all views on the page

---
Tags: views, 8
---


title: How do I change the comment sort order?

text:
# Question
Title: How do I change the comment sort order?
I am trying to work out how to change the order of a flat list of comments in Drupal 7. It seems that comments are listed in chronological order with the oldest appearing at the top and newer ones appearing further down. Is there some way of reversing this order so that the most recent comments appear at the top and older ones at the bottom?

There is a module called `sort_comments` but there is no official release version (only dev). The constraints of the project I am working on does not allow the use of non-production ready modules.

Project constraints also prevent the use of any custom modules. Only allowed to customize at theme layer (e.g. can create custom theme).

# Answer
You could use Comment goodness it has a stable D7 release.

> Provides comment sorting, comment form placement and comment form configuration settings.
> 1 votes

# Answer
Here is a simple way if you don't want to use Comment goodness, Use array\_reverse to reverse comments array in tpl.

1. Copy `modules/comment/comment-wrapper.tpl.php` into your `custom theme` with the same name.
2. Change this code `print render($content['comments']);` by:

```

 $comments = array_reverse ($content['comments']);
 print render($comments);

```
> 1 votes

---
Tags: 7, comments
---


# Question
Title: How are contextual arguments specified explicitly in the URL?
The examples in contextual arguments simply call for specifying them with slashes without specifying the name of the filter, but if you wish to apply the second or third filter in the contextual link, what syntax should be used? eg if there are contextual filters, on **`field_1`**, **`field_2`** and **`field_3`** and you want to ignore **`field_1`** and **`field_2`** in the URL, how do you write the URL for **`field_3`** only?

Even if you want to apply only the first filter, but specify it explicitly in the URL, what is the syntax for it?

PS. When contextual fields for different fields are applied are they combined with **`OR`** or **`AND`**? are they

# Answer
Contextual filters always use `AND` operator between them. Unless you use a special module to change it Views Contextual Filters OR.

But there are conditions under which a Contextual filter will show all the results as if it hasn't been applied. This means that it could be seen as if the `OR` operator is applied.

Contextual filters have two major options in their configuration:

```
`When the filter value is NOT available`

```

and

```
`When the filter value IS available or a default is provided`

```

Under the former options there is always the **Exceptions** setting, where the default value is `all` (you can change it if you think it would be better for UX).

But this means that you can use that expression in the URL as a way to temporarily cancel that Contextual filter, so you can test the others if you have more than one.

`field_1_value/all/all`

or in your case to ignore the first and the second one:

`all/all/field_3_value`

To apply the first one only you can use:

`field_1_value/all/all`

but you could also use

`field_1_value`

if you have configured the last two Filters to use
`Display all results for the specified field` or
`Provide default value`.

There is also the setting `Action to take if filter value does not validate` under `Specify validation criteria` where you can choose the option **Display all results for the specified field**. So you can also use this in combination with other settings, if it makes sense in your specific case.

Setting up a Contextual filter isn't a trivial thing, there are different "paths" that can come out out of a single filter, and you'll get a different set of results.
> 2 votes

---
Tags: 7, uri, views
---


# Question
Title: Group views exposed taxonomy filter terms based on parent
Here is the scenario :

We've got a taxonomy vocabulary called regions, this holds continents as parents and countries as children, this vocabulary then is used as a taxonomy term field in a content type called "Note", there user can select unlimited countries for the content. The user is forced to select from children so he/she cant choose a continent for that field.

Now I'm working on a view of "Notes", the country filter is exposed and user can select multiple countries, What I want now is to separate countries based on the continent they belong and show them in different part of form.

I know I can add a filter for each continent and select countries related to that continent using views but I'm looking for a programmatically based situation as the number of countries are so many and there might be human fault selecting proper countries for each continent.

# Answer
You have to use an additional module to influence how the Exposed filter is displayed: Views Reference Filter.

This module adds special new Filters to Views that rely on (existing) Entity reference Views Displays to filter the View. Basically, it's filtering one View Display with another View Display.

In your case, you first have to:

1. create an **Entity reference Views Display** that shows all the Countries, grouped by their Continents. It will be the `Term` type of View, not `Content`.

You're designing here what your Exposed Filter will later look like.
2. List Countries as Fields,
3. then use Parent item Relationship to show Continent for each Country,
4. Group the results by Continent (Parent) field in the `Entity Reference list` settings

You will now see a list of Countries grouped by Continents.
5. Save the View

With this ready you can:

1. edit your "Note" Content view,
2. add a new Filter `Has taxonomy term` that has **(reference filter)** in its name, expose it, and choose the Entity reference Display you created in previous steps above.
3. Use Better exposed filters module to display the choices as Checkboxes

You will now have a working Exposed filter by Countries that will be grouped by Continents.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to share some content in a multisite?
I'm working on the Drupal 8 multisite where there is main site and partner sites.

For example partners publish events or news.

I want some content from partner sites to be available on the main site. How can this be done?

What I discovered so far:

1. sharing db tables seems tricky - there are just to many node tables and their dependencies will likely break.
2. I could create custom entity but then its not place in "content" (beacause it's not node type) and I will lose nice content handling. but tables are easier to share then.
3. I could copy the content but then i have copies not the same content (what are possibilities here?)

# Answer
There are quite a few solutions available in Drupal contrib which allows sites to share the content with each other:

* Workspace In core now creates multiple versions of the site.
* Entity Pilot is a really good use core serializer solution. It tracks changes allow and merging via UI. If you want to track the content then you can also use Entity Pilot Git.
* CPS D7 version only.
* Domain access if your site shares the domain name then this is the best solution to display the same content on different domains.
* Default Content you have to manually import export the content.
* D8 to D8 migration is the last ditch solution there is no D8 to D8 migration in Drupal core at this moment but you can export content in CSV using CSV Serialization and then import it via Migrate Source CSV. The sites can periodically import or export data in hook\_cron.
> 1 votes

# Answer
You can use Domain module in Drupal 8 for content sharing .I am not sure about Acquia lift or Acquia Hub , you can check with this option too.
> 0 votes

---
Tags: 8, multi-sites
---


# Question
Title: Paragraphs Align Media Left or Right of Text with CSS
I am using Paragraphs module to create a cutom paragraph. The custom paragraph will have three fields: Image, Text and Position. Would like to use css to align as follows based on the value of the Position field.

Image Left | Text Right

Text Left | Image Right

Image Top / Text Below

How do I go about doing this? Do I need any extra configuration for the paragraph? Or is all the magic done in CSS?

# Answer
Yes, just CSS. You could use Classy Paragraphs to append CSS classes to your paragraphs depending on some field values, or you can do this very easily yourself (recommended) by preprocessing the paragraph in your theme's `*.theme` file.

---

Let's assume the position field is a single-value List (Text) field with the following allowed values:

```
image-left|image-left
image-right|image-right
image-top|image-top

```

Then you can easily retrieve that value and append it as CSS class by implementing `hook_preprocess_HOOK`:

```
/**
 * Implements template_preprocess_paragraph().
 */
function MYTHEME_preprocess_paragraph(&$variables) {

  $paragraph = $variables['paragraph'];

  // Retrieve certain field's values and add them as CSS classes.
  $classy_fields = [
    'field_image_position',
    'field_background_color',
    'field_social_media_type',
  ];

  foreach ($classy_fields as $classy_field) {

    if ($paragraph->hasField($classy_field)) {

      if (!$paragraph->get($classy_field)->isEmpty()) {

        $variables['attributes']['class'][] = $paragraph->get($classy_field)->getString();
      }
    }
  }
}

```

---

Which will result in `image-right` or whatever other class getting appended to this paragraph's attributes and it now can by styled accordingly:

```
<div class="paragraph-MYPARAGRAPH view-mode--default image-right">

```
> 4 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: How do I check the version of a third-party module?
There's a place in the search\_krumo module where we want to supply a different JavaScript file path basing on the version of the Devel module being used.

Is there a Drupal function that will check the version for us, or do we need to get the module version with `system_get_info()`, and then do something with `$module['version']` (which is a string like 7.x-1.5) ourselves?

If the latter, how should we test if version is greater than 1.6? Should we convert the string to an integer, strip out the x and stuff, and compare integers?

# Answer
> 1 votes
Supposing that the second version string is also in the *7.x-y.z* format, where *y* and *z* are numbers, you could use code similar to the following one.

```
function compare_module_version($module, $version) {
  $info = system_get_info('module', $module);

  if (empty($info) || empty($info['version'])) {
    // The module doesn't exist, it's not enabled,
    // or there isn't any information about the module version.
    return FALSE;
  }

  return version_compare($info['version'], $version);
}

```

If `$version` uses the *y.z* format (where *y* and *z* are numbers), you can use the following code.

```
function compare_module_version($module, $version) {
  $info = system_get_info('module', $module);

  if (empty($info) || empty($info['version'])) {
    // The module doesn't exist, it's not enabled,
    // or there isn't any information about the module version.
    return FALSE;
  }

  return version_compare(substr($info['version'], 4), $version);
}

```

If then both the version strings are in the 7.x-y.z format, and you want to compare the version string without considering the Drupal compatibility part of the version, you could use the following code.

```
function compare_module_version($module, $version) {
  $info = system_get_info('module', $module);

  if (empty($info) || empty($info['version'])) {
    // The module doesn't exist, it's not enabled,
    // or there isn't any information about the module version.
    return FALSE;
  }

  return version_compare(substr($info['version'], 4), substr($version, 4));
}

```

`version_compare()` is thought to compare version number strings, and it is able to correctly handle a version like `'7.x-1.0-alpha1'`, which is considered to be lower than `'7.x-1.0-beta1'`.

`compare_module_version()` returns `FALSE` if the module is not enabled (which also includes the case the module is not even installed), or when the information about the module version has not been found. Otherwise, it returns -1 if the module version is lower than the second function argument, 0 if they are equal, and 1 if the second function argument is lower.

I would not use `drupal_parse_info_file()` since that function re-parses the module .info file when the information contained in that file (or any .info file for enabled modules) has been already gathered from Drupal.

# Answer
> 0 votes
1. You can use `system_get_info('module', 'devel')` function and split version to get number after 7.x-
2. Or goes with this aproach parsing info file here is a solution from stackoverflow get a module version

---
Tags: 7
---


# Question
Title: How to use (reference) the uploaded file to a media(video) type?
I have read https://www.drupal.org/node/2941420 and I can upload a image file then use it in article.

But I can not use it as video field after I upload a video file.

My Drupal version is 8.6.0-beta2.

I use the media type ( Drupal 8 core module) for my video field, this is a Entity reference.

When I use

```
POST  http://www.myhots.com/file/upload/media/video/field_media_video_file?_fo...

```

I get the response as the end shows (the fid =47)

```
{
    "message":"Unprocessable Entity: validation failed.
field_user_video.0.target_id: The referenced entity (media: 47) does not exist.
"
}

```

Then I use it :

```
curl -X PATCH -H 'Content-Type: application/json' -H 'X-CSRF-Token:YYYYYYYYYYYYYYYYYYYY' -H 'Authorization: Basic XXXXXXXXXXX=' -i 'http://www.myhost.com/node/5?_format=json' --data '{

"type":[
    {
        "target_id":"user_video",
        "target_type":"node_type"
    }
],
"field_user_video":[
    {
        "target_id":47,
        "target_type":"media"
    }
]

```

}

The response is as follows:

```
{
    "message":"Unprocessable Entity: validation failed.
field_user_video.0.target_id: The referenced entity (media: 47) does not exist.
"
}

```

Which information should I use to patch it? It seems that the "fid" is not correct.

Maybe I need "target\_id " of "media“， but there is no response after I upload a video file, any suggestion?

```
"field_user_video": [{
  "target_id": 3,
  "target_type": "media",
  "url": "\/d86\/media\/3"
}]

'

{
"fid":[
    {
        "value":47
    }
],
"uuid":[
    {
        "value":"cf69fac4-5ba2-4861-9cce-a959dee3c480"
    }
],
"langcode":[
    {
        "value":"en"
    }
],
"uid":[
    {
        "target_id":1,
        "target_type":"user",
        "target_uuid":"c2b09ff8-345a-43fa-b9ae-68af0c9cd3ea",
        "url":"/d86/user/1"
    }
],
"filename":[
    {
        "value":"example2.mp4"
    }
],
"uri":[
    {
        "value":"public://2018-08/example2.mp4",
        "url":"/d86/sites/default/files/2018-08/example2.mp4"
    }
],
"filemime":[
    {
        "value":"video/mp4"
    }
],
"filesize":[
    {
        "value":6320348
    }
],
"status":[
    {
        "value":false
    }
],
"created":[
    {
        "value":"2018-08-31T03:04:20+00:00",
        "format":"Y-m-d\TH:i:sP"
    }
],
"changed":[
    {
        "value":"2018-08-31T03:04:20+00:00",
        "format":"Y-m-d\TH:i:sP"
    }
]
}

```

# Answer
> 0 votes
after two days trying , i find the solution myself. shortly ,

first, post file , get the fid.

second, post a media , get the Mid (media id)

third , post a node ,use the Mid

I omit the second step.

---
Tags: files, media, 8
---


title: How to test if memcache is working?

text:
# Question
Title: How to test if memcache is working?
After successfully enabling it, how do you know it's working? And how do you know how much better performance is increased?

In homepage of https://www.drupal.org/project/memcache it says:

* A module that provides a comprehensive administrative overview of Drupal's interaction with Memcached and stats.
* A set of tests that can be run to test your memcache setup.

But there is nothing for Drupal 8.

If you read docu http://cgit.drupalcode.org/memcache/tree/README.txt?h=8.x-2.x there is no information how to test/confirm memcache is doing its job.

It shows in Status report it's enabled. `Memcached version 3.0.0` But how do you know it's not just hanging around or idling?

Anyway, I read the 7.x docu and it had this:

```
## CACHE HEADER ##

Drupal core indicates whether or not a page was served out of the cache by
setting the 'X-Drupal-Cache' response header with a value of HIT or MISS. If
you'd like to confirm whether pages are actually being retreived from Memcache
and not another backend, you can enable the following option:

  $conf['memcache_pagecache_header'] = TRUE;

```

So I put in `$settings['memcache_pagecache_header'] = TRUE;`, but I don't see anything in my Network tab of Firefox's dev tools. All I see is `X-Drupal-Cache UNCACHABLE` with or without the setting.

# Answer
> 7 votes
You can enable the *memcache\_admin* module and this will provide a stats page at */admin/reports/memcache*, where you can see the number of sets and gets, hits and misses percentages and how much of the allocated memory is in use.

On the server, you can run this from the command line (assuming port 11211):

```
echo stats | nc 127.0.0.1 11211

```

# Answer
> 4 votes
The easiest things is:

* Take a backup of your site.
* Take another backup. :)
* `TRUNCATE` your cache tables in the database.
* Restart memcache.
* Clear caches, so dome page requests.
* Make sure caches that should be in memcache aren't in the database.
* Make sure caches that should be in memcache are actually there (use the CLI), check keys, and check stats

As for performance, that is beyond the scope of this site. You need to properly profile your site. And to do that properly, means optimizing everything else so you can properly gauge the impact of memcache.

---
Tags: 8, configuration, caching
---


# Question
Title: Taxonomy view page for double nested terms
I have a content type that has an entity reference to a taxonomy term. The referenced taxonomy term has furthermore taxonomy terms referenced to it.

On the taxonomy term view page, I would like the content appear, that refers to the terms nested inside first term reference.

The idea of double nested content and display on the taxonomy view page worked for me well, when I used for the first level nesting another content type instead of a taxonomy term. That way I could successfully apply following relationship and contextual filter on the view. I added a relationship to the entity reference field’s content and applied it to the contextual filter.

Now, wanting to use a taxonomy term as first level reference, I am not able to get it work. I thought the following should work, but it does not:

What relationship do I have to apply, to get the desired result?

(I hope I was able explain my problem comprehensibly)

Edit:

The schema is following:

NODE 1 \> TERM 1 \> TERM 3

NODE 2 \> TERM 2 \> TERM 3

TERM PAGE (taxonomy/term/3) SHOW: NODE 1 + 2

* The nodes have the reference field "field\_key\_data" that references the vocabulary "architecture". The terms in the vocabulary "architecture" have a term reference field "field\_style" (TERM 1 or TERM 2) of another vocabulary.
* The term in "architecture" may be different, but can reference to the same value in "field\_style" (TERM 3).
* If this is the case, the TERM PAGE for term 3 should show as result NODE 1 and NODE 2.
* Futhermore the result should be displayed with depth.

# Answer
## Show only *grandchild* nodes on Taxonomy term pages

In more words: Add nodes to Taxonomy term pages that are tagged with terms that reference the term shown on that page. This means that nodes that directly reference the TID will not be shown. Instead, we show nodes that have an additional Taxonomy link in between, a sort of *grandchild* connection.

We first introduce the "parent" connection (in your case it's "Architecture" from `field_key_data`). Then through it we bring in grandparent "Style" information from `field_style`. Since we want to show nodes that relate to that TID through that "lineage" we simply use Term ID Contextual filter with the "grandparent" Relationship.

1. Clone (Duplicate) the default Taxonomy term View (which is of Content type). It already has one Contextual filter (Has Taxonomy Term ID) that is responsible for showing all nodes tagged with that term. **Remove it**, we don't want parents, we're only interested in grandparent.
2. Add a Relationship **Taxonomy term referenced from field\_key\_data**.
3. Add another Relationship **Taxonomy term referenced from field\_style**, it will use the first Relationship.
4. Add a new Contextual Filter **Term ID**, make it use the **second** Relationship, and configure it:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from term page**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**
**Style** (or whatever in your case)
5. Under Query settings choose `Distinct` because you'll see duplicated results because Relationships introduce many connections so to prevent it Distinct only shows each node once.

No need for `Contextual OR` BTW, we only have one Contextual filter anyway :)

BTW you can "require" both Relationships since this entire scheme relies on existence of grandchildren.
> 2 votes

# Answer
## Add *cousin* nodes to Taxonomy term pages

In more words: Add nodes to Taxonomy term pages that are tagged with terms that reference the term shown on that page.

Node \> Original Term \> Referenced term \> Other nodes

Node is tagged with some term, that term has a field referencing another term, the other term also has nodes tagged with it. So it's kind of a *cousin* relationship between nodes.

What is required is a Contextual filter that filters out nodes tagged with a term, **OR** nodes tagged with a term that references the original term.

To do that we need to use Views Contextual Filters OR module.

1. Clone the default Taxonomy term View (which is of Content type). It already has one Contextual filter (Has Taxonomy Term ID) that is responsible for showing all nodes tagged with that term. You can leave that active.

The second Contextual Filter has to display nodes that have been tagged with terms that reference the "original" node. We have to add Relationships to introduce that new information into the Views.
2. Add a Relationship to Taxonomy terms (term).
3. Add another Relationship for the Taxonomy field referencing another Taxonomy field, it will use the first Relationship.
4. Add a new Contextual Filter for that same Field between Terms, make it use the second Relationship, and set it to display all results.
5. Under Query settings choose `Contextual filters OR`.

Now if your term 1 is referencing term 2, if you go to `taxonomy/term/1/2` it will show all nodes tagged with term 1 AND also all nodes that are tagged with term 2.
> 0 votes

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


# Question
Title: How can I control class="active" in a submenu
I have a view with several exposed filters, they work fine. I added the unfiltered view in the main menu. Then I copied the urls of the filtered results to add them as submenu.

The "active" class is attibuted to the ‘better exposed filter’ links in the form I show to my visitors, ahead of the view.
But only one of the submenu links is attributed that "active" class, even though it doesn't fit the displayed result. Does anyone see where the problem can come from?

See for yourself: https://nature-et-sens.eu/boutique.

Edit ----
I figured that the problem is slightly different. Here is what the submenu looks like (roughly):

```
<ul>
  <li class=""><a class="active" href="/boutique">…</a></li>
  <li class=""><a class="active" href="/boutique?some_filter">…</a></li>
  <li class="active-trail active">
    <a class="active" href="/boutique?some_other_filter">…</a>
  </li>
  <li>…</li>
</ul>

```

The only `<a class="active">` item which is properly styled is the one contained within the `<li class="active-trail active">`. I have no problem with that, my stylsheet complies accoardingly.

I would like to understand why this 'active-trail' class is always attributed to the very same item, even though it is not the one I clicked.

# Answer
Maybe this could help you, here
> 1 votes

---
Tags: 7, bootstrap-theme
---


# Question
Title: How to add a CSS class to an render array?
In a template file, before `print render($content['field_image']);` I would like to add a CSS class to the image in the `$content['field_image']` render array. How can I do this? Here is the render array:

```
Array
(
[#theme] => field
[#weight] => 2
[#title] => Image
[#access] => 1
[#label_display] => hidden
[#view_mode] => full
[#language] => und
[#field_name] => field_image
[#field_type] => image
[#field_translatable] => 1
[#entity_type] => node
[#bundle] => ll_basic_page
[#object] => stdClass Object
[#items] => Array
    (
        [0] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] =>
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array
                    (
                    )
            )
    )
[#formatter] => image
[0] => Array
    (
        [#theme] => image_formatter
        [#item] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] =>
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array ()
            )
        [#image_style] =>
        [#path] =>
    )
)

```

And this is the HTML output:

```
<div class="field field-name-field-image field-type-image field-label-hidden" thmr="thmr_96">
  <div class="field-items">
    <div class="field-item even">
      <span thmr="thmr_97">
        <span thmr="thmr_98">
          <img typeof="foaf:Image" src="http://..../sites/default/files/imageFile.jpg" alt="alt text" />
        </span>
      </span>
    </div>
  </div>
</div>

```

I tried adding a class to `$content['field_image']['#attributes']['class']`, but that didn't work.
Do you have any idea on how I can achieve what I am trying to do?

# Answer
I believe it would be:

```
$content['field_image'][0]['#attributes']['class'][] = 'my-class';

```

Or to assign it to every element,

```
foreach (element_children($content['field_image'] as $key) {
  $content['field_image'][$key]['#attributes']['class'][] = 'my-class';
}

```
> 7 votes

# Answer
The above solutions did not work for me (and weren't clearly described in any case). Here's the way I solved this exact problem. This is probably not the best way, and certainly not the only, but it's a valid "Drupal way" and works. Open up the **template.php** file for your template.

Paste in the following function, which you will have to MODIFY and customize for your usage scenario. For example, you must replace `<TEMPLATENAME>` with your template name, and add or subtract classes as desired, and other things, as you'll see.

```
function <TEMPLATENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'Staff Photo' then assign additional classes to it:
    if ($variables['style_name'] == 'staff_photo') {
        $variables['attributes']['class'][] = 'lightbox';
        $variables['attributes']['class'][] = 'wideborder';
    }
}

```

I created an "if" statement to determine when the class should be added to the image, but you will have to customize that however you like--you might eliminate it entirely if you want a class on ALL image-field images, or you might say `if (drupal_is_front_page())` if you only want it applied on the front page, etc.

In MY case, I created an image style (Configuration \> Media \> Image Styles) for Staff Photos and added the if clause to only apply my preferred classes to images of that specified Image Style. I think that's a great way to do it, but you can do what you like.

Now, whenever I am viewing a node which contains an image-field with image style of "Staff Photo," the classes magically appear in the IMG tag, which is just what I needed.
> 4 votes

# Answer
This issue seems fixed in core 7.23

In the node tpl add this at the top:

```
<?php
$content['field_name'][0]['#item']['attributes']['class'][] = 'your-class';
?>

```
> 3 votes

# Answer
You can also do something like this:

```
  $array['container']['#prefix'] = '<div id = "container">';
  $array['container']['#suffix'] = '</div>';

```
> 2 votes

# Answer
For those of you in a "field--field-image.tpl.php," use this:

```
$item['#item']['#attributes']['class'][] = 'your-class';

```
> 1 votes

# Answer
I was looking for a similar solution, but for styling a form input element and not an image. Inside my customized commerce\_coupon.checkout\_pane.inc include i added an #attributes array containing the necessary classes.

So if you're looking for a module entangled solution instead of template embedded, this might be a good alternative.

Running on Drupal 7.39

```
  $pane_form['coupon_add'] = array(
    '#type' => 'button',
    '#value' => t('Add coupon'),
    '#name' => 'coupon_add',
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'commerce_coupon_add_coupon_callback',
      'wrapper' => 'commerce-checkout-coupon-ajax-wrapper',
    ),
    '#attributes' => array('class' => array('btn', 'btn-13')),

```
> 0 votes

# Answer
If you need some conditions to apply the class, you'll need to gather page fields informations.

You can do it with function `template_preprocess_field(&$variables)`.

```
template_preprocess_field(&$variables) {
  if ($variables['element']['#field_type'] == 'image') {
        $variables['items'][0]['#item']['attributes']['class'][] = 'your-class';
  }
}

```
> 0 votes

---
Tags: 7, theming
---


title: Create URL and redirect?

text:
# Question
Title: Create URL and redirect?
```
function news_article_node_submit($node, $form, &$form_state)
{
// Make a URI link from title of pdf being uploaded
if (isset($form_state['values']['field_upload_import_pdf'])) {
    $file = file_load($node->field_upload_import_pdf['und'][0]['fid']);
    $filePath = file_create_url($file->uri);

    // Redirect to pdf
    isset($_GET['destination']);
    unset($_GET['destination']);
    if (isset($filePath)) {
        drupal_goto($filePath);

        // Return all field behaviors to redirect to default
    } else {
        $form_state['redirect'] = 'to page preview';
        drupal_redirect_form($form_state);
        }
    }
}

```

I was experimenting with `drupal_goto()` and `$form_state['redirect']`, but neither of them seems to work. Using `drupal_goto()` hijacks the whole module and the `$form_state['redirect']` doesn't do anything. Also I am getting PHP errors when `else` function encounters the first two lines of code above:

> Notice: Undefined offset: 0 in news\_article\_node\_submit()

> Notice: Trying to get property of non-object in news\_article\_node\_submit()

Is there a way to create a URI from the filename, and redirect users to `domainname://NAME_OF_FILE.pdf` when choosing a conditional field while, at the same time, when users use any other conditional field, the behavior is the default Drupal one?

# Answer
You can use the trick from the module File Force Download. You can check it in the their code repository https://cgit.drupalcode.org/file\_force/tree/file\_force.module?h=7.x-1.x
> 0 votes

---
Tags: forms
---


title: Get other users data custom value

text:
# Question
Title: Get other users data custom value
how can I get all (custom) data from other users ?

With my admin account, I want to show them in a page.

For example :

> * user 1 :
>     + name
>     + age
>     + custValue
>         - custValue1 / 2 / 3

I want to get custValue and the other data (custValue is the most important)

Example of values that I want to show :

# Answer
> 0 votes
Drupal 8 :

```
$user = \Drupal\user\Entity\User::load($uid);
$value = $user->field_name->value;

```

For multiple values, use

```
$value = $user->get('field_name')->getValue();

```

---
Tags: users
---


# Question
Title: Per language menu item settings in node forms
I'm working on a drupal 8 website. On every node the admin can choose wether or not to show a node in the main menu, and where it should be placed. This works great with the *menu settings* node form shown on every node edit page.

But at the moment I'm transforming the site to a multilingual website all is fine and via the *menu settings* node form it is possible to change the menu title but I can't choose to show a node in the menu for one language only.

So for example, I have a **about England** page that I want to show in the menu of my English site only and not in the menu of my Dutch site.

I thought it might be possible to only create an English node for this. But when I choose to add this English node to the menu it is shown in both my Dutch and English site even though there is no official Dutch version of the node. It's not official because I can't find it in the `admin/content` view but if you try to edit or show it it is there for some reason.

So for example when I create an English node with nid 62. When you want to see this you go to `/en/node/62` but the url `/node/62/` is also available and this is where the menu item on the Dutch site points to.

I also tried to have the node in both languages and unpublish one of them but then the menu item is removed from both menus.

Hope someone has a solutions for this, any suggestion is welcome. Thanks in advance.

# Answer
Okay the problem was that I used the Node view permissions module. Which works perfect but not for multilingual websites. That's why they also made Now view language permissions. By installing this and uninstalling the Node view permissions module the problem was solved.

Now it is possible to create a node and its translation and add them to the menu. By unpublishing the translation you see the default one in the menu and hide the translation from the menu in the other language.
> 0 votes

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