# Question
Title: Loading a custom library after all other libraries got loaded
So i wan't to load a custom `.js` file at the very end of the page after all other `.js` files have been loaded.

This is my library file:

```
my_library:
  js:
    assets/js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.dialog.ajax
    - core/toolbar.escapeAdmin

```

So the lib **is loaded** in the page footer with all the rest of the `.js` files, but it's not last, it's somewhere in the middle. I even tried to add the dependency for `toolbar.escapeAdmin` as it's javascript file is loaded the very last, as you can see from the picture bellow of the of `page:viewsource`, but it didn't work.

Any ideas?

# Answer
> 2 votes
That is neither possible (because JS files have no "weight" anymore in Drupal 8), nor does it make sense: Any module can declare a JS file as `async` or `defer`ed, so even if your file would be in last position in HMTL markup, there is absolutely no guarantee that it will be executed in that order.

PS: Module dependencies seem to quite reliably affect ordering of their JS libs in markup, not really certain about it though.

---
Tags: 8, javascript
---


# Question
Title: Two Views with autocomplete filters display no result
I have 2 views-blocks with autocomplete filters, both filters are for the title field. And autocomplete filters display no result when the views are placed on the same page. How to make them to not conflict with each other?

I use this module Views Autocomplete Filters

# Answer
The link provided by **WaQaR Ali** solved the problem.

> The problem lies in the fact that two form-fields get the same ID. Placing this code in a hook\_form\_FORM\_ID\_alter():

```
<?php
 $form['title']['#id'] = 'form-text-' . rand(0,100);
?>

```

Thank you Ali!
> 0 votes

# Answer
You can solve this issue by

1-clicking on your filter (in the view UI, under 'Filtering criteria')

2-Then scroll down in the opened window until you can open the "more" fieldset

3-Change the Filter ID to make it unique.. I mean if you can't have 2 block view on the same page with the same filter ID
> 0 votes

---
Tags: ajax
---


# Question
Title: Why is my Pantheon git clone not loading correctly?
My website is on Pantheon. I am using linux ubuntu 17.10 and LAMP for local development. I use the git clone command and it works. My drupal 8 files are there. Then I export and import the database sql file and the files folder. When I load my website on the local host I get this:

How do I fix this? What am I doing wrong? Am I missing a step?

# Answer
> 1 votes
The issue you're exhibiting is most likely a result of the database reflecting a temp directory (on the Pantheon server) that does not exist or is not writable on your local LAMP environment.

To reset the temp directory for your local development instance, you can:

1. use drush to set the temp directory (typically /tmp)
2. navigate to admin/config/media/file-system

If after setting the temp directory and clearing caches, you still exhibit similar behavior, you may want to double check the file owner/group permissions for the public files directory.

See https://www.drupal.org/node/244924 for a how to identify and set permissions, and refer to http://www.drupalden.co.uk/file-folder-permission-settings-drupal-7 which provides a good summary (note- permissions recommended for D7 also apply to D8)

# Answer
> 1 votes
If you have "Aggregate CSS files" and "Aggregate JavaScript files" checked in `/admin/config/development/performance` then the site will be trying to aggregate css and js files below the `sites/default/files` directory. However that site is not included in the codebase cloned from Pantheon, and you might not have thought to create it, especially if you haven't added files to your site.

**Quick Fix:** As a quick fix you can uncheck "Aggregate CSS files" and "Aggregate JavaScript files" checked in `/admin/config/development/performance`, then refresh the page. If that doesn't work then click "Clear all caches" on the same page. However your site will perform better with those 2 aggregation boxes checked. So...

**Better Fix:** A better solution is to visit your site's Pantheon dashboard, switch to the Git mode, open "Backups", create a new backup, then download the "Files" backup. Extract that downloaded tar.gz file which will give you a directory called something like `files_dev`. Move that directory into `sites/default/` and rename it to `files`. Check that it has `drwxr-xr-x` permissions. If not then `cd` to its parent `default` directory and issue the command `chmod 755 files`.

You should also check that your `sites/default` directory has `drwxr-xr-x` permissions. If not then open a terminal, `cd` to your `sites` directory and issue the command `chmod 755 default`.

Refresh the site and if necessary clear all caches and the css/js should work again.

For me this fixed a similar issue after importing a site from Pantheon to Lando.

---
Tags: version-control
---


title: Facet API block not displaying

text:
# Question
Title: Facet API block not displaying
To create a filter for my site I have installed following modules Search api, Search api db, Facet api

I followed the steps mentioned in http://www.webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages and http://www.webwash.net/tutorials/intro-search-api-part-2-faceted-search for creating facets.

I have created server and indexed my fields. Then I placed the Facet blocks in the particular region. But blocks are not displaying. Please Let me know what mistake I have done. Thank You

# Answer
I experienced the same problem. I desperately seeked a solution or even a little hint on the Internet but finally I figured it out.

My problem was about the database privileges of the default mysql user (the one with credentials in the settings.php). Facet api requires **Create Temporary Tables** privilege to run properly. And as you can tell, my db user was not granted that privilege. Running the following commands on mysql console solved the problem:

```
GRANT ALL PRIVILEGES ON your_db.* TO 'your_user'@'localhost';
FLUSH PRIVILEGS;

```

I hope this helps someone..
> 1 votes

---
Tags: search
---


# Question
Title: How can I disable a single checkbox in a 'checkboxes' FAPI element?
Title basically says it all, I want to disable a single checkbox of a **checkboxes** type FAPI element.

I don't want to do if with JavaScript, nor is changing it from **checkboxes** to multiple **checkbox** elements an option as the element is provided by another module.

Thoughts?

# Answer
> 37 votes
A clean way does exist in Drupal 7! Apparently, per this post, it's not yet documented.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#disabled'] = TRUE; //disables all options
  $form['checkboxes_element'][abc]['#disabled'] = TRUE; //disables option, called abc
}

```

Another example.

You can also set #access function to FALSE, to completely hide the checkbox.

# Answer
> 23 votes
Unfortunately there's no really clean way to do that in FAPI. Your best bet -- if you're determined -- is to alter an additional #process function onto the checkboxes element.

The default function added to elements of type 'checkboxes' is actually a function (expand\_checkboxes()) splits the single element out into multiple elements of type 'checkbox' that are later merged back into one. If you were to piggyback your second process function, it could reach into the expanded group of 'checkbox' elements and disable the one in question.

The following code is utterly untested, so caveat emptor:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#process'][] = 'mymodule_disable_element';
}

function mymodule_disable_element($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#disabled'] = TRUE;
      return;
    }
  }
}

```

# Answer
> 6 votes
Here is my code for Drupal 7, to change the Roles element in the Edit User page.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#pre_render'][] = 'form_process_checkboxes'; // I had to add this one, or it will return the first role only with my callback bellow
  $form['checkboxes_element']['#pre_render'][] = 'mymodule_disable_element';
}

function mymodule_disable_element(($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#attributes']['disabled'] = 'disabled';
    }
  }
  return $element;
}

```

# Answer
> 3 votes
I am using checkboxes as "assign" and "unassign". The client has asked that I disable "unassign", but it is still important to represent "assignment." Keeping in mind that DISABLED checkboxes submit as "false" and if not handled properly will unassign, I split my checkboxes into "process these" and "ignore these disabled ones." Here's how:

```
// Provide LIVE checkboxes only for un-assigned Partners
$form['partner']['partners'] = array(
  '#type' => 'checkboxes',
  '#options' => array_diff($partners, $assignments),
  '#title' => t($partnername),
);
// Provide DISABLED checkboxes for assigned Partners (but with a different variable, so it doesn't get processed as un-assignment)
$form['partner']['partner_assignments'] = array(
  '#type' => 'checkboxes',
  '#options' => $assignments,
  '#default_value' => array_keys($assignments),
  '#disabled' => TRUE,
  '#title' => t($partnername),
);

```

Notice that 'partner\_assignments' is its own array/variable and will not be processed as "unassign," in my use case. Thanks for posting-- it led me to this solution.

# Answer
> 3 votes
D7. Here we had to make sure that when adding a node one certain taxonomy term reference option is always uncheckable and will always be saved to the node. So we went into #after\_build and disabled that certain option, but had to make sure that in the end that certain option will be passed on. Cause only disabling it would have stopped that option's travel to future hooks.

```
// a constant
define('MYTERM', 113);

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'MYCONTENTTYPE_node_form') {
    $form['#after_build'][] = 'MYMODULE_MYCONTENTTYPE_node_form_after_build';
    }
}

/**
 * Implements custom after_build_function()
 */
function MYMODULE_MYCONTENTTYPE_node_form_after_build($form, &$form_state) {
  foreach (element_children($form['field_MYFIELD'][LANGUAGE_NONE]) as $tid) {
    if ($tid == MYTERM) {
      $element = &$form['field_MYFIELD'][LANGUAGE_NONE][$tid];
      $element['#checked'] = TRUE;
      $element['#attributes']['disabled'] = 'disabled';
    }
  }
  // here's ensured the term's travel goes on
  $form['field_MYFIELD'][LANGUAGE_NONE]['#value'] += drupal_map_assoc(array(MYTERM));
  return $form;
}

```

That's how the disabled option looks like:

# Answer
> 2 votes
I couldn't get Eaton's answer to work as written (the #process callback doesn't return anything, and it's called before the checkboxes are expanded) and I also wanted to have the value returned from the disabled checkbox (I wanted it permanently checked). This worked for me for Drupal 6.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#process'][] = 'mymodule_disable_element';
}

function mymodule_disable_element($element) {
  $expanded = expand_checkboxes($element);
  $checkbox =& $expanded[YOUR_CHECK_VALUE];
  $checkbox['#disabled'] = TRUE;
  $checkbox['#value_callback'] = 'mymodule_element_value_callback';
  return $expanded;
}

function mymodule_element_value_callback($element, $edit = FALSE) {
  // Return whatever value you'd like here, otherwise the element will return
  // FALSE because it's disabled.
  return 'VALUE';
}

```

# Answer
> 1 votes
Here is my code for Drupal 7, to change the Roles element in the Edit User page.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#pre_render'][] = 'form_process_checkboxes'; // I had to add this one, or it will return the first role only with my callback bellow
  $form['checkboxes_element']['#pre_render'][] = 'mymodule_disable_element';
}

function mymodule_disable_element(($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#attributes']['disabled'] = 'disabled';
      return $element;
    }
  }
  return $element;
}

```

# Answer
> 1 votes
Here is my example (using `#after_build`):

```
$form['legal']['legal_accept']['#type'] = 'checkboxes';
$form['legal']['legal_accept']['#options'] = $options;
$form['legal']['legal_accept']['#after_build'][] = '_process_checkboxes';

```

Plus the following function callback:

```
function _process_checkboxes($element) {
  foreach (element_children($element) as $key) {
    if ($key == 0) { // value of your checkbox, 0, 1, etc.
      $element[$key]['#attributes'] = array('disabled' => 'disabled');
      // $element[$key]['#theme'] = 'hidden'; // hide completely
    }
  }
  return $element;
}

```

Tested on Drupal 6, but it should work for Drupal 7 as well.

---

### Drupal 6

You can use the following function (source):

```
/*
 * Change options for individual checkbox or radio field in the form
 * You can use this function using form_alter hook.
 * i.e. _set_checkbox_option('field_tier_level', 'associate', array('#disabled' => 'disabled'), $form);
 *
 * @param $field_name (string)
 *    Name of the field in the form
 * @param $checkbox_name (string)
 *    Name of checkbox to change options (if it's null, set to all)
 * @param $options (array)
 *    Custom options to set
 * @param $form (array)
 *    Form to change
 *
 * @author kenorb at gmail.com
 */
function _set_checkbox_option($field_name, $checkbox_name = NULL, $options, &$form) {
    if (isset($form[$field_name]) && is_array($form[$field_name])) {
        foreach ($form[$field_name] as $key => $value) {
            if (isset($form[$field_name][$key]['#type'])) {
                $curr_arr = &$form[$field_name][$key]; // set array as current
                $type = $form[$field_name][$key]['#type'];
                break;
            }
        }
        if (isset($curr_arr) && is_array($curr_arr['#default_value'])) {
            switch ($type) { // changed type from plural to singular
                case 'radios':
                    $type = 'radio';
                    break;
                case 'checkboxes':
                    $type = 'checkbox';
                    break;
            }

            foreach ($curr_arr['#default_value'] as $key => $value) {
                foreach($curr_arr as $old_key => $old_value) { // copy existing options for to current option
                    $new_options[$old_key] = $old_value;
                }
                $new_options['#type'] = $type;  // set type
                $new_options['#title'] = $value;  // set correct title of option
                $curr_arr[$key] = $new_options; // set new options

                if (empty($checkbox_name) || strcasecmp($checkbox_name, $value) == 0) { // check name or set for
                    foreach($options as $new_key => $new_value) {
                        $curr_arr[$key][$new_key] = $value;
                    }
                }
            }
            unset($curr_arr['#options']); // delete old options settings
        } else {
            return NULL;
        }
    } else {
        return NULL;
    }
}

/*
 * Disable selected field in the form(whatever if it's textfield, checkbox or radio)
 * You can use this function using form_alter hook.
 * i.e. _disable_field('title', $form);
 *
 * @param $field_name (string)
 *    Name of the field in the form
 * @param $form (array)
 *    Form to change
 *
 * @author kenorb at gmail.com
 */
function _disable_field($field_name, &$form) {
    $keyname = '#disabled';

    if (!isset($form[$field_name])) { // case: if field doesn't exists, put keyname in the main array
        $form[$keyname] = TRUE;
    } else if (!isset($form[$field_name]['#type']) && is_array($form[$field_name])) { // case: if type not exist, find type from inside of array
        foreach ($form[$field_name] as $key => $value) {
            if (isset($form[$field_name][$key]['#type'])) {
                $curr_arr = &$form[$field_name][$key]; // set array as current
                break;
            }
        }
    } else {
        $curr_arr = &$form[$field_name]; // set field array as current
    }

    // set the value
    if (isset($curr_arr['#type'])) {
        switch ($curr_arr['#type']) {
            case 'textfield':
            default:
                $curr_arr[$keyname] = TRUE;
        }
    }
}

```

# Answer
> 1 votes
In Drupal 7, in order to disable options in a select in a fieldable entity, I found that I had to install a `#process` function. Unfortunately, this disabled the built-in process function, `form_process_checkboxes`, so that needs to be added back (or called from your process function). Additionally, when disabling checkboxes that are already checked, I discovered that the built-in value callback (`form_type_checkboxes_value`) ignores defaults when retrieving results from the input.

```
$field_lang_form = &$your_form[$field][LANGUAGE_NONE];
$field_lang_form['#process'][] = 'form_process_checkboxes';
$field_lang_form['#process'][] = 'YOURMODULE_YOURFUNCTION_process';
$field_lang_form['#value_callback'] = 'YOURMODULE_form_type_checkboxes_value';

```

Then something like this:

```
function YOURMODULE_YOURFUNCTION_process($element) {
  // Disallow access YOUR REASON, but show as disabled if option is set.
  foreach (element_children($element) as $field) {
    if (REASON TO DISABLE HERE) {
      if (!empty($element[$field]['#default_value'])) {
        $element[$field]['#disabled'] = TRUE;
      } else {
        $element[$club]['#access'] = FALSE;
      }
    }
  }
  return $element;
}

```

And finally:

```
function YOURMODULE_form_type_checkboxes_value($element, $input = FALSE) {
  if ($input !== FALSE) {
    foreach ($element['#default_value'] as $value) {
      if (THIS OPTION WAS SET AND DISABLED - YOUR BUSINESS LOGIC) {
        // This option was disabled and was not returned by the browser. Set it manually.
        $input[$value] = $value;
      }
    }
  }
  return form_type_checkboxes_value($element, $input);
}

```

I did not find that any of the other answers on this page worked in this case.

# Answer
> 0 votes
I am using this following code at drupal 6:-

```
$form['statuses'] = array(
    '#type' => 'checkboxes',
    '#options' => $statuses,
    '#default_value' => $status_val,
    '#after_build' => array('legal_process_checkboxes')
    );

```

and the call back function is here:-

/\** * Process each checkbox based on 'feture' is already used by a Sub-domain or not. * @param Array $element array of form checkboxes \*/

```
function legal_process_checkboxes($element) {

  foreach (element_children($element) as $key) {

    $feature_id = $key;
    $res_total = '';

    $total = feature_used($feature_id) ;

    if ($total) {
      $element[$key]['#attributes'] = array('disabled' => 'disabled');
    }
  }
  return $element;
}

```

# Answer
> 0 votes
One important thing to factor in is that disabled checkboxes do not get submitted, so you might find that you need to force the `#value` of the checkbox too.. For example:

```
$element['child1']['#disabled'] = TRUE;
$element['child1']['#value'] = 'child1';

```

In my case, without this, the `$form_state['values']` did not contain my checkbox value (which was checked by default, but disabled).

# Answer
> 0 votes
Hook textfield and make a dynamic textbox with info from database

1° get the assoc. array from database eg

```
$blah = array('test1' => 'Choose for test1', 'test2' => 'Choose for test2', ...)

```

2° Implements `hook_form_alter()`

/\** * Implements hook\_form\_alter(). * form id = views-exposed-form \*/

```
function test_form_alter(&$form, &$form_state, $form_id)
{
  //only for this particular form
  if ($form['#id'] == "views-exposed-form-advanced-search-page-2")
    {
       $form['phases'] = array(
           '#type' => 'checkboxes',
           '#options' => $blah,
      );
    }
}

```

3° multiple fields will be checkable !

# Answer
> 0 votes
If you're building your own form, instead of running through separate form\_alter/#process/#pre\_render functions you can just switch from 'checkboxes' to generating individual 'checkbox' elements.

```
$options = array(
   1 => t('Option one'),
   2 => t('Option two'),
);

// Standard 'checkboxes' method:
$form['my_element'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Some checkboxes'),
  '#options' => $options,
);

// Individual 'checkbox' method:
$form['my_element'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('form-checkboxes')),
  '#tree' => TRUE,
  'label' => array('#markup' => '<label>' . t('Some checkboxes') . '</label>',
);
foreach ($options as $key => $label) {
  $form['my_element'][$key] = array(
    '#type' => 'checkbox',
    '#title' => $label,
    '#return_value' => $key,
  );
}
// Set whatever #disabled (etc) properties you need.
$form['my_element'][1]['#disabled'] = TRUE;

```

`'#tree' => TRUE` gives you the same tree structure as the checkboxes version when the $form\_state\['values'\] array arrives at validation/submit/rebuild. If you can't or don't want to use #tree for some reason, give each checkbox a `'#parents' => array('my_element', $key)` property to explicitly set its position in the values structure.

---
Tags: 7, forms
---


# Question
Title: How to list nodes in a view as checkboxes?
For my drupal 8 website I need to create a view page with nodes of particular content type. I need to dispaly them as a list of checkboxes, and further implement a PDF manual, composed out of the "checked" nodes. Is it possible to implement it using standard Drupal tools?

# Answer
> 1 votes
You'll have to test that particular combination yourself, but there are modules that seem the best fit to try first.

To be able to select individual views results and perform actions on them you need Views Bulk Operations (VBO). You don't need to look further than that module for this part.

The tricky part is the PDF. Views PDF and Printer, email and PDF versions might have helped in D7 but they don't seem to be ready in D8.

In D8 Entity Print seems to be the rightful heir so try that one. Also I don't know how far you can get without custom code. You will probably need to use Rules to create the action that would be executed with VBO.

---
Tags: views, 8
---


# Question
Title: How to apply the page-hiding snippet for Google Optimize?
I'm trying to use Google Optimize on a Drupal 8 site through Google Tag Manager. I have set up the tags in Google Tag Manager through Google's UI and used the Google Tag Manager module to add the snippets to my site on path `/test/*`.

However, according to the Google Optimize documentation, I should also add a "page-hiding snippet":

```
<HEAD>
<!-- Page hiding snippet (recommended)  -->
<style>.async-hide { opacity: 0 !important} </style>
<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-XXXXXX':true});</script>

```

There are three requirements here.

1. The snippet needs to come before the Google Tag Manager tag in the HEAD of the page.
2. The snippet should only be shown on pages with path `/test/*`
3. Inside the snippet, the `GTM-XXXXXX` needs to be different for dev/staging/live environments.

Is there a way to standard way to set this up? I assumed that Google Optimize/Analytics is popular enough there would be some information for integrating it with Drupal, but all I found was this DrupalCon 2019 seminar that hasn't happened yet.

Setting up Google Tag Manager was fine, but I'm lost at how to get this final bit in the right place.

# Answer
> 1 votes
Well, since posting my question, there is now a Google Optimize Hide Page module, which provides a code example of how to do this.

There is also a patch to add this functionality to the Google Tag Manager module.

---
Tags: 8, javascript
---


# Question
Title: How to prevent the conversion of text URL to link on a single URL?
I have a page that I am adding, and for my purposes I want to have a text-only URL without an automatic link, but only for that one link, one this specific page. I need to be able to add full html content to the page, and I would prefer if other URLs on the page automatically became links.

I have tried putting other tags around the URL and HTML-escaping certain characters in the URL, but it still gets converted to a link.

Is there a way to prevent a specific URL from becoming a link?

# Answer
> 1 votes
The only way I think it is possible to selectively disable the "Convert URLs into links" filter is to use CSS and add something like below to the body. Since CSS is applied client-side after Drupal has returned the page, the filter is effectively disabled for this one single link.

```
<style type="text/css">
  .mylink > span {
    display:none;
  }
  .mylink:after {
    content: 'http://www.google.com';
  }
</style>
<p class="mylink"><span>blah</span></p>

```

Since you are using the 'Full HTML' format, you should be able to add CSS directly into the body field like shown.

---
Tags: 7, navigation
---


# Question
Title: How do I set the default values for creating a new content type?
This is a follow up to my question in Can I change the Display Settings by modifying the database? which was answered. Basically, I could not get to the 'display authoring and date information' checkbox because of a module installed. Running the command 'drush cedit node.type.article' as given in @4k4's answer allows me to change this setting.

However, when a new content type is created, the type has `display_submitted: true` set meaning I have to go in and change it whenever a new content type is created, which I sometimes cannot do.

Is there a way to change the default settings so that any new content type has `display_submitted: false` by default?

# Answer
For content or config entities you can set default values in a hook\_ENTITY\_TYPE\_create():

```
use Drupal\node\Entity\NodeType;

/**
 * Implements hook_ENTITY_TYPE_create() for 'node_type'.
 */
function mymodule_node_type_create(NodeType $node_type) {
  $node_type->set('display_submitted', FALSE);
}

```
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How to display list of nodes by number in views
I want to put my custom list of ids to views filter but is seems to work only for one id. How can I do it for this list for example (1, 5, 9, 12, 455)

# Answer
You can use the filter operator for regular expressions and this regex:

```
1|5|9|12|455

```
> 3 votes

---
Tags: views, 8
---


# Question
Title: basics of settings.php and settings.local.php?
What is the up-to-date basic workflow regarding database credentials when you launch a local version of a site that is already operating remotely?

What are the considerations and how is each best addressed? Are there advanced considerations that might require one to vary the basic approach?

Thoughtful confirmations of the community's understanding welcomed. (As appropriate) I'll happily help kick off documentation. It appears not to be documented clearly elsewhere, though if someone else has seen clear documentation on each point of the workflow and related decisions, please include links in your remarks.

UPDATE:

As promised above, I've started working on improving drupal docs. I've opened an issue https://www.drupal.org/project/user\_guide/issues/3013725

# Answer
Its common to either include a local settings file from settings.php or create a site folder for local development (local.mysite.com) that has a settings file that will be used. In either case, both are gitignored so its only for you. This also avoids the annoying issue when Drupal locks the site folders from being written, causing git errors when pulling or switching branches.
> 1 votes

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


# Question
Title: Drush on production server without Composer
I want Drush 9 on a Drupal 8 production server without having to install Composer. Is there any way to do this?

And if that is not possible, can anyone suggest an alternative to Drush especially for maintenance, updating and syncing the site with dev and staging?

# Answer
> 11 votes
If you don't want composer in production on your server, you can run the composer commands locally to install Drush, then make sure to push the vendordirectory to the server. Make sure to also commit the composer.json and composer.lock files, so that anyone else working with the codebase can handle composer on their own local machines as well.

In this way you never need composer on the remote production server, but can get drush.

# Answer
> 2 votes
On the production stage we don't need Composer (neither composer.json nor composer.lock), Composer is used to build your project and to generate the vendors after that it is necessary to pack all the generated files and to deploy them on the target server.

# Answer
> 1 votes
If you build out your D8 site locally in your dev environment using Composer, you'll have Drush 9. Then, if you commit your D8 instance (Git) and pull onto your server, you'll have Drush- albeit you'll have to execute using the full path. For example: From my command line on a Ubuntu 18.04, I can execute

> $ vendor/bin/drush pml --no-core

My D8 instance on the Production servers contains the following at the root.

Notice that /vendor is committed and present in this repository. And that contains /vendor/bin/drush

Refer to the Drush Documentation for more info.

Hope this helps!

---
Tags: drush, composer
---


# Question
Title: Best way to display PDF in drupal as a slideshow
I'm looking to display a PDF on a page, but don't want to outsource the hosting to scribd or slideshare, or one of the other players. My constraints are basically...

1. I want to host it on my site.
2. I want it to look like a slideshow (can click to go forward, navigation backward, etc.)
3. I want most users to have whatever they need to access it already (ie, if it's SWF, fine.)
4. I want the whole PDF to be downloadable easily, as a PDF (rather than SWF, etc).

Does anything fit that bill? I saw on stack overflow, at one time the answer was no.

https://stackoverflow.com/questions/291813/best-way-to-embed-pdf-in-html

But wondering if the Drupal way can offer any better.

# Answer
> 7 votes
Drupal is essentially a framework, it can't do anything that a 'normal' website can't do. This includes displaying PDF files in the format you want.

The only way is to use Flash (as suggested on the SO post you linked to). This would involve either building the SWF file yourself using Adobe's tools, or using one of the dozens of tools available to build a navigable SWF from a PDF file (e.g. SWFTools).

Drupal only comes into the equation when you actually want to *display* the Flash file.

Some purists might actually argue that this is a bad idea anyway; you should probably allow your users to read PDF files using the software that they have chosen for that particular job.

If you were trying to DRM your PDF for whatever reason then it might make sense, but as you're providing a download link to the direct file anyway I don't think this applies.

# Answer
> 3 votes
You could do this using imagecache with ImageMagick + GhostScript to convert the PDF pages into individual JPG files. Then you can use a slideshow module to display the JPGs, and provide a download link to the original PDF.

The PDF to ImageField module that converts PDFs to images (although I haven't used it). Here is an excerpt about it from the module's project page:

> ... provides automatic conversion of uploaded PDF files to images. It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.
>
> The module is implemented as an additional widget for File Field where PDFs are uploaded to. It places generated images into a Image Field on the same content type.

Keep in mind many servers use GD for image processing, and GD cannot deal with PDFs. So you need to make sure you have ImageMagick available on the server.

# Answer
> 3 votes
Noticed some good answers already but havent seen this module been mentioned:

http://drupal.org/project/pdf\_reader

You might want to take a look at it. It offers for example the option to use pdf.js, the pdf viewer Mozilla is going to use in FF 19:

http://www.webpronews.com/mozilla-kills-the-pdf-plugin-in-firefox-19-2013-01

I would not recommend to use any Flash now, HTML5 is out and tablets being hot (compatible problems).

# Answer
> 2 votes
If the browsers of your users support HTML5, you can use the PDF module. Here is an excerpt about it from the module's project page:

> Use HTML5 to display PDF files if users don't have pdf plugin for their browsers. Thanks to pdf.js project by Mozilla.
>
> With this module you can use pdf.js to display PDF file all the time or only use pdf.js when visitors don't have pdf reader plugin.

If you need to support old browsers like IE6, you can try the File viewer module. Here is an excerpt about it from the module's project page:

> ... adds Internet Archive BookReader for PDF and EPUB support into Drupal to make both of them can be open and view file field in the browser. "Search inside" was just added. Can be bugy. If you upload a book, it will be very slow, because I just use JS for search. Maybe do it on server side in the future. didn't test on IE.

Neither of them require Flash.

# Answer
> 1 votes
I don't think you can get around using Flash in this situation, especially if you want a user interface that is anywhere near what the user would get by opening the PDF natively. It's dubious to hijack the user's preference for viewing PDFs in the first place, but at least don't give them a highly inferior UI/experience to boot.

The SWFTools module has support for FlexPaper, an open-source flash plugin for viewing PDFs. It's only available for D6, but another option would be to create a custom module to implement the FlexPaper API yourself.

# Answer
> 1 votes
Have you considered converting your PDF into HTML and import to your Drupal site? You could do that using Acrobat's save as Word function, clean up the document in Word and save as HTML. There are ways to then import the single HTML into Drupal books such as using Feeds (see some examples). That way your pages will be just standard HTML and it will be way easier to navigate through pages than using an embedded PDF reader.

# Answer
> 0 votes
Try FlexPaper - there is a HTML5 PDF viewer with "readonly" option - should do the trick and you get around Flash: http://flexpaper.devaldi.com/

# Answer
> 0 votes
Does anyone have experience with the contrib PDF module? Its project page mentions it uses the pdf.js project by Mozilla. I'll give it a test drive for d8 and report back....

Related: https://stackoverflow.com/questions/291813/recommended-way-to-embed-pdf-in-html

---
Tags: files, javascript
---


# Question
Title: Form incorrectly displays differently depending on logged in user's role
All logged in users can add a forum node. The current topic is determined by a field in another node (nid=77) and set to the default value for the node being created by this form.

While this all works perfectly for admin users, authenticated users see only **'- Select a value -'** as the default value. I verified with set\_message that the code obtains the correct default value of the taxonomy term. What could be causing this? Note in case of authenticated user, `<option value="_none">` is the only item in the select list. For admin user, the select list contains all of the taxonomy items with the correct option value set to `selected="selected"`.

```
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id != 'node_forum_form') {
    return FALSE;
  }
  else {

    $nid = 77; // Node ID 77 contains this week's topic in field_topic
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $current_topic_id = $node->get('field_topic')->getString(); // get the TID
    $term = Term::load($current_topic_id); // load the term from the taxonomy
    $the_topic = $term->getName(); // get the Term Name for the debug message

    $form['field_topic']['widget']['#title'] = 'The Current Topic';
    $form['field_topic']['widget']['#default_value'] = $current_topic_id;
    $form['field_topic']['widget']['#disabled'] = TRUE;

    drupal_set_message('current_topic_id: ' . $current_topic_id . ', termName: ' .  $the_topic);

    return $form;
  }
}

```

For admin role, developer tools show `<option value="44" selected="selected">Name of the entity</option>` as well as all the other values/names of taxonomy items.

For authenticated user role, only one item is listed, `<option value="_none" selected="selected">Select a value</option>`.

# Answer
> 1 votes
Your code isn't manipulating the select field's options (`$form['field_topic']['#options']`), so the difference in options is something outside your code (you can confirm this by commenting out your form manipulation code).

If this is the case, you'll have to investigate why non-admin auth users are seeing empty options; it seems like it would have something to do with user permissions on your taxonomy, field, or something else that would prevent auth users from querying the valid terms for your taxonomy field.

---
Tags: 8, forms
---


title: How to create menu overview?

text:
# Question
Title: How to create menu overview?
I'm creating a custom menu in the administration for my module with multiple elements. This works fine by defining the forms, routes and menu links.

How can I create a page like /admin/config for my custom menu? Is it created somehow automatically or do I really need to create a custom page that lists all submenu items in a custom controller?

# Answer
> 1 votes
You can use SystemController::systemAdminMenuBlockPage as controller in the route of parent menu of module. Some like this:

```
mymodule.overview:
  path: '/admin/mymodule'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'My module overview'

```

---
Tags: 8, navigation
---


# Question
Title: How to hide certain taxonomy views from user?
I have one general taxonomy view wich has this alias mask /taxonomy/term/%.

What I need is to hide views for certain taxonomy terms like 'canada' from display while it'll remain showing the other ones the same way it was before.

# Answer
> 1 votes
Out of the box Views only has 2 different types of access management:

* Via role
* Via permission

However, it's an all-or-nothing control; you can't do it on a per contextual argument basis (for a taxonomy in your `/taxonomy/term/%` view).

What you can do, is create your own Views access plugin (or perhaps one already exists, look through drupal.org for 8.x Views projects). Take a look at the access plugin code docs or this tutorial as primer on how this is done.

# Answer
> 1 votes
Although you could edit the existing views and with some effort split the display into more than one page that would address each of the special terms individually it's not the most convenient way to go.

There are modules that can help you get there: Permissions by Term. It doesn't only restrict access of the taxonomy term pages but the nodes as well. There is a documentation page with more information: Documentation: Permissions by Term.

If that doesn't help then try Taxonomy Permissions (not quite D8 ready) and/or Taxonomy access fix.

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


# Question
Title: How do i create a breadcrumb based on Main Navigation Menu in programatically?
I want to display the breadcrumb according to the main navigation menu.
If i've a menu structure like
a-\>b
-\>c
-\>d
e-\>f
-\>g
Now if i go to menu **a-\>c**, now the breadcrumb shows **Home \> c** but i want it as like **a \>b**
How to do it programatically ?

# Answer
> 0 votes
Menu breadcrumb module create breadcrumb based on a menu. Maybe this could help.

---
Tags: 8, breadcrumbs
---


# Question
Title: "managed_file" form field type returns null value in my form submission
I am have been struggling with this for the past day or so. I am simply trying to create a custom entity and populate/or update the image field with the fid. Whats weird is that every other form field I am passing I can get the value for but this managed\_file field for uploading an image always returns NULL when I call `dpm()`.

```
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

```

Within my form\_build function, I use the following code.

```
// Manage file.
$form['theimage'] = array(
  '#type' => 'managed_file',
  '#title' => 'Managed file',
  '#description' => $this->t('Manage file, #type = managed_file'),
  //'#default_value' => $form_state->getValue('theimage'),
  '#upload_location' => 'public://images/',
  '#required' => FALSE,
);

```

In the submission handler, I use the following code.

```
// Get the fid value, upload it and save it to the managed file table.
$fid = $form_state->getValue(['theimage', 0]);
dpm($fid);
if (!empty($fid)) {
  $file = File::load($fid);
  $file->setPermanent();
  $file->save();
}

```

Any thoughts, solutions, or recommendations would be greatly appreciated.

# Answer
After alot of digging/debugging i discovered that i could not pull any data from the "manage\_file" field while using the PrivateTempStore in my Multi-Step form. After disabling the form cache, i began to get the values and the expected behavior by using:

```
$form_state->disableCache();

```

My Submit Handler

```
public function buildForm(array $form, FormStateInterface $form_state) {
 /**
 *  Fixes image upload bug in form. Does not work unless we
 disable the cache while using PrivateTempStore
 **/

 $form_state->disableCache();

.......

}

```

See https://www.drupal.org/project/drupal/issues/2647812#comment-11683961
> 1 votes

# Answer
$form\_state will show NULL or empty arrays in the file upload if you don't use the proper upload function. The file hasn't been uploaded yet.

In the validation function, for example, you should use the function file\_save\_upload.

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

  $file = file_save_upload('banner_image', array(), FALSE, 0, FILE_EXISTS_REPLACE);
}

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Force Creation of New Node With hook_feeds_presave Rather Than Node Update
I want to have very specific control over the node update process for Feeds. Using `hook_feeds_presave()` I can stop a node from being updated with `$entity->feeds_item->skip = TRUE;` but how can I force a new node to be created.

If a node would otherwise update an existing node I want it to create a new node.

This is for Drupal 7.

Thanks!

# Answer
You can make use of Entity::isNew function to check if the entity is new, and skip the setting of skip to true:

```
  if(!$entity::isNew()){
    $entity->feeds_item->skip = TRUE;
  }

```
> 0 votes

---
Tags: feeds
---


# Question
Title: Which method creates the cache directories inside sites/default/files
I am trying to solve the question SETGID bit gets reset for newly created directories inside sites/default/files. Please Note the **Update-2** there.

I want to know which method creates the directories like php, css and js inside the `web/sites/default/files` directory. I think the method or function which creates css and js abuse the `chmod` function because only PHP directories obeys the setgid (set group ID) bit rule.

# Answer
> 1 votes
> I think the method or function which creates css and js abuse the chmod function

There's no code that abuses `chmod` in Drupal. There simply couldn't be - the only interface to the system `chmod` that PHP provides is its own `chmod` function. It's not possible to abuse that function, it only accepts two basic parameters.

It would, of course, be possible to provide extra functionality via a custom PHP extension, but only you could know if you had such a thing installed.

But to answer your specific question:

> I want to know which method creates the directories like php, css and js inside the web/sites/default/files directory

That's `FileSystem::mkdir`. You can see from looking at the handful of lines of code in there that there's no abuse of `chmod` \- just the standard usage.

---
Tags: 8, files
---


# Question
Title: Drupal Commerce Stock Availability or Out of Stock
I am working on Drupal Commerce website. Using Commerce Stock I am able to manage the inventory but on product details page I want to print the following.

Availability: In Stock

or

Availability: Out of Stock

Also if possible

Availability: Limited Stock

If I am displaying stock filed its showing number of items available in stock, which I don't want to display.

Is there any way in Drupal I can acheive this task?

# Answer
> 1 votes
On Drupal 7.61 & Commerce Stock 7.x-2.3 I've solved it with hook\_commerce\_product\_reference\_default\_delta\_alter:

```
/**
 * Implements hook_commerce_product_reference_default_delta_alter().
*/
function test_module_commerce_product_reference_default_delta_alter(&$delta, $products) {

foreach ($products as $product) {
  if ($product->commerce_stock['und'][0]['value'] > 0){
    $product->commerce_stock['und'][0]['value'] = "On stock";
  }else {
    $product->commerce_stock['und'][0]['value'] = "Out of stock";
  }
 }
}

```

# Answer
> 0 votes
You can set these message in **STOCK** manage display of every product variation type. **Store-\>Configuration-\>Product variation types-\>YOUR PRODUCT VARIATION TYPE-\>Manage display**. Change label as **above** and change format as **Show stock display as message** .Finally change the message on settings on right side of field.

---
Tags: entities, rules, commerce
---


# Question
Title: How to map multiple existing term IDs to an entity
I'm trying to map multiple existing terms using their target\_id values to an entity (Commerce Product) and I can only get the first value to map.

My yml file looks like this:

```
  'field_prod_category/target_id':
    plugin: explode
    source: tid
    delimiter: ','

```

And, for now, I'm hard coding two existing term ID values in through the source plugin like so:

```
$row->setSourceProperty('tid', '806,635');

```

But no matter what I try only the first term is referenced. And, yes, the term field is set to unlimited.

Any ideas?

# Answer
You need to use plugin sub\_process. File yml have soure like this:

```
  field_prod_category:
    plugin: sub_process
    source: tids
    process:
      target_id: tid

```

and soure plugin need to prepare:

```
$tids = [
      'tid' => 806,
      'tid' => 635
    ];
$row->setSourceProperty('tids', $tids);

```
> -1 votes

---
Tags: 8, taxonomy-terms, migrations
---


# Question
Title: How can I override the page title using contextual filters?
I have 3 contextual filters in a view and I use them to override the views title. However, still, the page title (title in the browser tab) are still using the default title of the view. How can I make it use the title provided from the contextual filters?

# Answer
Most themes output the main page title also into the `<title>` element in the HTML `<head>`, usually with the site name appended.

The title you see in the browser tab should be the same as the main title you see on the page, unless your theme does something different (unlikely) or you're using a module that changes the Page title (for example Metatag).

The `Override title` option is only activated `When the filter value IS in the URL or a default is provided`. If this option isn't kicking in when it seems it should (either in page title or in the browser tab) then there is no contextual filter or it doesn't validate in some way. This is most likely a problem with your contextual filter configuration.
> 2 votes

---
Tags: views, 8
---


# Question
Title: How can i configure the core search module to also show results for incomplete words?
I see that the results page only shows results if the "keys" parameter matches a complete word. how Can i configure the core search engine to also show results for incomplete words?

I am using core search module .

# Answer
> -1 votes
Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. No need for Solr.

Enable both the modules and go to the Search API configuration page (admin/config/search/search\_api)Add a server and give it a recognizable name (such as "MySQL"), make sure it's enabled.

Choose the following service class: Database service (normally the only option. If you don't see it, make sure that the "Search API Database Search" module is enabled).

Selecting this service class will provide you the option Search on parts of a word (make sure you enable it). Now hit "Create server".

Next, go back to the Search API configuration page, and add an index. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled. Select the server you recently created (in this example "MySQL"). Datasource options: check the content types you want to index (the description of this field may be a bit confusing, but make no mistake: you should check the content types you want to index, not the ones you want to leave out).

You could check "Index items immediately", but that depends on the size of your content. This option is alright for smaller websites. In the other case: let cron take care of it. Hit "Create index".

Next, you want to enable the fields (in the fields tab) to that very index, e.g.: content type, title, status and author - and hit "Save changes" (we'll take care of the related fields later).

Then you want to configure the filters (in the filter tab). Here you can enable the bundle filter, if you want to finetune the content types once again (probably won't need to). Down below you'll find the highlight filter, to highlight the search word in the results. Now return to the fields tab and unfold the "Add related fields" tab. Add all the fields of which you want to get the content indexed, and hit Save.

Finally go to the "view" tab of the index, and index now all the items. The last step is to create search results page and search block in Views, which only takes a few minutes.

Make sure the submodule Search Views is enabled and create a view page which will show "Contentindex" (select the name you gave to your index configuration instead of "content" which is selected by default.

Add all the fields (make sure your format is "fields") that every search result should consist of (title \[link to content\], body, …).

You'll notice that these fields look like this Indexed Node: Title Add an exposed filter: Search: Fulltext search; and select the following in its settings: Contains any of these words, and use as: Search keys.

You're done!

---
Tags: 8
---


title: Rules Flag Count

text:
# Question
Title: Rules Flag Count
I have added a flag \[FOLLOW\] that allows users to follow each other. Using Display Suite, I am trying to add a token field that will count total number a FOLLOWS a user has received.

From what I can gather you should be able to add token \[flag-follow-count\] but it is not working.

What is the right way to add a count to show how many times a user has been followed?

# Answer
> 2 votes
I haven't tried it with Tokens but there is **Flag Followers** Views you can use.

The Page display already lists all users and their Follower count. You could add a Block display and set a contextual filter to filter out only one relevant user, depending on where exactly you want to display that Block.

If you do decide to edit the views it's good practice to Duplicate it and work on that instance, disable the original so you always have it intact for future reference.

---
Tags: 8, flags
---


title: Media and cache keys

text:
# Question
Title: Media and cache keys
I'm using images inside of a Paragraph, and trying to use checkboxes in the Paragraph to control whether to display the credit and/or caption of the images.

The problem is that the image gets cached the first time it loads and subsequent instances ignore the checkbox values.

I'm trying to set that cache keys so that each Paragraph + image gets its own cache instance, but keep getting errors saying that I'm not allowed to set cache keys.

I've tried in hook\_media\_preprocess, hook\_paragraph\_preprocess, hook\_entity\_view, hook\_entity\_view\_alter, but no luck.

Could someone point me in the right direction?

Thanks,

Luca

# Answer
> 0 votes
This might sound like a dumb solution, but the simplest and fastest solution of hiding fields would be hiding with CSS depending on a parent (paragraph) attribute or class. E.g. in paragraph preprocess

```
if ($paragraph->get('your_field')->value == "hide credit") {
  $variables['attributes']['class'][] = 'paragraph--credit-hidden';
}

```

and in CSS

```
.paragraph--credit-hidden .field--credit {
  display: none;
}

```

Other options would be either additional view modes for media entities (if not to many permutations), additional cache contexts (depending on the case, given your problem description most likely not a good solution), corresponding to your host paragraph settings. But given your description I'd go the KISS way and avoid the coding overhead.

---
Tags: caching
---


# Question
Title: Edit button on content which users have permissions to edit, including their profile
If I am logged in as an administrator, I get the contextual edit buttons an all blocks and nodes and can edit. If I am logged in as a user with less permission, but still enough to edit that content, those buttons aren't there. There are also no edit buttons on the user profile pages for any types of user, so if you are not an admin, you cannot easily edit this. I was hoping for a way to either turn on the contextual admin style pencil buttons for all users with permission to edit a specific bit of content, or at least be able to add my own buttons in the node or user template if allowed.

# Answer
Contextual Links are a Permission that can be enabled for different roles via admin/people/permissions. If enabled, it will only show the options that user has access to.

If I wanted to add my own custom buttons in different situations, I'd start with Display Suite which allows me to create custom fields (which might be my buttons) and show/hide those buttons based on View Mode, content type, etc.
> 1 votes

---
Tags: 8
---


# Question
Title: How to render the field from custom block in node.twig
I want to render the custom field from my block in node.twig. As I understand I have to expose the fields from Block to Node variables.

How to realize that?

# Answer
A node should not have access to a block unless you've done something to add the block to the node. A block can have access to node fields, though (the reverse).

To do what you're talking about I would recommend adding that block to the node in some way. For example:

if you want to add a block as a field in a node: https://www.drupal.org/project/fieldblock I would normally use Display suite to then output this block as I want, where I want. But you can also access it via twig template at this point just as you would any other field.

if you're building with paragraphs: https://www.drupal.org/project/paragraph\_blocks
> 1 votes

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


# Question
Title: Unable to override default translation publishing status using entity_translation module
We are using the entity\_translation module in a large site, and we have 57 defined languages. We have some custom date fields in each locale, and we are using some custom code to only publish the locale when the current date is within the specified date range. However, one problem we are running into is that when an entity (node, taxonomy term) is created, the Published status for the default language (`en-us` in our case, defined at `admin/config/regional/entity_translation`) is automatically set to Published, which we don't want, so I need to override that value and set it to 0.

After delving into the module code, I found the `hook_entity_translation_insert` hook, which is called from `EntityTranslationDefaultHandler:saveTranslations()`:

```
  foreach ($translations->hook as $langcode => $info) {
    $translation = isset($translations->data[$langcode]) ? $translations->data[$langcode] : $langcode;
    $data = isset($info['data']) ? $info['data'] : NULL;
    module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);
    // Provide Rules events integration if available.
    if (module_exists('rules')) {
      // Pass the entity as a wrapped one since rules can't do it for us
      // when using the variable type 'entity'.
      rules_invoke_event('entity_translation_' . $info['hook'], $this->entityType, entity_metadata_wrapper($this->entityType, $this->entity), $translation, $data);
    }
  }

```

where `$op = 'insert'`. I tried implementing my hook like so:

```
function mymodule_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
  }
}

```

but that doesn't change the status that gets passed on. If I try passing `$translation` in by reference:

```
function fluke_staging_entity_translation_insert($entity_type, $entity, &$translation, $values = array())

```

krumo gets into a huge recursive loop, and my computer maxes out the CPU.I can return a value like so:

```
function mymodule_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
    return ['translation' => $translation];
  }
}

```

but that's worthless, too, because the hook invocation doesn't do anything with it:

```
module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);

```

as compared to

```
$new_data = module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);

```

or something like that.

So my question is, how can I override the translation status in this hook, since it doesn't seem that it's a) passable by reference, or 2) it accepts any data from the `hook_entity_translation_insert` implementation?

# Answer
I ended up posting this to the module issue queue and got this suggested code:

```
function MODULE_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  // Set the publishing status for en-us to 0.
  if ($translation['language'] == 'en-us') {
    $translation['status'] = 0;
    $handler = entity_translation_get_handler($entity_type, $entity);
    $handler->setTranslation($translation);
    // Important: Avoid infinite loops by firing the insert hook again and again.
    $handler->getTranslations()->hook = array();
    $handler->saveTranslations();
  }
}

```

which was pretty close to what I had come up with on my own:

```
function mymodule_entity_insert($entity, $type) {
  // We don't want to do this for field collections.
   if (in_array($type, array('node', 'taxonomy_term'))) {
    // Attempt to unpublish the en-us translation that is set to published by default.
    $handler = entity_translation_get_handler($type, $entity);
    $translations = $handler->getTranslations();
    $enus_translation = $translations->data['en-us'];
    // Set the status = 0.
    $enus_translation['status'] = 0;
    $handler->setTranslation($enus_translation);
    // Save the translation.
    $handler->saveTranslations();
  }
}

```

And since it's not part of the saveTranslations() hook firing logic, no infinite loops should occur.
> 0 votes

---
Tags: 7, hooks, i18n-l10n
---


# Question
Title: How create a new variable according field value
Please I need a hand, I would like to create a new variable like the native "frontpage" variable. I have a content type called "Config", in this CT I have some boolean fields and I need check for this field values to print a view in my page.tpl

Something like this, my example field "display reviews block?", its may be set "yes" or "no". So, I need create a new variable "$display\_reviews" according this value and print this in page.tpl:

```
<?php if (isset($display_reviews)): ?>
 <?php print views_embed_view('reviews', 'block'); ?>
<?php endif; ?>

```

Sincerly, I dont know how to do this, but i tried something like this:

```
function mytemplate_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $n = $variables['node'];

    if ($variables['node']->type == 'config') {

        if (isset($n->field_display_reviews == 'yes') {
          $variables['display_reviews'] = 'this variable need be created';

        }
    }

 }
}

```

UPDATE

Considering I want to print this variable in my node.tpl not in my page.tpl, I have decided to try with directly query, I dont know if is the better and fast way, but this is my code. Its not working yet, this is broking my site, but now I can display the FIELD ID. Im trying to use the field\_attach\_load to get the field value but no luck:

```
/**
* Implementation of preprocess_().
*/
function mytemplate_preprocess_node(&$variables, $hook) {

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'config')
  ->propertyCondition('status', 1)
  // value 1 from boolean field
  ->fieldCondition('field_display_reviews','value', '1', '=');
$result = $query->execute();

if (isset($result['node'])) {
  $stories = $result['node'];

  $fields = field_info_instances('node', 'config');

  // Get id of field
  $reviews = $fields['field_display_reviews']['field_id'];
  field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $reviews));
  $output = field_get_items('node', $stories, 'field_display_reviews');

  $variables['display_reviews'] = $output;

}

}

```

# Answer
> 0 votes
Your code is already there, i think you didn't extract the value of the `field_display_reviews` correctly, try the following:

```
 /**
 * Implements hook_preprocess_HOOK().
 */
function mytemplate_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $node = $variables['node'];
    if ($node->type == 'config') {
      if (
        isset($node->field_display_reviews[LANGUAGE_NONE][0]['value'])
        && $node->field_display_reviews[LANGUAGE_NONE][0]['value'] == 'yes'
      ) {
        $variables['display_reviews'] = 'this variable need be created';
      }
    }
  }
}

```

**NOTE**: if your `display_reviews` field of type `Boolean` the value it will be `1` instead of `yes`, print the value of `$node->field_display_reviews[LANGUAGE_NONE][0]['value']` before if to see.

---
Tags: 7, theming
---


# Question
Title: How to setup view to filter based on second URL parameter?
We have a view, `myview`, that is added to the `https://www.adomain.com/some-page/` page. It has an exposed filter, `Topic` that a person can use to filter the user where `Ajax = Enabled` so that it loads the results without refreshing the page.

The view is added to a landing page (`content type = basic`) and at the bottom of the page. It is meant to return nodes where `topic` tag value is equal to what is supplied from the url.

Taxonomy term values (topic):

1. IoT
2. Cloud
3. Cloud Security

**How to setup view to filter based on second URL parameter?**

Expected behavior:

1. Display all items when `https://www.adomain.com/some-page/` is loaded.
2. Display all items where `topic = Cloud Security` when `https://www.adomain.com/some-page/cloud-security` is loaded
3. Display all items where `topic = Cloud` when `https://www.adomain.com/some-page/cloud` is loaded

Current Behavior:

1. Displays all items when loading `https://www.adomain.com/some-page/`
2. Displays no items when loading `https://www.adomain.com/some-page/cloud`

**What we have tried using `block display type`:**

1. Create view using `block display type` with a contextual filter `Content: topic`
2. `When filter value is not available` = `Display all results for the specified field`
3. `When the filter value is available or a default is provided` is set to `Specify Validation Criteria = enabled`, `Validator = Taxonomy Term Name`, `Vocabulary = topic`, and `Action to take if filter value does not validate = Display all results for the specified field`

**What we tried using `Page display type`:**

1. add path `/some-path` (without `%`)
2. Add relationship, `field_topic: taxonomy term` and `require relationship = true`
3. Add contextual filter: `Name from Taxonomy term (field_topic)` with the following settings below.

Contextual filter settings:

`When the filter value is not in the URL`

* Display all results for the specified field

`When the filter value is in the url or a default is provided`

* `Specify validation criteria` = `Validator = Taxonomy term name`
* `Vocabulary` = `Topic`
* `Transform dashes in URL to spaces in term name filter values` = true
* `Action to take if filter value does not validate` = Display a summary
* `Case` = Lower case
* `Case in path` = lower case
* `More` = `Transform spaces to dashes in url = enabled`

# Answer
> 4 votes
Content Views don't have access to Taxonomy term name information out of the box, you only have term ID available. So even if you add the Taxonomy term field as the contextual filter and set the `Validator = Taxonomy Term Name` you're not telling it what to use, you're basically making a mistake trying to use that validator.

You can test this if you enter the term ID into the Preview instead of the name, or set the `Action to take if filter value does not validate` to `Display a Summary` and see what you get as output ;)

## Add term name info through Relationship

To introduce the term name information into your content views you have to:

1. add a Relationship to the term: `Taxonomy term referenced from field_topic`. Require it if you only want to list nodes that have a topic assigned.

Now you will see a new Category of fields when adding Contextual filters: `Taxonomy term`
2. Add the Contextual filter `Name` from `Taxonomy term` Category, it will use the Relationship from previous step by default, and configure it:
`When filter value is not available`
**Display all results for the specified field**
`When the filter value is available or a default is provided`
**Specify validation criteria**
**Taxonomy term name**
\[Case settings, other relevant config as you see fit\]

You will now see all results when visiting the main path, and if you visit the path with topic name appended the list will be filtered to show only nodes with that topic.

---

## In case you have terms with the same name accross vocabularies

There is a bug that kicks in sometimes when using term name as the Validator, if you have different terms with the same term name: TermName views argument\_validator is not working as expected.

The patch from that issue is working, as reported by the question author usernameabc, so it can be used until a new version is released that includes it.

---
Tags: views, 8
---


# Question
Title: Using Automatic Entity Label how to add number if title is already used (unique)
I have setup auto entity label with tokens. All works great. Lets say I have a title e.g. tokens \[firstname\] \[lastname\]

Displayed as: Tom Cruise

But if there are multiple identical titles named "Tom Cruise". e.g.

node 65: Tom Cruise
node 90: Tom Cruise
node 23: Tom Cruise

What I want is it to validate, the title is not unique therefore add number on the end.

node 65: Tom Cruise
node 90: Tom Cruise 1
node 23: Tom Cruise 2

Or something like that. I have been using nid / serial field to make them unique but that isn't what I need.

# Answer
You can add node id to the label. It will make labels unique anyway. For example

```
[node:field_first_name] [node:field_last_name] #[node:nid]

```

Please note, that there is an issue in module that prevents \[node:nid\] token from working. https://www.drupal.org/project/auto\_entitylabel/issues/2920695

But there is simple patch available in this issue to fix this. So this should be resolved soon I hope. Until that you need to apply patch manually. https://www.drupal.org/files/issues/2018-11-11/auto\_entitylabel-support\_entity\_id-2920695-31.patch
> 1 votes

---
Tags: forms, entities, nodes
---


# Question
Title: How to sort language select list on current language context
I have a form with a language field with the language select list widget. The options of this field contains an array with a pattern like

```
['langcode' => t('language')]

```

Now I want to sort these options in the right order.

The default sorting is on the value but not on the translated one.

e.g. \['de' =\> t('german')\] which I translated into "Deutsch" will now sort under "g" instead of "d".

So I did try to do it in a form alter hook and a preprocess hook but this is not the right place to do it, because the values are still untranslated here.

So my question is how can I sort these options if the values are translated?

# Answer
> 2 votes
Now I did this in a form\_alter\_hook.

This worked for me.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function arph_profile_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $language_options = $form["field_languages"]["widget"][0]["value"]["#options"];
  $new_language_options = [];
  foreach($language_options as $langcode => $language) {
    /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $language */
    $new_language_options[$langcode] = $language->render();
  }
  asort($new_language_options); // We need to keep the keys here.
  $form["field_languages"]["widget"][0]["value"]["#options"] = $new_language_options;
}

```

# Answer
> 2 votes
i think it can be done in a hook\_form\_alter()

if the options are in $form\['languages'\], you can do something like :

```
$language_options = $form['languages'];

```

then manipulate the array $language\_options, until it has the order you need then override it in form :

```
$form['languages'] = $language_options;

```

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


title: Can I initialize the broken view mode?

text:
# Question
Title: Can I initialize the broken view mode?
In a bundle of content types, I placed fields on many vertical tabs of the field group. In order to switch display / non-display of the field, I moved and saved it without going well for each tab. Movement of many fields and field groups at one time was not very easy. t was saved with tab items and fields that do not belong to parent tab. After that, even when tabs and fields were moved and saved, there was no change.

I think that the View mode is broken. I also copied the broken view mode to default. Therefore, all the view modes are deleted, the newly created view mode is copied from the broken default and remains broken.

Is there a way to restore the default view mode for a particular bundle?

Environment: Drupal 8.5.6, Field group module 8.x-3.0-beta1, Display Suite 8.x-3.1

# Answer
Export the config and open the view mode in a text editor or run this drush command from the command line:

```
drush cedit core.entity_view_display.node.[content-type].default

```

Then remove the field settings you think could break your view mode and import the config again or exit/save if you used the drush command.
> 2 votes

---
Tags: 8
---


# Question
Title: Invalid parameter number: number of bound variables does not match number of tokens: SELECT 1 AS expression
Good Morning

I get this error: Invalid parameter number: number of bound variables does not match number of tokens: SELECT 1 AS expression (edited)

I need to insert an array of values into a field in the table using merge

I attach my code for revision. Thank you

```
public function submitForm(array &$form, FormStateInterface $form_state) {
$connection = \Drupal::database();
$this->nids=array();
/**
* Load the current User.
* Use \Drupal\user\Entity\User::load.
*/
$uid = \Drupal::currentUser()->id();
$this->nids= $form_state->getValue('field_nodes');

// foreach ($this->nids as $nid){
//   $this->nid = $nid;
//   // var_dump($this->nid); die();
// }

  $result = $connection->merge('WishList')
  ->key(['nid' => $this->nids])
  ->fields([
  'uid' => $uid,
  'nid' =>$this->nids,
  ])->execute();

```

# Answer
> I need to insert an array of values into a field in the table using merge

If you mean that literally, it isn't possible - a PHP array is not a type of data that can be inserted into MySQL.

Maybe you meant to loop over the IDs instead:

```
foreach ($this->nids as $nid) {
  $result = $connection->merge('WishList')
    ->key(['nid' => $nid])
    ->fields([
      'uid' => $uid,
      'nid' => $nid,
    ])->execute();

}

```
> 0 votes

---
Tags: database
---


# Question
Title: Page not found error when creating a simple module
I have my first module in drupal 8 with three files in modules section of my drupal:

**hello\_world.routing.yml:**

```
hello_world:
    path: '/hello/world'
    defaults:
        _controller: '\Drupal\hello_world\Controller\HelloWorldController::hello'
    requirements:
        _permission: 'access content'

```

**hello\_world.info.yml:** ( in modules/hello\_world/src/Controller directory)

```
name: Hello World!
type: module
description: Say Hello World
package: Custom
core: 8.x

```

**HelloWorldController.php**:

```
namespace Drupal\hello_world\Controller;

class HelloWorldController {

    public function hello() {

        return array(
                '#title' => 'Hello World!!!',
                '#markup' => 'Here is some content.',
            );
    }
}

?>

```

however, when I press clear all caches button and run code again. I just have *Page not found* problem.

# Answer
> 0 votes
hello\_world.info.yml sould be in modules/hello\_world/

then check if the hello\_world is enabled and rebuild cache

---
Tags: page-controller
---


# Question
Title: How to edit e-mail settings for project issue content type
I am using the project and the project issue module on a Drupal 7 instance and ran into some trouble with the notification settings.

Apparently, the `poject issue` module saves for every content type a variable which contains information which e-mail sender address should be used for e-mail notifications on new issues etc. The variable is named `project_issue_reply_to_NAME_OF_CONTENT_TYPE`. **How can I change this value for an existing content type?**

As the variable is of type `blob` I can't change the value easily in the database.

# Answer
suggestion 1 :

drush vset project\_issue\_reply\_to\_NAME\_OF\_CONTENT\_TYPE test@example.com

suggestion 2 :

in a custom hook\_update\_N() : variable\_set('project\_issue\_reply\_to\_NAME\_OF\_CONTENT\_TYPE', 'test@example.com');
> 1 votes

---
Tags: 7
---


# Question
Title: Set default country for the Address type element (Webform)
I'm using the webform module (8.x-5.0-rc12) and I've used the *Address* type element to store my addresses.

I'd like to set the *Country* field to default to *United Kingdom* when the form is displayed.

Does anyone konw if I can set that within the user interface?

Thanks.

# Answer
Under the 'Address' element's 'Advanced' tab, you can set the 'Default value' via the UI.
> 6 votes

---
Tags: webforms
---


# Question
Title: How to sort on different columns in the same view?
I'm trying to build a Glossary View in Drupal 8. Let's say I have 3 content types: Person, Article, Event. I want sort by title ASC for Article and Event, but sort by Last Name for Person. So that listing would show something like.

Deep Study on Dolphins (article) John Doe (person) Jam in the Backyard (event)

And Not

Deep Study Jam in the Backyard John Doe

I think I can do this with hook\_views\_query\_alter, but the only examples I've seen are for Drupal 7.

I've got something like this

```
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'glossary_everything') {
     $query->orderby[0]['field'] = "CASE WHEN node_field_data.last_name IS NULL THEN node_field_data.title ELSE node_field_data.last_name END";
  }
}

```

But I'm getting a "column not found" sql error. I think it's treating the whole CASE statement as one big field. Is that because of the \['field'\] designation in my array?

# Answer
> 7 votes
In Drupal 8, if you want to alter an ORDER BY, in particular to use a formula, you have to add an expression and then order by it:

```
$query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'order_field');
$query->orderBy('order_field', 'ASC');

```

There can be some confusion in Views, because their version of addExpression is Sql::addField. And in fact, Sql::addOrderBy let's you add a field and order by it in one call.

So, your code would look like:

```
$sql = <<<SQL
CASE
     WHEN node_field_data.last_name IS NULL THEN node_field_data.title
          ELSE node_field_data.last_name
END
SQL;

$query->addField(NULL, $sql, 'last_name_else_title');
$query->orderby[] = array(
  'field' => 'last_name_else_title',
  'direction' => 'ASC',
);

```

Or just...

```
$query->addOrderBy(NULL, $sql, 'ASC', 'last_name_else_title');

```

Thanks agileadam for pointing out the failure point (see also).

# Answer
> 1 votes
This is caused by the call to `$this->connection->escapeField($field)` in `\Drupal\Core\Database\Query\Select::__toString()`.

`\Drupal\Core\Database\Connection::escapeField` is wiping out the spaces (CASE WHEN becomes CASEWHEN, for example), which renders your statement invalid.

I don't have time to come up with the solution, but that's where it's breaking.

# Answer
> 0 votes
From this example, this is how you would do to sort by a date field and Node published date:

```
   $orderBySql = <<<ORDER_BY_SQL
CASE
  WHEN node__field_date.field_date_value IS NULL THEN node_field_data.created
  ELSE UNIX_TIMESTAMP(DATE_FORMAT(node__field_date.field_date_value, '%Y%m%d'))
END
ORDER_BY_SQL;

    // Override existing Order rules.
    $query->orderby = [];
    $query->addOrderBy(NULL, $orderBySql, 'ASC', 'diff_date_fields');

```

---
Tags: views, 8, database
---


# Question
Title: Adding custom html and css to views header and footer
Is it possible to add custom HTML and CSS in views header and footer using the administrative UI? I am trying to add a header to my view but that is not giving me any option through which I can add HTML and CSS like the options which are given to us when we add fields in views. I have tried adding a header using Global Textarea but in this, we can only write HTML not CSS. Kindly tell how can we add HTML and CSS both to the header.

# Answer
> 2 votes
It isn't good practice to intermix HTML and CSS (embed CSS or use inline styles). As a rule CSS is kept separate in files in your theme, and some in modules.

Views allows you to define CSS classes for certain parts of the output, but you still have to keep the CSS rules and declarations in your theme.

If you don't have access to your subtheme for some reason or only want to apply tiny changes you can try CSS Editor. It gives you a place where to enter new CSS rules that will apply throughout your theme.

You still have to edit your Views output to include the custom HTML classes to elements you want to style, you can do that through Global Text area as you already found.

Many themes already assign a lot of classes to various Views parts, so maybe you already have classes relevant to your design and you can use them in custom CSS without adding new classes in HTML.

---
Tags: views, 8
---


# Question
Title: How to programmatically set the user timezone
I am programmatically creating a user and wanted to assign a timezone for the user

I am able to successfully create a user by the following code

```
$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);

```

How do I assign the timezone?

# Answer
> 3 votes
You can use Set method on `user` Entity like the following:

```
$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);
//- Set Time Zone to London
$user->set('timezone','Europe/London');
$user->save();

```

**NOTE :** You can set other fields with `set` method, for example if you can activate the user with `$user->set('status',1);` or give him administrator role with `$user->set('roles',['administrator']);` .

---
Tags: 8, users, datetime
---


title: Admin toolbar default left / vertical

text:
# Question
Title: Admin toolbar default left / vertical
On page load I need to

* show the toolbar on the left / in vertical mode when in admin theme
* collapse/minimize the toolbar when in frontend theme

I'm looking for the event and the function to trigger those actions programmatically, e.g. something like

`$(document).on('toolbar.loaded', Drupal.toolbar.setOrientationLeft);`

and

`$(document).on('toolbar.loaded', Drupal.toolbar.closeToolbar);`

(I'm using the Admin Toolbar plugin)

Please note that I'm looking a solution that does *not* check CSS classes or triggers DOM clicks, in order to avoid timing problems due to asynchronous loading or exisiting toolbar settings.

# Answer
This is the cleanest and most reliable solution I've found so far. It uses localStorage and view models like the core toolbar itself. These are the important parts of my module:

toolbar\_always\_vertical.info.yml

```
name: 'Toolbar always vertical on the left'
type: module
description: 'Shows the toolbar by default in vertical mode, on the left side and hide it on frontend pages.'
core: 8.x
dependencies:
  - toolbar

```

toolbar\_always\_vertical.libaries.yml

```
toolbar:
  version: 0.0.1
  js:
    js/toolbar.js: {}
  dependencies:
    - toolbar/toolbar

```

toolbar\_always\_vertical.module

```
function toolbar_always_vertical_preprocess_html(&$variables) {
  $variables['#attached']['library'][] = 'toolbar_always_vertical/toolbar';
}

```

js/toolbar.js

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.toolbarAlwaysVerticalSetToolbarDefaults = {
    attach: function (context, settings) {
      if (Drupal.toolbar.views.toolbarVisualView) {
        // this forces the vertical orientation
        localStorage.setItem('Drupal.toolbar.trayVerticalLocked', 'true');
        Drupal.toolbar.views.toolbarVisualView.model.set({locked: true, orientation: 'vertical'}, {validate: true, override: true});
        if (drupalSettings.path.currentPathIsAdmin && Drupal.toolbar.views.toolbarVisualView.model.attributes.isFixed) {
          // show administration toolbar when in admin and not collapsed
          Drupal.toolbar.views.toolbarVisualView.model.set({activeTab: $('#toolbar-item-administration')});
        }
        else {
          // hide toolbar when on frontend page
          Drupal.toolbar.views.toolbarVisualView.model.set({activeTab: null});
        }
      }
    }
  };
})(jQuery, Drupal, drupalSettings);

```

There is a critical point all other answers missed: **it has to be done in a module and not in a theme**, because only modules can add dependencies to other modules and guarantee that the code is exectued *after* the core toolbar.
> 0 votes

# Answer
If you go through its possible to make it as horizontal. Try this code wherever needed:

```
jQuery('#toolbar-bar button').each(function(){
  if(jQuery(this).html() === 'Vertical orientation'){
    jQuery(this).click();
  }
  if(jQuery(this).find('span.label').text() === 'Tools'){
    var open = jQuery(".toolbar-box").find('.open').length;
    if (open > 0) {
      jQuery(this).find('span.label').click();
    }
  }
});

```

For checking try this in the console first and add snippet to your JS file.
> 0 votes

# Answer
If you look into the js file in the toolbar core module , there is no event like this triggered.

I you want this event, i think you'll have to override or extend the toolbar behaviors.

For exemple :

```
(function ($, Drupal, drupalSettings) {
    var behaviorsToolbar = Drupal.behaviors.toolbar;

    Drupal.behaviors.toolbar = {
        attach: function attach(context) {
            behaviorsToolbar.attach(context);
            $(document).trigger('toolbar.loaded');
        }
    };
    //this is just a exemple but it worked for me, to force horizontal toolbar
    $(document).on('toolbar.loaded', function () {
        if ($('.toolbar-toggle-orientation button').hasClass('toolbar-icon-toggle-vertical'))
            $('.toolbar-toggle-orientation button').trigger('click');

    });

})(jQuery, Drupal, drupalSettings);

```

We have to be sure that this script is call every time a toolbar is created, so we attach it on the toolbar itself :

```
/**
 * Implements hook_toolbar_alter().
 */
function mymodule_toolbar_alter(&$items) {
    $items['administration']['#attached']['library'][] = 'nameOfYourLibrary';
}

```
> 0 votes

# Answer
**Try please this code:**

```
Drupal.behaviors.changeToolbar = {
  attach: function (context, settings) {
    // Your code (if) ...
    $(context).find('#toolbar-bar').click('.toolbar-toggle-orientation button'); // Change orientation.
    $(context).find('#toolbar-bar').click('.toolbar-item-administration'); // Close.
  }
};

```
> -1 votes

# Answer
In the top-right corner of the Admin section there is a left-facing arrow, which, when you hover over it says "Vertical orientation". Is this not an easy way to achieve this?
> -1 votes

---
Tags: 8, toolbar
---


# Question
Title: Can I connect via REST services with a mobile app I will develop?
I'm thinking of developing an e-commerce with Drupal 8 and Drupal Commerce, but I need to know if I can connect via REST services with a mobile app that I would develop too. The app would need to be able to create carts, make orders, payments, and so on.

I have already developed several apps which connect to Drupal 8 and created content, but I need to know if it's possible to create orders, carts, payments, etc.

# Answer
yes you can exposes entities and other resources as RESTful web API by activating the core RESTful Web Services module

> /admin/modules
> 0 votes

---
Tags: 8, commerce, services
---


title: Run a drush command via module

text:
# Question
Title: Run a drush command via module
Is there a way to run a Drush command using a module? I tried `exec("drush ...");` but I have found out it is not recommended. Is there any other command I could use?

# Answer
It is better to use `drush_invoke_process()` rather than `exec()`.

```
$values = drush_invoke_process("@site", "cc", array("all"), array("verbose"));

```
> 4 votes

# Answer
drush\_invoke\_process() can be used in a drush context. Since cron is executed via drush you can used it inside a cron.
> 0 votes

---
Tags: drush
---


# Question
Title: Translate the allowed values list of an entity access field?
I have a field of type: `Entity access field`.

In my allowed values list I have:

```
public|Public
community|Community

```

I have all of the core translation modules enabled:

* Configuration Translation
* Content Translation
* Interface Translation
* Language

I cannot find where in the administrative interface to translate these. Can they be translated in the interface?

# Answer
As @4k4 already said in his comment, if you have the Configuration Translation module enabled, you simply go to *your-site*/en/admin/structure/types/manage/*your-content-type*/fields and select the list field you want to translate (see screenshot below).
> 1 votes

---
Tags: 8
---


# Question
Title: Using Drush on shared hosting without `curl` and `wget`
I have a Drupal 7 site installed on shared hosting.

And installed Drush:8.1.17 with composer and cgr all is working well except `drush up` because hosting provider does not support `curl` or `wget` on shared accounts.

When I ask them they said that there is no plans for giving permissions on shared account users to `curl` or `wget` when I run:

```
$ drush up
$ wget nor curl executable found.

$ curl
-jailshell: /usr/bin/curl: Permission denied

```

Is there another way of using `drush up`?

# Answer
> 1 votes
Your use case is not supported. You'll have to update locally and then push to your provider.

---
Tags: 7, drush, ssh
---


title: How to group by one field

text:
# Question
Title: How to group by one field
I have a view which shows the users subscribed to the website. Some users have multiple roles, therefore, on the results, there are some duplicates.

What I want to do is to remove these duplicates, so I've tried to enable the *Aggregation* in the view settings. This action reduced the repeated results, but it haven't erased them.
By looking at the query the `GROUP BY` is done for every field, but I want to enable for just one field, more specifically like this: `GROUP BY users_name`.

I've tried to achieve it by making a simple module with this function:

```
function alter_users_query_views_query_alter(&$view, &$query) {
    if ($view->name == 'all_users') {
        $query->add_groupby('users_name');
    }
}

```

Which adds the additional field in the `GROUP BY`, but it doesn't remove the others.
How can I achieve it? More specifically, how can I unset the other fields and group by just one?

# Answer
> 0 votes
I was able to find a solution by following this example. Here is the code in my case:

```
function alter_users_query_query_alter($query) {
    if (isset($query->alterMetaData)) {
        if (isset($query->alterMetaData['view'])) {
            if($query->alterMetaData['view']->name == 'all_users') {
                $fields =& $query->getGroupBy();

                unset($fields['field-you-want-to-remove']);
                $query->groupBy('users_name');
            }
        }
    }
}

```

---
Tags: views, database
---


# Question
Title: How to inculde 3d parrty libraries into your module?
I am using the 3d party php library, and I do not know how to connect. The file structure of my project looks like following:

```
-my_project
--src
---Plugin
----Action
-----MyAction.php
---libs
----mylibs
-----src
------ClassWhichINeed.php

--my_project.info.yml

```

So I need to connect ClassWhichINeed.php to MyAction.php. In ClassWhichINeed.php I specified namespace as Drupal\my\_project\mylibs;

And in MyAction.php i use Drupal\my\_project\mylibs;

But when I create $object = new ClassWhichINeed;

I get an error "Undefiened class"

# Answer
suggestion:

in MyAction.php add:

```
require_once DRUPAL_ROOT . '/modules/my_project/src/libs/mylibs/src/ClassWhichINeed.php';

```
> -1 votes

---
Tags: 8
---


# Question
Title: How to redirect programmatically inside a module to an external url?
I am trying to redirect to a page after I unset a session. I read this article but I am pretty new to Drupal module building.

Here this amazing guy says to do the comming thing:

> If you know that the destination is an external URL then you are encouraged to use TrustedRedirectResponse instead:
>
> ```
> return new RedirectResponse(\Drupal::url('<front>', [], ['absolute' => TRUE]));
>   return new TrustedRedirectResponse('http://www.bbc.com/');
>
> ```

I don't understand how I should use this code and where to put it...

Any help would be great This is my controller file content.

```
<?php

namespace Drupal\achva_sso\Controller;

use Drupal\Core\Controller\ControllerBase;

class SsoController extends ControllerBase{
    public function ssoLogout(){
        unset($_SESSION['name']);

        if(isset($_SESSION['name'])){
            $status = $_SESSION['name'] .' is logged in';
        }else{
            $status = 'is logged out';
        }
        return[
            '#type' => 'markup',
            '#markup' => '<p>' . $status . '</p>' ,
        ];

    }
}

```

# Answer
> 3 votes
Well if you want to redirect to an external page this can be your code:

```
<?php

namespace Drupal\achva_sso\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

class SsoController extends ControllerBase{
    public function ssoLogout(){
        unset($_SESSION['name']);

        // Redirect.
        return new TrustedRedirectResponse('http://www.bbc.com/');

    }
}

```

In this case, the redirection will happen when your ssoLogout() method will be called.

---
Tags: 8, routes
---


# Question
Title: MODULENAME_page_attachment_alter() Undefined
I have a custom module named `rsm_library`. I would like to use `hook_page_attachment_alter()` in `rsm_library.module` and called the hook as follows:

```
rsm_library_page_attachment_alter($attachments);

```

I then issued `$ drush cr` to clear the caches.

This resulted in:

> AH01071: Got error 'PHP message: Error: Call to undefined function rsm\_library\_page\_attachments\_alter().

# Answer
> 1 votes
do it like this :

```
/**
 * Implements hook_page_attachments_alter().
 */
function rsm_library_page_attachments_alter(array &$attachments) {
  // do stuff
}

```

# Answer
> 1 votes
First, there's a typo. It's not attachment, it's attachment**s**.

Next, you can't simply call a function without defining it.

In Drupal hooks are used to modify existing code when it's being processed.

See `hook_page_attachments_alter` for an example of what you are supposed to do.

Using hooks, you simply define a new function prefixed with your module's machine name, put your code/alterations in there, and in the end it's automatically being *hooked up* for execution. No need to call it again.

> ```
> function hook_page_attachments_alter(array &$attachments) {
>
>   // Conditionally remove an asset.
>   if (in_array('core/jquery', $attachments['#attached']['library'])) {
>     $index = array_search('core/jquery', $attachments['#attached']['library']);
>     unset($attachments['#attached']['library'][$index]);
>   }
> }
>
> ```

---
Tags: 8, hooks
---


# Question
Title: How can I add an array or a new value to the query condition?
I need to add a new type of content in my query condition, but I don't know how to do it.

This is the code I am using.

```
$query_result = $query->getQuery()
  ->condition('type','series'+ ......others items)
  ->execute();

```

# Answer
> 0 votes
try:

$query\_result = $query-\>getQuery() $query-\>condition('type', \['type1', 'type2'\], 'IN') -\>execute();

---
Tags: database
---


# Question
Title: Drush upwd Changes Database Hash but Login Fails
I have a weird one. I have a site that was abandoned for a while and we need to get access to it again. So I tried to use drush to reset the admin password, but it's not working.

I'm using Drush 8.1.17 on what I presume is a Drupal 7.57 site (because of the CHANGELOG.txt file in the docroot).

Syntax for my command is like: `php drush.phar upwd fakeadmin --password="examplepassword123"`

I get a message `Changed password for fakeadmin success` and because I'm literally looking at the users table in my database I can see the hash change in the password field. Yet, when I copy the text 'examplepassword123' (without single quotes) into my login page, it does nothing.

Am I just messing up the Drush 8 syntax? (I'm already more used to Drush 9). What would cause it to not work?

EDIT: Drush just uses whatever DB credentials are in the standard sites/default/settings.php file correct? So if that's correct, then I should be working with the right database. No?

EDIT 2:

1) I tried it without the double quote just in case and that didn't work either.

2) I also tried running the script `/scripts/password-hash.sh "examplepassword123"` and copied the resulting hash into my database, and nothing happened. (found reading through this: https://www.drupal.org/node/992400)

3) I would almost say I'm using the wrong database at this point except that with another drush command I was able to see it add a new user\_role row in an attempt to make another user we have access to an admin. Ideas?

EDIT: Well this was disappointing and weird. Drush was somehow changing the hash but not the password? An employee of ghosts past somehow had it saved on their hard drive, and gave me the password, and it was the same as before. I'm not going to question it....

# Answer
> 0 votes
Check to see if your cookies are being set correctly. It's possible that your login is succeeding, but if the session cookie is not set, then you will be immediately logged out again (or, more to the point, the browser won't get the message about you being logged in and will continue to present an anonymous user to your site).

Check your settings.php file and see if you have any configuration options related to the cookie domain that are not correct.

---
Tags: 7, users, drush
---