title: Drush to remote server returns nothing

text:
# Question
Title: Drush to remote server returns nothing
I am getting permission denied publickey password when I type

drush @prod (alias for my production site on shared bluehost.com) status

Both drush @dev (alias for my local site running on Win 7) status & drush status work fine.

**Here is the output from drush @dev status executed on my Win 7 machine.**

```
C:\Windows\system32>drush @dev status
Drupal version : 7.43
Site URI : http://bluehostclone
Database driver : mysql
Database hostname : 127.0.0.1
Database port : 33067
Database username : drupaluser
Database name : bluehostclone
Drupal bootstrap : Successful
Drupal user :
Default theme : outreach
Administration theme : seven
PHP executable : php.exe
PHP configuration : "C:\Program Files (x86)\DevDesktop\php5_5\php.ini"
PHP OS : WINNT
Drush script : C:\Program Files(x86)\DevDesktop\drush\vendor\drush\drush\drush.php
Drush version : 8.0.0
Drush temp directory : C:\Users\Sam\AppData\Local\Temp
Drush configuration : "C:\Program Files(x86)\DevDesktop\drush\vendor\drush\drush\drushrc.php"
Drush alias files : "C:\Program Files (x86)\DevDesktop\drush\vendor\drush\drush\includes/../aliases.drushrc.php" c:\users\sam\sites\devdesktop\bluehostclone\sites\all\drush/myaliases.alias.drushrc.php C:\Users\Sam\Sites\devdesktop\bluehostclone/sites/all/drush/myaliases.alias.drushrc.php
Install profile : openoutreach
Drupal root : C:\Users\Sam\Sites\devdesktop\bluehostclone
Site path : sites/default
File directory path : sites/default/files
Private file : backups
directory path
Temporary file : /tmp
directory path</code>

```

Output from the same command executed on production server\**

```
columck5@columbiablooms.org [~]# drush status --full
 PHP executable         :  /ramdisk/php/54/bin/php54-cli
 PHP configuration      :  /home1/columck5/public_html/drush/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home1/columck5/.composer/vendor/drush/drush/drush.p
                           hp
 Drush version          :  7.1.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Other paths            :</code>

```

**aliases.drushrc.php (on Win 7 computer) Password has been blotted out.**

```
$aliases["dev"] = array (
  'root' => 'C:\\Users\\Sam\\Sites\\devdesktop\\bluehostclone',
  'uri' => 'http://bluehostclone',
  'path-aliases' =>
  array (
    '%drush' => 'C:\\Program Files (x86)\\DevDesktop\\drush\\vendor\\drush\\drush',
    '%site' => 'sites/bluehostclone/',
  ),
  'databases' =>
  array (
    'default' =>
    array (
      'default' =>
      array (
        'driver' => 'mysql',
        'database' => 'bluehostclone',
        'username' => 'drupaluser',
        'password' => '',
        'host' => '127.0.0.1',
        'port' => 33067,
      ),
    ),
  ),
);

$aliases["prod"] = array (
  'remote-host' => 'box1278.bluehost.com',
  'root' => '/home1/columck5',
  'uri' => 'http://columbiablooms.org',
  'path-aliases' =>
  array (
    '%drush' => './drush',
    '%site' => '/public_html',
  ),
  'databases' =>
  array (
    'default' =>
    array (
      'default' =>
      array (
        'driver' => 'mysql',
        'database' => 'columck5_dr9626',
        'username' => 'columck5',
        'password' => '***',
        'host' => 'localhost',
        'port' => '',
      ),

```

**Output from drush @prod status -v -full --debug\`**

```
Drush preflight prepare loaded autoloader at C:\Program Files        [preflight]

(x86)\DevDesktop\drush\vendor\autoload.php [0.13 sec, 1.71 MB]
Starting Drush preflight. [0.24 sec, 1.71 MB]                        [preflight]

Loading drushrc "C:\Program Files                                    [bootstrap]

(x86)\DevDesktop\drush\vendor\drush\drush\drushrc.php" into "drush"
scope. [0.24 sec, 1.71 MB]
Cache HIT cid: 8.0.0-commandfiles-0-8cbf3598903cd4c09cf48f8bb47cae28     [debug]

[0.36 sec, 1.76 MB]
Scanning into C:\ProgramData/Drush/etc/drush for                     [sitealias]

/.*aliases\.drush(8|)rc\.php$/ [0.44 sec, 3.45 MB]
Scanning into C:\ProgramData/Drush/etc/drush for                     [sitealias]

/prod\.alias\.drush(8|)rc\.php$/ [0.44 sec, 3.45 MB]
Scanning into C:\Program Files                                       [sitealias]

(x86)\DevDesktop\drush\vendor\drush\drush\includes/.. for
/.*aliases\.drush(8|)rc\.php$/ [0.44 sec, 3.45 MB]
Scanning into C:\Program Files                                       [sitealias]

(x86)\DevDesktop\drush\vendor\drush\drush\includes/.. for
/prod\.alias\.drush(8|)rc\.php$/ [0.57 sec, 3.45 MB]
Scanning into C:\Users\Sam\Sites\devdesktop\columbiablooms-dev/.drush[sitealias]

for /.*aliases\.drush(8|)rc\.php$/ [0.71 sec, 3.45 MB]
Scanning into C:\Users\Sam\Sites\devdesktop\columbiablooms-dev/.drush[sitealias]

for /prod\.alias\.drush(8|)rc\.php$/ [0.71 sec, 3.45 MB]
Scanning into                                                        [sitealias]

C:\Users\Sam\Sites\devdesktop\columbiablooms-dev/.acquia/DevDesktop/Drush/Aliase
s
for /.*aliases\.drush(8|)rc\.php$/ [0.71 sec, 3.45 MB]
Scanning into                                                        [sitealias]

C:\Users\Sam\Sites\devdesktop\columbiablooms-dev/.acquia/DevDesktop/Drush/Aliase
s
for /prod\.alias\.drush(8|)rc\.php$/ [0.71 sec, 3.45 MB]
Loaded alias @prod from file C:\Program Files                           [notice]

(x86)\DevDesktop\drush\vendor\drush\drush\includes/../aliases.drushrc.php
[1.06 sec, 5.2 MB]
Begin redispatch via drush_invoke_process(). [1.18 sec, 5.21 MB]        [notice]

Backend invoke: ssh -o PasswordAuthentication=no box1278.bluehost.com  [command]

"drush  --debug --uri=http://columbiablooms.org --verbose --user
--root=/home1/columck5  core-status   --f 2>&1" 2>&1 [1.18 sec, 5.22
MB]
Calling proc_open(ssh -o PasswordAuthentication=no box1278.bluehost.com "drush
--debug --uri=http://columbiablooms.org --verbose --user --root=/home1/columck5
 core-status   --f 2>&1" 2>&1);
Permission denied (publickey,password).
End redispatch via drush_invoke_process(). [1.95 sec, 5.21 MB]          [notice]
`
    ),
  ),
);

```

I'm guessing the answer to my problem lies somewhere above, but despite lots of Google searches I'm not able to figure out what this is telling me. I am a newbie.

Update: I made the following changes.

```
    a. Changed root to '/home1/columck5/public_html'
    b. Changed %drush to '/home1/columck5/.composer/vendor/drush/drush'
    c. Changed %site to  'sites//'
    d. ****** All above changes on Win 7. **************
    e. Added
    PATH=$PATH:/home1/columck5/.composer/vendor/bin
    to bashrc on remote

```

Drush @prod status returns nothing after these changes.

# Answer
> 1 votes
This is a SSH question really. You need to enable publickey login to the server. To test (without involving Drush) run

```
ssh -o PasswordAuthentication=no box1278.bluehost.com date

```

When that commands returns the date, and not an error, you can return to Drush ;-)

Your ISP probably has some info about this but basically you have to generate a SSH private-public key-pair and add the public key to the `.ssh/authorized_keys` on the server. Just Google it!

# Answer
> 1 votes
First, as noted above, you will need to check that your public key is added to the Web server. Usually, it's done locally (provided you already have a public key), by running `ssh-copy-id -i ~/.ssh/id_rsa.pub [your_username@remote_host]`. Once you close your CLI session and reopen, if it works, you should be able to log in without a password when entering `ssh your_username@remote_host`, since it's referencing your local credentials.

Then, add this to your production site alias:

`ssh-options' => '-i ~/.ssh/id_rsa',
ssh-options' => '-o PasswordAuthentication=yes',`

Drush will now be able to connect using your stored credentials.

One other thing to check—what shell you are running locally? In looking at your output above, the debug script has the `2>&1` string in it. Because of this, it appears your Web host is running bash as its shell, but I'm not sure about your local. Presumably, if it were bash/bourne, your commands would work fine. If csh/tcsh, there is the issue that Drush only supports bash or Bourne shells. The `2>&1` is bourne/bash syntax to redirect stderr to stdout, but it’s not understood by csh/tcsh and the command fails.

You may want to run `finger [your_username]` in your local environment, which will show your shell. If not bash, you may look if you can change it to that, after which you should be able to run remote drush commands locally.

---
Tags: drush, ssh
---


# Question
Title: How do I fix the missing top 1/2 inch of the content box?
I made a number of formatting changes to several basic pages using a Bootstrap-based premium theme. The changes accomplished what I wanted but I subsequently noticed that, when I visited the site as an anonymous user, the top roughly 1/2 inch of the content part of each page is not displayed. It's as if the top of the page is hidden behind the horizontal menu bar at the top of the page rather than appearing correctly a 1/2 inch down.

I backed out all the changes I could remember making but it's still broken. It displays correctly when logged in as either admin or an authenticated user. I don't know how to even begin troubleshooting this issue. Can anyone point me in the right direction?

# Answer
> 0 votes
The body class in the custom-media.css is defining margin-top: 90px for the fixed header, you will need to increase this to match the size of your header.

You may need to include media queries to account for reactive menu changes.

It probably works when you are logged in because either the admin toolbar is modifying the margin or there is a rule specifically for being logged in that assumes the toolbar but you don't have it enabled.

---
Tags: theming
---


# Question
Title: I want to place my business page linkedin feed onto our Drupal website. Is it possible?
This question is most likely more about LinkedIn. I can't find answers to this question anywhere. It is as if no one ever asked it.

I have follow links to the linkedin business page. I have share links to the visiting user's linkedin feed.

# Answer
> 0 votes
Take a look at these links:

https://www.drupal.org/docs/8/modules/get-linkedin-posts

https://www.drupal.org/docs/8/modules/get-linkedin-posts/how-to-setup-get-linkedin-posts-module

I haven't played with Linkedin or with this module, but that's what you need if I understand right.

It's up to you if you install it or not.

---
Tags: 8, social-network
---


# Question
Title: Trying to inject JS file, getting theme errors...why?
So, my theme.libraries.yml file shows:

```
global-styling:
  css:
    theme:
      css/style.css: {}
      css/custom.css: {}
  js:
    js/myjavascript.js: {}

```

In mytheme.theme, hook\_preprocess\_node() I have added:

```
$variables['#attached']['library'][] = 'myjavascript.js';

```

Drupal is throwing this error message:

```
User warning: The following theme is missing from the file system: myjavascript.js in drupal_get_filename() (line 250 of core/includes/bootstrap.inc).

```

I cannot see where I'm going wrong. The javascript is definitely being injected, since it all works. Why am I getting this error?

thanks

# Answer
> 0 votes
To sum it up: You may just omit your manual inclusion/attachment of the JavaScript file in hook\_preprocess\_node().

Long version:

As @MrD already stated, in Drupal 8 you attach libraries, not files. So with your statement, your Drupal is looking for a library definition `myjavascript.js`. Which would mean a libraries file like:

```
myjavascript.js:
  js:
    js/myjavascript.js: {}

```

As you already added the JavaScript file to your `global-styling` library, and this library seems to being attached within your theme already, the JavaScript automagically will be included when you use the theme.

For creating an own library that can be attached conditionally, please refer to the answer referenced by MrD.

---
Tags: 8, javascript
---


# Question
Title: How to reuse object between Drupal Behaviors?
We have a JS file (basic-page.js) that has the following Drupal Behavior. In this, we created what we believe is considered a Drupal object (need help with correct term) that contains a function that can be called. In the latest request, we need the ability to reuse the same code from the Drupal Behavior in another Drupal Behavior.

How could we reuse the code? Currently the article.js is not able to use the code from basic-page.js, no errors or warnings are given.

basic-page.js (where Drupal object resides)

```
(function($) {
  'use strict';
  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

  Drupal.behaviors.customName = {
    attach: function(context, setting).once('customName').each(function() {
      /* behavior runs here */
      var func1 = Drupal.customObj;
      var results = func1.function1($('body'));
      //process results
    });
  };
})(jQuery);

```

article.js (where we want to reuse Drupal.customObj.function1)

```
(function($) {
  'use strict';

  Drupal.behaviors.articleResults = {
    attach: function(context, setting).once('articleResults').each(function() {
      /* behavior runs here */
      var customObj = Drupal.customObj;
      var results = customObj.function1($('body'));
      //process results
    });
  };
})(jQuery);

```

# Answer
> 7 votes
I'll focus on the inclusion first, then describe what Clive was referring to, while mentioning that your JS is not valid:

For your use case you should add a common library to your module/theme that extends the Drupal object. (You don't even have to extend the Drupal object, but can create an own one, if you prefer.)

Then use dependencies to make sure the object is available in your basic page JS, as well as in your article JS.

**Example**

*In your `*.libraries.yml`*

```
mymodule/common:
  js:
    js/mymodule-common.js: {}
  dependencies:
    - core/drupal
    - core/jquery

mymodule/page:
  js:
    js/mymodule-page.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

mymodule/article:
  js:
    js/mymodule-article.js: {}
  dependencies:
    - mymodule/common
    - core/drupal
    - core/jquery
    - core/jquery.once

```

You can then split your JS to the three separate files containing your code. The `dependencies` section makes sure the scripts your library depends on are loaded before.

Now to the scripts itself:

*`mymodule-common.js`*

```
(function($) {
  'use strict';

  Drupal.customObj = {
    'function1': function(element) {
      /* perform some logic here */
    },
    'function2': function(var) {
      /* perform some other logic here */
    }
  };

})(jQuery);

```

*`mymodule-page.js`*

```
(function($) {
  'use strict';

  Drupal.behaviors.customName = {
    attach: function(context, setting) {
      $('body').once('customName').each(function() {
        var func1 = Drupal.customObj;
        var results = func1.function1($('body'));
        //process results
      });
    }
  };

})(jQuery);

```

And similar in your `mymodule-article.js`.

And here the promised feedback to the comment of Clive: Compare the attach property in the last example. It expects a callable that will be executed every time a page/ajax load finished. Within its body you can then do your magic.

**References:**

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

---
Tags: 8, javascript
---


title: How to display a block in twig (D8)

text:
# Question
Title: How to display a block in twig (D8)
I read the other similar questions, but it didn't work.

I created a block in a region and I want to display that same block on my custom page (inside the twig).

I'm using this code to load the block:

```
$block = \Drupal::entityTypeManager()->getStorage('block')->load('block_id');
$block_content =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

```

and I'm trying to build it like this:

```
$build['page'] = array(
      '#type' => 'inline_template',
      '#template' => $template,
      '#form' => $block_content,
);
return $build;

```

My twig file is like this:

```
<section>
  <tbody>
    <div>{{ form }}</div>
  </tbody>
</section>

```

But nothing is displayed... What am I doing wrong?

Thanks in advance.

# Answer
> 0 votes
To make the `form` variable available in the Twig template you need to supply a context like follows.

```
$build['page'] = [
  '#type' => 'inline_template',
  '#template' => $template,
  '#context' => ['form' => $block_content],
];

```

Generally, I would recommend using custom `#theme` hook instead of an inline template.

Another way to render block within a template is using Twig Tweak module.

```
{{ drupal_entity('block', 'block_id') }}

```

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


# Question
Title: Where are the field variables in a block template?
How can I access the variables of the fields in a block template?

# Answer
> 2 votes
They're in the `content` variable, e.g.

```
<div{{ attributes }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content.field_foo }}
    {{ content|without('field_bar') }}
    {{ content.field_bar }}
  {% endblock %}
</div>

```

For reference, these are the default core variables you have available (from the core template:

> * plugin\_id: The ID of the block implementation.
> * label: The configured label of the block if visible.
> * configuration: A list of the block's configuration values.
> * label: The configured label for the block.
> * label\_display: The display settings for the label.
> * provider: The module or other provider that provided this block plugin.
> * Block plugin specific settings will also be stored here.
> * content: The content of this block.
> * attributes: array of HTML attributes populated by modules, intended to be added to the main container tag of this template.
> * id: A valid HTML ID and guaranteed unique.
> * title\_attributes: Same as attributes, except applied to the main title tag that appears in the template.
> * title\_prefix: Additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.
> * title\_suffix: Additional output populated by modules, intended to be displayed after the main title tag that appears in the template.

---
Tags: theming, blocks
---


# Question
Title: Throw entity field value from submission to route path?
I have created two entities and I want to connect them by route. my edit route is:

```
entity.entity_two.edit_form:

  path:
'/property/configuration/communication/{entity_one}/variant/{entity_two}/edit'

  defaults:

    _entity_form: communication_variant.edit
    _title: 'Add/Edit Email Variant'
    entity_one: '%id'
  options:

    parameters:
      entity_one:
        type: 'entity_one'
      communication_variant:
        type: entity:node

```

but I get an error on edit path as it says: entity one is empty but as i check entity one has value in the table. so my idea is that on submission of entity two form, I get entity\_one id by entity reference and set in my route. so I want to implement that idea any help?

# Answer
I have found the way to pass the value in edit route without using route subscriber or any pram converter. I will pass the value to Entity list builder default operations function. From there I can change the URL of edit and delete.

```
public function getDefaultOperations(EntityInterface $entity) {
    /* @var $entity \Drupal\my_module\Entity\entity_two */
    $operations = parent::getDefaultOperations($entity);
    $cid = $entity->cid->getString();
    $edit= \Drupal\Core\Url::fromRoute('entity.entity_two.edit_form',array('entity_one' => $cid , 'entity_two' => $entity->id()));
    $operations['edit'] = array(
        'title' => $this->t('edit'),
        'weight' => 10,
        'url' => $edit,
    );
    $delete= \Drupal\Core\Url::fromRoute('entity.entity_two.delete_form',array('entity_one' => $cid , 'entity_two' => $entity->id()));
    $operations['delete'] = array(
        'title' => $this->t('delete'),
        'weight' => 11,
        'url' => $delete,
    );

    return $operations;

}

```
> 0 votes

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


# Question
Title: How to condition SelectQuery by field value?
I have a view that receives taxonomy terms. Via pre execute hook, I want to only get terms the terms that have the current user referenced (in their field). I know it works via views itself, but there is more to it. I have to do it programmatically.

```
function tk_access_views_pre_execute(&$view) {
  if ('myview' == $view->name) {
    global $user;

    if (in_array('extern', $user->roles)) {
      $query = $view->build_info['query'];
      // debug($query->conditions());
      // $query->condition('field_referenced_user', $user->uid);
      $query->join(
        'field_data_field_referenced_user',
        'referenced_user'
        // 'field_data_field_referenced_user.field_referenced_user_target_id = '
      );
      $query->condition('referenced_user.field_referenced_user_target_id', $user->uid);
      $view->build_info['query'] = $query;
    }
    // debug(array_keys($view->build_info));
  }
}

```

But it doesnt work, unfortunately. What am I doing wrong?

# Edit

If I add a contextual filter inside the view, I can debug the final sql statement:

```
SELECT
  taxonomy_term_data.name AS taxonomy_term_data_name,
  taxonomy_term_data.vid AS taxonomy_term_data_vid,
  taxonomy_term_data.tid AS tid,
  taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name,
  'taxonomy_term' AS field_data_field_customer_taxonomy_term_entity_type,
  'myview:entityreference_1' AS view_name

FROM
  {taxonomy_term_data} taxonomy_term_data
LEFT JOIN
  {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
INNER JOIN
  {field_data_field_projectstatus} field_data_field_projectstatus ON taxonomy_term_data.tid = field_data_field_projectstatus.entity_id
    AND (field_data_field_projectstatus.entity_type = :views_join_condition_0
    AND field_data_field_projectstatus.deleted = :views_join_condition_1)
LEFT JOIN
  {field_data_field_referenced_user} field_data_field_referenced_user ON taxonomy_term_data.tid = field_data_field_referenced_user.entity_id
  AND (field_data_field_referenced_user.entity_type = :views_join_condition_2
  AND field_data_field_referenced_user.deleted = :views_join_condition_3)

WHERE
  (((field_data_field_referenced_user.field_referenced_user_target_id = :field_data_field_referenced_user_field_referenced_user_target_id )
   )
  AND(( (taxonomy_vocabulary.machine_name IN (:db_condition_placeholder_4)) AND (field_data_field_projectstatus.field_projectstatus_value IN (:db_condition_placeholder_5, :db_condition_placeholder_6)) )))

ORDER BY taxonomy_term_data_name ASC

```

I still dont know how to get the additional conditions via SelectQuery object.

# Answer
Yay, I dit it:

```
$query = $view->build_info['query'];
$query->leftJoin(
  'field_data_field_referenced_user',
  'field_referenced_user',
  'taxonomy_term_data.tid = field_referenced_user.entity_id'
);
$query->where(
  'field_referenced_user.field_referenced_user_target_id = :uid',
  array(':uid' => $user->uid)
);

$view->build_info['query'] = $query;

```
> 0 votes

---
Tags: 7, views, database
---


# Question
Title: No calendar showing on Rooms bookable unit - when clicking manage availability
I am not sure what I have missed. I first installed BAT module,but later decided to instead use Rooms module. I am under the impression that Rooms will make use BAT FullCalendar , I could be wrong. Unless if there are some configurations needed. Or must I uninstall BAT completely and only use Rooms module with a normal fullcaleder module? I have checked permissions but could not see anything funny. See attached. Thanking you in advance.

# Answer
Rooms and BAT are separate modules, you should fully un-install BAT and then follow the Rooms installation instructions. Rooms depends on the fullcalendar library, but not the full calendar module.

> Within the Rooms module there is a rooms.make file which will download the library if using Drush or you can visit https://github.com/arshaw/fullcalendar/releases/download/v2.6.1/fullcalendar-2.6.1.zip to download it. The FullCalendar library should be placed in sites/all/libraries so that you end up with the file located here: sites/all/libraries/fullcalendar/fullcalendar.js

(quoted from http://docs.roomify.us/rooms/installation.html)
> 0 votes

---
Tags: 7, javascript, bookings
---


# Question
Title: Using twig inside theme folder rather than twig from modules
I installed a paragraph module and it uses twig from inside /modules/paragraphs/templates/ but I would like to override it inside my /theme/theme\_name/ folder.

How can I do this? Thanks.

Edit:

```
<!-- FILE NAME SUGGESTIONS:
* paragraph--steps--default.html.twig
* paragraph--steps.html.twig
* paragraph--default.html.twig
x paragraph.html.twig
-->
<!-- BEGIN OUTPUT from 'modules/paragraphs/templates/paragraph.html.twig' -->

```

Twig debug looks for the file in modules/paragraphs/templates and I would need it to look in mytheme/templates/. :/

# Answer
> 1 votes
Simply copy the mentioned module template over to your theme's template folder. That's all.

# Answer
> 1 votes
Create templates folder inside your theme and enable Twig debugging, check here for how to enable twig debugging.

Once twig debugging enable look for theme suggestions and name the templates accordingly.

---
Tags: 8, theming
---


# Question
Title: #default_value for select form elements does not work
```
<?php
namespace Drupal\dishes_dropdown\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Component\Utility\UrlHelper;

/**
 * Desarrollo de un formulario en drupal 8
 *
 */
class DishesDropdownForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'dishes_dropdown_form';
    }

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

        $maxlength = 250;

        $tax_terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('dish_type', $parent=0, $max_depth=NULL, $load_entities=FALSE);
        $taxs = array();
        foreach ($tax_terms as $tax_term) {
            $taxs[$tax_term->tid] = $tax_term->name;
        }

        $form['dish_dropdown'] = array(
            '#type' => 'select',
            '#options' => $taxs,
            '#chosen' => true,
            '#multiple' => false,
            '#maxlength' => $maxlength,
            '#default_value' => $form_state->hasValue('dish_dropdown') ? $form_state->getValue('dish_dropdown') : '' ,

        $form['submit'] = [
            '#type'  => 'submit',
            '#value' => $this->t('Ir al tipo de plato'),
            '#weight' => 50,
        ];
        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Display result.
        $id = reset($form_state-> getValues('dish_dropdown'));
        $aliasManager = \Drupal::service('path.alias_manager');
        // The second argument to getAliasByPath is a language code such as "en" or LanguageInterface::DEFAULT_LANGUAGE.
        $alias = $aliasManager->getAliasByPath('/taxonomy/term/' . $id);

        $url = new TrustedRedirectResponse($alias);
        if (isset($url)) {
            $form_state-> setResponse($url);
        }

        return;

    }
}

```

---

I do not load the "default\_value" in select. I have tried a thousand ways in the "build" but there is no way. I want a blank default value but without forcing it load it. It's like if you read the "default\_value".

# Answer
> 1 votes
> The **#default\_value** for a select element should be an integer value matching an array **key** in the **#options** array.

In your case, lets say

```
$taxs = [5 => 'blue dish', 9 => 'red dish', 15 => 'green dish'];

```

Then an option for the value for \*#default\_value will be one of 5,9 or 15.

In your case the function *$form\_state-\>hasValue('dish\_dropdown')* will return one of "blue dish", "red dish" or "green dish" which is **not** an array key in your $taxs array.

So what do you do?

1. Either select one of your dish types as the default **OR**
2. Add a default value *\- None -*

For example:

```
$taxs[0] = '-- None --';
$reverseTaxs = array_flip($taxs);
$form['dish_dropdown'] = array(
        '#type' => 'select',
        '#options' => $taxs,
        '#chosen' => true,
        '#multiple' => false,
        '#maxlength' => $maxlength,
        '#default_value' => $form_state->hasValue('dish_dropdown') ? $reverseTaxs[$form_state->getValue('dish_dropdown')] : 0 ,

    $form['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Ir al tipo de plato'),
        '#weight' => 50,
    ];
    return $form;

```

---
Tags: forms
---


# Question
Title: Out of memory error in composer when requiring drupal/bootstrap
I currently set up a Drupal 8 website using Composer like described here. Drupal is already running. Now I want to add Bootstrap theme by calling

```
composer require drupal/bootstrap

```

But I get

> Using version ^7.3 for drupal/bootstrap ./composer.json has been updated DrupalProject\composer\ScriptHandler::checkComposerVersion Loading composer repositories with package information Updating dependencies (including require-dev)
>
> mmap() failed: \[12\] Cannot allocate memory
>
> mmap() failed: \[12\] Cannot allocate memory PHP Fatal error: Out of memory (allocated 515907584) (tried to allocate 20480 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/Pool.php on line 221
>
> Fatal error: Out of memory (allocated 515907584) (tried to allocate 20480 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/Pool.php on line 221

Im using Composer version 1.2.1 2016-09-12 11:27:19

# Answer
> 3 votes
This is related to your `php.ini` file's `memory_limit` entry which defaults to `128M`. **You need access to your server's `php` configuration file**. If you do here is the step by step for making that change on an Ubuntu server with **PHP 7** and **PHP CLI** extension.

1. Open the PHP CLI configuration file located at `/etc/php/7.0/cli`; e.g. I use vim as follows `sudo vim /etc/php/7.0/cli/php.ini`
2. Search for the line containing `memory_limit` by pressing the `/` (forward slash) key, type the phrase `memory_limit` and press enter.
3. Once on that line go to vim's insert mode by pressing 'ESC' followed by 'i'.
4. Change the value for the `memory_limit` to something higher, e.g. `memory_limit = 1024M` since you already have `512M` for the limit.
5. Save and exit the configuration file by pressing 'ESC' type in 'wq' and then press 'enter'.

If you don't see any changes it could be that you have an **error** in you `php.ini` configuration file. You are always welcome to comment on the answers to get more help.

# Answer
> 0 votes
The best way to fix this will be to add a swap space to the instance. Please note, this error can appear even if you set memory\_limit= -1, as eventually, the system will run out of memory if the maximum memory is limited.

Please note, the commands required to execute varies with the OS variant. One example is below.

Run the following commands:

> sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=2048
>
> sudo /sbin/mkswap /var/swap.1
>
> sudo chmod 600 /var/swap.1
>
> sudo /sbin/swapon /var/swap.1

To survive a restart, append the following entry to /etc/fstab

```
/var/swap.1   swap    swap    defaults        0   0

```

---
Tags: 8, composer
---


# Question
Title: Do not import configurations if already exists
I have built a custom module and there are two configuration files in `config/install` directory of my module. When the module is installed the configurations are installed correctly. When I uninstall the module and try to reinstall it, I get the error that that the \`

> fields already exist in the database

These fields are defined in the configuration files and I want that they should be installed only if they not exist.

\`

# Answer
> 4 votes
Move them to config/optional instead.

In that case, they will only be installed if they don't exist yet and if all their dependencies are met.

---
Tags: 8, configuration
---


# Question
Title: Bundle field validation with Feature in Drupal 8
How can I have the field validation settings (via the field validation module) bundle with the content type using Features module?

eg: I have a content type Post and a field validation that says post's title must match a certain regex. I need to bundle this logic up with Features.

Thank you!

# Answer
It looks like the field validation module has it's own configuration entity type. This means that in the feature editor there should be a section labeled something like Field Validation Rule Sets.

Select the appropriate configuration under this section to include it with your content type feature.

I assume that you know that to include the content definition you need a minimum of the content type, the individual fields (storage and field settings), the entity form display, and entity view display.

There may be other specialty items like language settings here. Enter the machine name of the content type in the feature editor search field (after checking include conflicts) to find them. NOTE: Red indicates they are part of another feature and you may not need to include them.
> 0 votes

---
Tags: 8, features
---


# Question
Title: Convert a regular autocomplete field into an autocomplete deluxe field?
I am using the following code.

```
   $form['usershare'] = array(
     '#title' => t('Share Collection Internally - Example: Alice, Bob, Pat'),
     '#type' => 'textfield',
     '#default_value' => empty($flag->usershare) ? '' : $flag->usershare,
     '#autocomplete_path' => 'user/autocomplete/fl',
     '#multiple' => TRUE,
   );

```

I installed the Autocomplete Deluxe module.

How do I convert the code I am using to have a form field that uses autocomplete deluxe?

I tried changing the form field type to *autocomplete\_deluxe*, but that didn't work as only a blank input box shows up.

# Answer
As per the README.txt file, something like this should work

> ```
>    $form['field_term_ref_tid'] = array(
>      '#type' => 'autocomplete_deluxe',
>      '#autocomplete_deluxe_path' => url(
>        'autocomplete_deluxe/taxonomy/field_term_ref',
>        array('absolute' => TRUE)
>      ),
>      '#multiple' => TRUE,
>      '#autocomplete_min_length' => 0,
>      '#autocomplete_multiple_delimiter' => ',',
>      '#not_found_message' => "The term '@term' will be added.",
>    );
>
> ```
> 2 votes

---
Tags: 7, forms
---


title: Get fid from file path

text:
# Question
Title: Get fid from file path
I've to create a custom function to display images because I've to add values from custom fields.

I've added a function to template php, like this:

```
function mytheme_image($variables) {
}

```

The problem is that in $variables I haven't the fid of the file, but only the path. I have to load the file to get values from field, how should I do?

I'm looking for functions to get fid from path but I haven't found something..

# Answer
> 5 votes
@pvorb, you can also use EntityFieldQuery. See the first comment on https://api.drupal.org/api/drupal/includes%21file.inc/function/file\_load\_multiple/7 for an example. Something along the lines of:

```
$filename = 'myfirstpony.png';
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', $filename)
  ->execute();
// if you are guaranteed there is exactly one result, then:
$file_object = reset($result['file']);
$fid = $file_object->fid;
// but beware you might get 0 or many results

```

If you have more information -- such as the path (from which you can generate a URI) -- then change the query condition to something like `->propertyCondition('uri', 'public://path/to/myfirstpony.png')`.

# Answer
> 2 votes
Assuming you want to change the image field output - you might want to look at the theme\_image\_formatter function that you can override and add your variables to the $image var, that will be later sent to theme\_image or theme\_image\_style.

Be aware, that theme\_image is working with the paths, so it is possible that the function is not called from within the theme\_image\_formatter.

# Answer
> 1 votes
Suggestions about formatting are helpful, but to answer the actual question, the answer at https://drupal.org/comment/6493610#comment-6493610 looks good.

```
// Take a look at: file.inc::file_load_multiple
$files = file_load_multiple(array(), array('uri' => $uri));
$file = reset($files);
// If empty, $file will be false, otherwise will contain the required file

```

A two-liner instead of one, but should get the result we need.

# Answer
> 1 votes
If using the *file\_entity* module, you can use `file_uri_to_object` as it can load an existing file object (if exists) or create a new one.

http://www.drupalcontrib.org/api/drupal/contributions!file\_entity!file\_entity.file\_api.inc/function/file\_uri\_to\_object/7

If not using this module, just copy this function from "Source" at the link above.

This is a core issue and should be fixed in D8 sometime: https://www.drupal.org/node/685818

# Answer
> -1 votes
This seems to be the way to do it In Drupal 8

```
$files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $uri]);

```

Where `$files` will be an array of file objects, keyed by the file id.

---
Tags: 7, theming, files
---


# Question
Title: How to display title of a webform in twig template Drupal 8
I want to display webform title in a `webform.html.twig` but I did not find anything in `variables` array regarding the title of the webform

```
function THEMENAME_preprocess_webform($variables){
  $title = "?";
}

```

How do I get webform title in a preprocess function ? Any suggestions or other approach ?

# Answer
Here is what I came up with

```
function THEMENAME_preprocess_webform(&$vars){
  $wfid = $vars["element"]["#webform_id"];
  $wf = \Drupal\webform\Entity\Webform::load($wfid);
  $vars["title"] = $wf->label();
}

```

Then in your theme's `webform.html.twig` you can use `{{title}}`
> 7 votes

---
Tags: 8, theming, webforms
---


# Question
Title: How can I show 4 latest articles in ascending order?
Lets say I have 10 articles, tenth being the last one created. I want my view block to show 4 latest articles, but in ASCENDING order.

7,8,9,10 - something like this.

Can I somehow filter out the exact number of latest articles?

# Answer
Just output the rows you need and reverse them with CSS.

```
.view-content {
  display: flex;
  flex-direction: column-reverse;
}

```
> 3 votes

---
Tags: views
---


title: file_save_data doesn't save image

text:
# Question
Title: file_save_data doesn't save image
I'm using Drupal 7.56.. I want to upload images from other urls.. I use:

```
$image_original_path = '.. here my original path..';
$my_destination = 'sites/default/files/images/';
$my_new_name = 'my_image.jpg';
$filename = $my_destination.$my_new_name;
$image_object = file_get_contents($image_original_path);
$file = file_save_data($image_object,  $base_url.'/'.$filename, FILE_EXISTS_RENAME);

```

But the image is not uploaded.. Any idea please? Thank you..

# Answer
My problem is fixed by

1. going to **admin/config/media/file-system** and save configurations with **temporary folder** = **tmp**
2. check permissions 777 on tmp folder
3. `$filename = 'my_image.jpg';
 $image_object = file_get_contents('...original_image_s_path...');
 $file = file_save_data($image_object, 'public://' . $filename, FILE_EXISTS_RENAME);`

This saves my image under sites/default/files

Thank you.
> 0 votes

# Answer
**Updated:**
Try with this code:

```

$image_original_path = '.. here my original path..';
$image_object = file_get_contents($image_original_path);
$file = file_save_data($image_object, file_default_scheme().'://'.basename($image_original_path),FILE_EXISTS_RENAME);
// Add this code also
if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
  $file->status = 1;
  $file = file_save($file);
}

```
> 0 votes

---
Tags: 7, files
---


# Question
Title: Drupal 8 update via drush removes files from vendor folder
I recently made a core update with drush for D8. After the update I saw that it removed a folder from the 'vendor' folder on the server? Why did that happen?

The module has been installed via Composer because it needs dependencies to be installed: https://www.drupal.org/project/alinks

Re-installing the dependencies, works:

```
composer require "wamania/php-stemmer"

```

Is there something I did wrong? Do I need to update the core in a different way rather then using drush if you have installed modules via composer?

Removing the module via backoffice D8 and then removing folders from 'module/contrib' and 'vendor' and then re-installing the module works, but that is just not the way to do.

Thanks.

# Answer
> 3 votes
This is normal, because an update with Drush overwrites vendor and composer.json. So if you've installed a module via composer you need to reinstall it the same way (but you should be able to avoid a reinstall in the backoffice if you manage to get the code base right before running update.php or `drush updatedb`).

Updating core with Drush is depracetated and this function is removed from Drush 9.0. So you might consider switching core to a composer based install.

**Edit to answer this comment:**

> Well I'm a bit lost here on how to manage this, so more info is required I guess? Today I tried to install a module with composer (fieldblock) but could not find it? So I had to install it with drush ... For me it is not really clear right now what the best practice is and how to avoid problems in the future when having a core update ..

It's still OK to manage core and module updates with Drush as long as you use only modules which can be installed by Drush and don't mix it with Composer. However, when you start to use composer only modules you should really think about switching over to a composer based Drupal install. It's possible to start a new composer based project and keep the existing database, see this great answer from @greg\_1\_anderson Updating core with Composer doesn't work

---
Tags: 8, updating, composer
---


# Question
Title: Install a Drupal module from git on a production site
I would like to install the "Private-Message-Messenger" module on my Drupal 8 site, but the module is not available on drupal.org

It is only available on git.

If I install this module on my site in production, how will happen the update when the module will be available on drupal.org?

Should I uninstall the git module completely and install the drupal.org module?

Should I just do an update of the module?

Is it likely to break the site?

I specify that I use "Composer". I take this module as an example but this question is valid for all modules of the git.

https://github.com/jez500/Private-Message-Messenger

# Answer
How to install something from git with composer is not drupal specific: https://lornajane.net/posts/2014/use-a-github-branch-as-a-composer-dependency.

You just specifiy it as a repository as explained there.

Other than that, you already answered all our questions, once it will be on drupal.org, you can just remove that extra repository.

And yes, of course it can break your site. Any module theoretically can, and development versions even more so. There is no guarantee that updates will come with an upgrade path for existing installations. You will need to figure out that out by talking to the author about his plans.
> 1 votes

---
Tags: 8, users, composer
---


# Question
Title: Create user without password using rest api
From this documentation, currently what the User Registration resource does is to register a user that requires password in the Rest API.

Our goal is to call/use this api endpoint http://localhost:8080/user/register?\_format=json to create a user once validated via facebook and dont want to have password in the json.

This is what Im getting when tried to remove the `pass` field

```
{
    "message": "No password provided."
}

```

from

```
{
"name": { "value": "test03" },
"mail": { "value": "test03@gmail.com" }
}

```

# Answer
Just like when you create a user on user/register, the visibility/requiredness of the password field depends on the verify\_mail setting.

If e-mail verification is enabled, then you must not provide a password, if disabled, you must provide one.
> 1 votes

---
Tags: 8
---


# Question
Title: dynamically fill a field with the value of a field in another node referenced with an entity reference field
Referencing entities is a great capability of Drupal but gives me headaches.

I have three content types: Client, Contact and Job ticket.

Clients are companies with whom I conduct business. Contacts are contact persons within these companies. The Contact content type has a reference field referencing their company's node. Job tickets are tickets for jobs these companies hire me to do for them. In this content type I have two reference fields: one for the Client and one for the Contact.

This is my problem: In the Job Ticket I have a select list field that needs to be populated with the address (or addresses, since there can be multiple values for the Address field in the Client content type) of the client when I select the client in the reference field select list. How can I do this automatically.

I tried the Field Reference module but I can't get it to work, and it would give me ALL the addresses from ALL the client nodes. I only need the one(s) from the previously selected client.

Thanks in advance.

# Answer
> 0 votes
You don't state much about your setup, so I am gonna presume you are using drupal 7. In that case I highly recommend using entityreferences. It replaces the former nodereference and userreference modules IMO. You can reference any entity with it. Also your custom CTs (Client, Contact, Job.)

When you create a reference field you have to option to use a 'simple' selection which indeed gives you ALL content of a certain type. But you can also choose to use a custom made view for the selection.

Using a contextual filter (which you can pass along in the entityreference field settings) you can filter the view down to exactly what you want. It's brilliant, try it!

---
Tags: entities
---


title: Absolute or relative URLs?

text:
# Question
Title: Absolute or relative URLs?
Never thought Drupal's way to use relative URLs everywhere in template files was a problem until I happened on https://stackoverflow.com/questions/17187437/relative-urls-in-wordpress and read some arguments against using relative urls of many WP developers including core ones. Copying them here:

> * Root-relative URLs aren't really proper. /path/ might not be WordPress, it might be outside of the install. So really it's not
> much different than an absolute URL.
> * Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace
> is going to be necessary in most situations, and having an absolute
> URL is ironically more portable for those reasons.
> * absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce
> potential bugs (and incompatibilities with plugins).
> * Relative to what, I'm not sure, as WordPress is often in a subdirectory, which means we'll always need to process the content to then add in the rest of the path. This introduces overhead.
> * Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.
> * WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.

Now I wonder how much those concerns are legitimate in general, in if they or some of them are, then how much this relates to Drupal in particular?

# Answer
> 0 votes
As a developer who has worked extensively with both Drupal and Wordpress I have to say that the convenience of Drupal's relative URLs outweighs the (apparent) accuracy of Wordpress's absolute URLs.

* When moving a site from dev \> staging \> production a Wordpress site's URLs and image references have to be replaced in the DB, this can create an absolute mess.
* Rather than creating links between pages as hyperlinks a good Drupal setup uses entity reference and entity embed, so if the path or URL of a file changes the page's source is still correct.
* Wordpress feeds are natively better as the URLs are natively absolute, Drupal views feeds can be made to use content filters to make links absolute.
* In Drupal I like to use a module called pathologic to set absolute URLs in the rendered source, the stored source however remains free of site domain.
* Performance hit of content filtering is negligible on Drupal and there are multiple layers of caching.

Hope that answers some people's questions if they arrive here.

---
Tags: uri
---


# Question
Title: How to correctly modify Taxonomy Term selection Plugin
I want some slight modifications of `Drupal\taxonomy\Plugin\EntityReferenceSelection\TermSelection::getReferenceableEntities()`, for example to not use `-` to indicate term hierarchy. How can that be achieved?

I tried to extend that class in a custom module like that:

```
/**
 * Provides specific access control for the taxonomy_term entity type.
 *
 * @EntityReferenceSelection(
 *   id = "default:custom_taxonomy_term",
 *   label = @Translation("Custom Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "custom",
 *   weight = 2
 * )
 */
class CustomTermSelection extends TermSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    // Customization will be here...
  }
}

```

The plugin seems to be detected, it appears while debugging `$selection_plugins` in `Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::fieldSettingsForm()`, but it won't appear as reference method on editing the term reference field.

What else do I need to modify to get it work?

# Answer
The annotation in the sample code of my question was wrong. With the help of the first comment to this issue I was able to solve the problem (see accepted answer there). Although this question is a bit different it might be marked as duplicate to How to display more than 10 items in link widget autocomplete?.

Anyway I want to leave the custom plugin including the annotation:

```
<?php

namespace Drupal\custom\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\Plugin\EntityReferenceSelection\TermSelection;

/**
 * Provides specific access control for the taxonomy_term entity type.
 *
 * @EntityReferenceSelection(
 *   id = "custom:taxonomy_term",
 *   label = @Translation("Custom Taxonomy Term selection"),
 *   base_plugin_label = @Translation("Custom Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "custom",
 *   weight = 2
 * )
 */
class CustomTermSelection extends TermSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    if ($match || $limit) {
      return parent::getReferenceableEntities($match, $match_operator, $limit);
    }

    $options = [];

    $bundles = $this->entityManager->getBundleInfo('taxonomy_term');
    $bundle_names = $this->getConfiguration()['target_bundles'] ?: array_keys($bundles);

    foreach ($bundle_names as $bundle) {
      if ($vocabulary = Vocabulary::load($bundle)) {
        if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) {
          foreach ($terms as $term) {
            $options[$vocabulary->id()][$term->id()] = Html::escape($this->entityManager->getTranslationFromContext($term)->label());
          }
        }
      }
    }

    return $options;
  }

}

```

One thing I want to point out, which was not part of the above linked answer is the `base_plugin_label = @Translation("Custom Taxonomy Term selection")` (solution found on d.o. issue). Without that I got the following notice:

> Notice: Undefined index: base\_plugin\_label in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem-\>fieldSettingsForm() (line 336 of core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php).
> 4 votes

# Answer
You need to create new custom plugin which extends class of target Core plugin.

File: modules/custom/src/Plugin/EntityReferenceSelection/CustomSelection.php

After this you can navigate to field settings and select your method.
> 2 votes

---
Tags: 8, taxonomy-terms, plugins
---


# Question
Title: 8.4 - Use entity browser in a module block from in same way as I would in a custom block
I am having trouble adding an image picker to a block form defined in a custom module.

If I create a custom block type I can define an image field as `entity_reference` and in the block's form view tell it to use `entity_browser` and `media_entity_browser`. This provides me with an picker with which I can select my image:

I am trying to recreate this in a block provided by my custom module, without much success

```
// /src/Plugin/Block/MyCustomBlock.php

function blockForm($form, FormStateInterface $form_state)
{
    ...

    $form['image'] = [
      '#type' => 'entity_browser',
      '#entity_browser' => 'media_entity_browser',
      '#title' => $this->t('Image'),
      '#default_value' => $this->configuration['image'] ?? null,
      '#weight' => '0',
    ];

    ...
}

```

This gives me the following. Note the lack of the bounding box, title and option to edit remove items:

Exporting the configuration files for the working form view gets me this:

```
// core.entity_form_display.block_content.lead_block.default.yml

...

field_image:
    weight: 1
    settings:
      entity_browser: media_entity_browser
      field_widget_display: rendered_entity
      field_widget_edit: true
      field_widget_remove: true
      selection_mode: selection_append
      field_widget_display_settings:
        view_mode: default
      open: false
    third_party_settings: {  }
    type: entity_browser_entity_reference
    region: content

 ...

```

But if I try and use `'type' => 'entity_browser_entity_reference'` in my blockForm function the field disappears altogether.

Looking into various core files I can see that `entity_browser` is a `@FormElement` and `entity_browser_entity_reference` is a `@FieldWidget` but I don't really understand the difference.

As you might guess I am fairly new to Drupal and I feel like I am missing something fundamental. I (think I) understand that custom block types are actually nodes internally and that they are subject to different rules to blocks which I define in my custom modules, but I don't fully grasp what the differences here are.

**Is is it possible to use the entity browser in my custom module block form in the same way as it is used in the form which I build through the admin's custom block type builder?**

Thank you.

# Answer
> 1 votes
No, this is not possible. Block forms in a block plugin are configuration forms and here you can only use Form API fields.

> I (think I) understand that custom block types are actually nodes internally and that they are subject to different rules to blocks which I define in my custom modules, but I don't fully grasp what the differences here are.

Custom blocks are not exactly nodes internally, it's very similar, custom blocks and nodes are both content entities. This doesn't change the rest of what you found out correctly. You can use entity fields and their form elements, widget and formatters only for content entities.

---
Tags: 8, media
---


# Question
Title: Block View Relationship between two content types
I have a *Program* content type which has a *Paragraphs* field which uses an Entity reference to a *Course* content type. Basically, when adding a program, I'm able to add a listing of what courses are available each semester. The semester is the paragraph field which includes a title (Ex. Semester 1) and then unlimited items to add the courses per semester. The courses are then shown on the program page by name and code and you're then able to click on the program name which takes you to the course page. This page has a description of the course and all the other info about it.

I have everything working how I need so far but what I'd like is to create a block view on each Course page that pretty much lists all the programs which this course is being taught in. I'm assuming I have to create some sort of Contextual Filter and perhaps a Relationships filter but everything I've tried has been a failure.

**To sum this up:** If a course is used by a program, display this program title on the course page in a block view.

**Edit: Some images for reference**

This is how the add courses paragraph looks on the Program content type

This is how the course page looks at the moment. I'd like an aside to the right showing the programs this course is taught in.

**Edit 2: My relationships available**

Here are the relationships that have the field courses:

# Answer
I ended up figuring out what was needed for my issue. A **Contextual Filter** and a **Relationship** needed to be set.

For relationship, I needed to select *Paragraph referenced from field\_courses*. Then the contextual filter needed to be **Courses (field\_courses)** *Paragraph* (category) *Appears in: semester\_courses* (Description).

Now when I go to each course, it displays what program that course is taught in.
> 0 votes

---
Tags: 8, views
---


# Question
Title: Menu theme suggestion ignored when cache turned on
I have an alternative main menu that is used on specific node types. When turning on the cache the menu block is cached. The theme suggestion for the menu is then ignored.

I tried to disable the menu cache by changing the block preprocess cache settings. But the menu block is not called when using hook\_preprocess\_block.

Also I tried to change the menu / block by using the hook\_page\_preprocess

```
function bootstrap_custom_preprocess_page(&$variables) {
   //disable caches for every top header element
   //we do this as the dynamic header menu can't be cached - because of the landing page node type

   if(key_exists('top_header', $variables['page'])){
      foreach ($variables['page']['top_header'] as $key => $value){
        if(substr($key, 0, 1) !== '#'){
          $value['#cache']['max-age'] = 0;
        }
      }
   }
}

```

No success.

# Answer
```
function bootstrap_custom_preprocess_block(&$vars) {
    if($vars['derivative_plugin_id'] == 'header-navigation') {
        //-- This stops the block being cached in drupal 8
        $vars['#cache']['max-age'] = 0;
    }
}

```

This works for me. Block preprocess is correct.
> 0 votes

---
Tags: 8, navigation, caching
---


# Question
Title: How do I modify and then render the Drupal login form in a page template in Drupal 7?
I'm working on building a custom Drupal 7 theme using bootstrap. One of the things I want to achieve is a login form that is part of the standard page template, rather than sitting alone on its own login page.

Much like on pages like this, for example, where if you are not logged in, the login form sits on each page so you can log in directly from there.

I also need to modify the rendered form to use bootstrap containers and classes, so instead of just rendering the standard form, I need to wrap the form elements in divs with "col-md-4" etc classes.

Can anyone advise or direct me to any documentation on how to achieve this. I'm sure you know that for a beginner, Drupal can be very confusing!

# Answer
> 3 votes
Drupal provides login block, you can alter or theme this by tpl file **block--user--login.tpl.php**.

so you are telling you want to use bootstrap classes for this login block.

to achive this get elements of this block by calling `$elements = drupal_get_form('user_login_block');` function

you can debug this by calling `print_r($elements);`

paste the following code in **block--user--login.tpl.php** and do changes

```
    <?php
            $elements = drupal_get_form('user_login_block');
            $rendered = drupal_render($elements);
            // to see what you have to work with
            // print "<pre>ELEMENTS: " . print_r($elements,1) . "</pre>";
            $output  = '<form action="' . $elements['#action'] .
                                      '" method="' . $elements['#method'] .
                                      '" id="' . $elements['#id'] .
                                      '" accept-charset="UTF-8"><div>';
            $output .= "<div class='col-sm-4'>".$elements['name']['#children']."</div>";
            $output .= "<div class='col-sm-4'>".$elements['pass']['#children']."</div>";
            $output .= $elements['form_build_id']['#children'];
            $output .= $elements['form_id']['#children'];
            $output .= $elements['actions']['#children'];
            $output .= $elements['links']['#children'];
            $output .= '</div></form>';
                print $output;
?>

```

# Answer
> 3 votes
1 ) Create the login and password empty page files and place them in your theme "templates" folder. The name of the files are **page--user--login.tpl.php** and page--user--password.tpl.php. There's no need of all those steps of "hook", "alter", blablabla... Drupal will use those files automatically without any call or whatever.

2 ) Put this code inside your files.

**page--user--login.tpl.php**

```
<?php print $messages; ?>
<?php print drupal_render(drupal_get_form('user_login')); ?>
<a href="user/password">Request new password"</a>

```

**page--user--password.tpl.php**

```
<?php print $messages; ?>
<?php print drupal_render(drupal_get_form('user_pass')); ?>
<a href="user/login">Go back</a>

```

3 ) Done! In thee steps. Now style your css as much you need and pimp your new fancy login page. "Inspect" your html output of your new login page and see how clean it is now. ; D

**Afterwords )**

I just spent this last hour reading posts and questions about this all over the internet, and the work around in some cases are simply crazy like using the dpm(get\_defined\_vars()); function, copying html and paste all of those input forms and attributes, blablabla. I didn't found a concise post like this. It's crazy!!!

Also, you will need (if you still don't have it and if you want it) to disable "label/description" and enable "placehover" for the inputs. You can do it all together like this:

```
<?php
/*
 *  Remove labels and add HTML5 placeholder attribute to login form
 */
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) )
    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
    $form['name']['#title_display'] = "invisible";
    $form['pass']['#title_display'] = "invisible";
}
/*
 *  Remove login form descriptions
 */
function THEMENAME_form_user_login_alter(&$form, &$form_state) {
    $form['name']['#description'] = t('');
    $form['pass']['#description'] = t('');
}
?>

```

PS ) Do you have the "header", "footer" and "sidebar" visible and want to remove them too? No problem. Go to `admin/structure/block` and click "configure". Scroll down and include this on "Show block on specific pages" option:

```
user/login
user/password

```

Done! Drupal it's incredible powerful. I think people complicate things a lot and if you see it in a simple way it will be more efficient... Most of the things you can do it inside Drupal environment.

source: https://www.drupal.org/node/1195754

# Answer
> 0 votes
https://www.drupal.org/project/simplelogin

It is a simple module for Customize Drupal Login, Password and Register pages with Background images.

Administrators can provide the ability to allow users to attach their own background images/ own background color to user login, password, registration pages. Better features including customize background color, image settings.

---
Tags: users
---


title: How to customize the user login form?

text:
# Question
Title: How to customize the user login form?
I'm trying to customize user login form in `/user/login` page and I want to use a `hook_form_alter` function to add some awesome style and placeholder to each of user login form fields and remove or hide:
"Enter your *admin* username" and "Enter the password that accompanies your username" description expressions under each of theme.
To resolve this issue I added something like below code to my **ThemeName.theme**:

```
function ThemeName_form_alter(&$form, $form_state, $form_id) {
  if ( $form['#form_id'] == 'user_login_form' ) {
    $form['actions']['submit']['#attributes']['class'][] = 'button glow button-primary expanded';
    $form['keys']['#attributes']['placeholder']['name'] = t('User name');
    $form['keys']['#attributes']['placeholder']['password'] = t('Password');
  }
}

```

I try out many different ways but I can't get any result. in finally I want to achieve something like below image:

I read this pages but seems none work in Drupal 8:
How to modify the fields of user registration form and user login form?
Modifying the default user registration page
Customize user login block

# Answer
You can add placeholders in hook\_form\_alter().

```
/**
 * Implements hook_form_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function ThemeName_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form' ) {
    // Add placeholders.
    $form['name']['#attributes']['placeholder'] = t('User name');
    $form['pass']['#attributes']['placeholder'] = t('Password');
  }
}

```

Use the Devel module functions to print out the form using kint, this way you can visibly see the entire structure of the $form array.
> 13 votes

# Answer
**SimpleLogin**

https://www.drupal.org/project/simplelogin

It is a simple module for Customize Drupal Login, Password and Register pages with Background images.

Administrators can provide the ability to allow users to attach their own background images/ own background color to user login, password, registration pages. Better features including customize background color, image settings.

Features: Clean & Sleek Design, Customize background color, link color, submit button color, Customize image settings, Background image Opacity, Remove unwanted Css files from simplelogin pages, Login pages wrapper width, Mobile responsive,
> 2 votes

---
Tags: 8, forms, theming
---


title: Customize user login block

text:
# Question
Title: Customize user login block
I've been playing around with Drupal 8 since about a week. A couple days ago I tried to design the user login page to my needs but I couldn't quite do it. My problem is the following:

I want to customize the user login form (**/user/login**). I can edit the user login page (page--user--login.html.twig) but I can't find out what the name is of the user login form? How can I restructure the elements of the user login form? Or am I looking in the wrong place?

I appreciate any help you can give!

# Answer
> 2 votes
One thing that helps immensely is to enable Twig debugging in your services.yml (not recommended for production environment).

```
parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

```

The auto\_reload and cache settings can also be set to their development settings so you do not need to rebuild cache (remove compiled twig templates manually).

This will enable HTML comments that show what template is being used for various components in markup. Bartik and Classy, by default, displays this as `block.html.twig`. The template suggestions for a block is `block--PLUGINID.html.twig` where the PLUGINID is the the block's plugin id with underscores replaced by dashes.

Example debug output from my local development environment using a sub-theme of Classy:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--userlogin.html.twig
   x block--user-login-block.html.twig
   * block--user.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/blah8/templates/block--user-login-block.html.twig' -->
<div id="block-userlogin" class="contextual-region block block-user block-user-login-block" role="form">

```

`templates/block--user-login-block.html.twig`

# Answer
> 1 votes
You have this page:

* /user - page--user.html.twig
* /user/login - page--user--login.html.twig
* /user/password - page--user--password.html.twig

I suggest you to use, for all this page

```
{% extends "page.html.twig" %}

```

Inside of this page **page--user.html.twig** with this

```
<div class="user-login">
{% if page.content %}
       {{ page.content }}
    {% endif %}
</div>

```

And the joke is in css you have this:

```
.user-login input[type="text"],input[type="password"],input[type="email"],input[type="submit"]:hover, form, label, input[type="submit"]

```

I did only page--user.html.twig and css for all type.

If you want to structure the elements in a different way look this:

* form.html.twig
* form-element.html.twig
* menu-local-tasks.html.twig

And pls put debug: true inside services.yml

# Answer
> 0 votes
SimpleLogin: https://www.drupal.org/project/simplelogin

It is a simple module for Customize Drupal Login, Password and Register pages with Background images.

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


# Question
Title: Create relationship between node and menu link
I would like to create a node with a menu link programmatically. When the operation is complete, I would like the user to see the relationship between the node and the menu link under "Menu Settings" of the node.

I am aware of this post:

Programmatically create a node with a menu link

This shows the mechanics of creating a node and creating a menu link. It does not show how to build the relationship between the node and menu link so it is available in "Menu Settings" of the node for a user working with the Drupal GUI. How can I build this relationship?

# Answer
> 1 votes
To create a menu link for a node programmatically and to see it in the node edit form you have to connect the link uri to the node entity:

```
$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'title' => 'Menu item for node ' . $node->id(),
  'menu_name' => 'main',
]);
$item->save();

```

---
Tags: 8, nodes, navigation
---


title: How affect for each user a subdomain ?

text:
# Question
Title: How affect for each user a subdomain ?
with module domain-acces, we can manage domains and subdomains, example:

* domain.com is my first domain.
* user1.domain.com is affected to user1
* user2.domain.com is affected to user2

but user1 can connect to user2.domain.com that is my problem.

# Answer
> 0 votes
Unfortunately, it looks like this isn't what Domain Access was intended to do, as its focus is "sharing information across subdomains" rather than restricting it:

https://www.drupal.org/project/domain/issues/480716

In the comments there is a link to a code library that can achieve what you want, however.

---
Tags: users, subsites
---


title: Theming breadcrumb.html.twig

text:
# Question
Title: Theming breadcrumb.html.twig
In my theme I need to print the breadcrumbs using two different UL class names so they can be styled differently. For mobile device the breadcrumbs appear at the top with the UL

```
<ul class="topnav">

```

For large device the breadcrumbs appear in the left sidebar with the UL

```
<ul class="leftnav">

```

They both also have different LI an A class names. But I only have one template file to work with called breadcrumb.html.twig, and its themed for the topnav.

In my top region I print out the breadcrumbs with this and it the style looks good:

```
{{ drupal_block('breadcrumbs') }}

```

And for the sidebar I print out the breadcrumb again using this:

```
{{ drupal_block('breadcrumbs') }}

```

But Its using the same style as the first nav. How can I theme it differently using different class names? Can I create a theme preprocess hook and use 2 templates. breadcrumb-1.html.twig and breadcrumb-2.html.twig. THen print it like this {{ drupal\_block('breadcrumbs-1') }} and {{ drupal\_block('breadcrumbs-2') }}

I edited this because its not clear what I want. I mainly want to know if I can created and use two different templates for breadcrumb.html.twig. In Twig debug FILE NAME SUGGESTIONS, it does not give any suggestions for this template which means I can only use one in my theme. I think what I will do is add two different ul class names in my template then print the breadcrumb in each one, then add style by targeting the two different ul class names.

# Answer
> 1 votes
One quick option is to add some html markup that wraps the region (if you've disabled the default Drupal theme markup) in your page twig template where you call `{{ drupal_block('breadcrumbs') }}`.

For instance,

```
<div class="topnav">
{{ drupal_block('breadcrumbs') }}
</div>

```

and

```
<div class="leftnav">
{{ drupal_block('breadcrumbs') }}
</div>

```

---

Alternatively, if your theme is setup to render blocks assigned to regions in Drupal's *Structure \> Block Layout*, you could:

1. install/enable the Block Class module (as of Feb 23, it's in an alpha release for D8)
2. place two Breadcrumb blocks, one per region
3. assign your topnav and leftnav classes in the block config screen

---

For both use cases, you'll need to change your css to target:

```
.topnav ul
.topnav ul li
.leftnav ul
.leftnav ul li

```

---
Tags: 8, theming
---


# Question
Title: how to include one drush make.yml file in another?
With the INI-style drush `.make` files I could say `includes[common] = "common.make"` in say, `drupal_master.make` but I can't see a way of breaking my `make.yml` files into smaller reusable chunks.
I've tried

```
imports:
  - common.make.yml

```

(like Symfony uses elsewhere) as well as other guesses and I can't see any examples or documentation on "including" YAML drush make sub-files.

Can it be done?

# Answer
> 2 votes
Edit: I do see that you were using the wrong keyword, it should be `includes` and not `imports`.

It looks like you have the correct syntax above I believe. We use something like the code below in our make process, there are three different core makes that we call that one in, local, development, and build (we wanted to get updated versions in local and more stable ones in dev and build, just so we can update when appropriate.). It works pretty well but see the code below for an example. Thanks!

```
api: 2
core: X.x

defaults:
  projects:
    subdir: "contrib"

includes:
  - drupal.make.yml
  - libraries.make.yml
  - modules.make.yml
  - themes.make.yml
  - custom.make.yml

```

Here is the link for the Drush documentation for the make files, I didn't notice that they had swapped over to YML in the make docs or I would have started with this probably: Drush Docs - Make.

# Answer
> 0 votes
A typical "including" `make.yml` file:

```
---
# dev.make.yml
api: 2
core: "8.x"

includes:
  - common.make.yml

projects:
  # Modules only for development.
  devel: "1.x-dev"

```

and an "included" file:

```
---
# common.make.yml
projects:

  drupal:
    type: "core"
    download:
      branch: "8.0.0-rc1"
      working-copy: true

  views_slideshow: 3.0-beta1

```

# Answer
> -1 votes
Drush do a large use of YAML files, I suggest you organize as a codebase and use a command line tool to parse a group of files into one for every task! You can include the common parts and share schemas use a '$include' tag provided by utility like this https://github.com/javanile/yamlinc

Comparisone 'includes:' vs '$include:'

'includes:' only support specific section no nested include support, only one level of inclusion '$include:' generic place everywhere you need it, nested inclusions supported

---
Tags: drush, 8
---


title: Drupal Google Maps clustering of nodes.

text:
# Question
Title: Drupal Google Maps clustering of nodes.
I am trying to find a way I can cluster nodes on a Google Map from a custom entity according to particular regions in a country. I have been using the Geocoder module to geocode addresses but I now want to group these addresses into regional clusters. I need a way I can implement Google Map clustering in Drupal 8.

If there is a way to do it programtically please do not hesitate to illustrate.

# Answer
> 1 votes
In order to cluster your map pins/node results, you'll need to write your own javascript function to call the Google Maps Clustering Library/initialize the map (since as of Feb 23, 2018, the GMap module has yet to be fully ported/available for D8).

Based on Google's Marker Clustering Documentation/Example, I'd recommend creating a custom module that includes:

1. The Google Maps Marker Clusterer js library.
2. Setting up a json endpoint/route for the location nodes/entities
3. Custom module javascript that loads the nodes from the endpoint above and parses them (their latitude & longitude data) for the locations array in the init\_map function.

***Worth noting:***
The Google Maps clustering library is grid-based, dividing the map into squares of a certain size.

If you want regions bounded by state/provincial borders, this library won't satisfy the zoomed out map with multiple regions; you'll need something more custom. In such a case, you can:

1. add a taxonomy for the regions (with a custom set of geocoordinates for the center or political capital of each region)
2. load a custom high level map with the regions defined/outlined with svg polygon paths and displaying custom cluster pins
3. on each specific regional map utilize the grid-based clustering library

---
Tags: 8, nodes, google-maps
---


# Question
Title: How does one compare a date field with the non-UTC user/system time?
Date field data won't always correspond to UTC. From a user perspective, these dates are assumed to be in the user's timezone. However, it is currently not possible to store dates in timezones other than UTC, at least until Add ability to select a timezone for datetime field gets in.

So when comparing these fields to the current time, the timezones won't match because the current time is in the local timezone and the field data is in UTC. We therefore need to adjust the current time to match the incorrect date field timezone (or vice versa).

What's a good solution for this?

# Answer
> 3 votes
I've developed a method to handle the conversion, thanks to help from another answer to another question. It requires a patch from Add DateTimePlus::getPhpDateTime() for situations that require a DateTimeInterface to work, however.

```
  /**
   * Fetches the current time adjusted for comparing to non-UTC date fields.
   *
   * Date field data won't always correspond to UTC. From a user perspective,
   * these dates are assumed to be in the user's timezone.  However, it is
   * currently not possible to store dates in timezones other than UTC. So when
   * comparing these fields to the current time, the timezones won't match
   * because one is the local timezone and the other is in UTC.  We therefore
   * need to adjust the current time to match the incorrect date field timezone.
   *
   * @param Drupal\Core\Datetime\DrupalDateTime $date_time
   *   The date-time object fetched from a Date field (e.g. field_date->date).
   */
  protected static function getCurrentTimeForComparingToDateFieldIncorrectlyStoredInUtc(DrupalDateTime $date_time) {
    $current_time = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
    $userTimezone = new \DateTimeZone(drupal_get_user_timezone());
    $timezone_offset = $userTimezone->getOffset($date_time->getPhpDateTime());
    $time_interval = \DateInterval::createFromDateString($timezone_offset . ' seconds');
    $current_time->add($time_interval);
    return $current_time;
  }

```

---
Tags: 8, datetime
---


# Question
Title: What is the correct syntax to embed JS from Jquery UI website in Drupal 7?
I'm trying to get simple JS to work on my site for testing, but having a hard time with the syntax.

The script I want to enable is simple hide script, html is:

```
<p>Click anywhere to toggle the box.</p>
<div id="toggle"></div>

```

JS is:

```
$( document ).click(function() {
  $( "#toggle" ).toggle( "slide" );
});

```

Example is here:

https://api.jqueryui.com/slide-effect/

What should I put in JS file to make this work with Drupal 7?

# Answer
> What should I put in JS file to make this work with Drupal 7?

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $( document ).click(function() {
      $( "#toggle" ).toggle( "slide" );
    });
    //code ends

  }
};
})(jQuery);

```

See Working with JavaScript and jQuery for in-depth info.
> 1 votes

---
Tags: javascript
---


title: Getting node in theme_preprocess_node

text:
# Question
Title: Getting node in theme_preprocess_node
I have this code:

```
function material_base_preprocess_node(&$variables){
    $node = $variables['node'];
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $variables['username'] = $node->getOwner()->getTranslation($language)->field_name->value;
    $variables['mediums1'] = $node->getTranslation($language)->field_mediums->value;
}

```

this line works fine:

```
 $variables['username'] = $node->getOwner()->getTranslation($language)->field_name->value;

```

but this

```
 $variables['mediums1'] = $node->getTranslation($language)->field_mediums->value;

```

gets error:

```
The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">InvalidArgumentException</em>: Invalid translation language (en) specified. in <em class="placeholder">Drupal\Core\Entity\ContentEntityBase->getTranslation()</em> (line <em class="placeholder">789</em> of <em class="placeholder">core/lib/Drupal/Core/Entity/ContentEntityBase.php</em>).

```

Why this code works for user, but not for node and how to fix that?

this one works

```
$node->get('field_mediums')->entity->getTranslation($language)->name->value;

```

# Answer
As the exception message says, there is no english translation for that node.

The node is already in the translation that Drupal determined is the best available translation for this page.

If you do want to get a specific translation, you need to check with `hasTranslation()` first or use `\Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode);`
> 2 votes

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


# Question
Title: D8 generate double URL for commerce product
I need to create double URL alias for commerce product. I tried with code below :

```
function mymodule_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
    if($entity->getEntityTypeId() == 'commerce_product'){
        $alias = '/store/'.$entity->getTitle();
        $source = '/product/' . $entity->id();
        $path = \Drupal::service('path.alias_storage')->save($source, $alias, "en");
    }
}

```

but doesn't work. My alias is overridden by pathauto and I have 2 equal alias. I need to create /catalog/\[commerce\_product:title\] and /store/\[commerce\_product:title\] URLs.

The first one is set with pathauto pattern and created succesfully. The second one is create with the code above.

After updating the product i have 2 equal URLs:

1. /catalog/product-title
2. /catalog/product-title

why do not I have

1. /catalog/product-title
2. /store/product-title

how can I save double different alias?

Thanks in advance.

# Answer
In your hook\_entity\_update() do like below

```
    function mymodule_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
      if($entity->getEntityTypeId() == 'commerce_product'){
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $aliasStorage = \Drupal::service('path.alias_storage');
        $source = '/product/' . $entity->id();
        if ($aliasStorage->aliasExists($source, $langcode)) {
          // alias already exist. So save your second alias here.
          $aliasStorage->save('/product/' . $entity->id(), YOURNEWALIAS, $language);

        }
        else {
           $aliasStorage->save('/product/' . $entity->id(), YOURNEWALIAS_1, $language);
           $aliasStorage->save('/product/' . $entity->id(), YOURNEWALIAS_2, $language);
        }
        }
    }

```
> 1 votes

# Answer
```
function mymodule_node_update(Drupal\Core\Entity\EntityInterface $node) {
  multiple_alias_callback($node);
}

function multiple_alias_callback(Drupal\Core\Entity\EntityInterface $node) {
// Set of conditions as per your requirement
  $new_alias_val = '/your/custom/new/alias';
  $node->path = \Drupal::service('path.alias_storage')->save('/node/' . $node->id(), $new_alias_val);
}

```

This is example for saving multiple alias for node, you can use that for saving multiple alias for entity. Please update your code like this **$node-\>path** for saving.
> 0 votes

# Answer
To store double URL alias you have to disable pathauto patterns created in admin/config/search/path/patterns. Generate desired pattern for products or nodes. In this example pattern\_id\_1, pattern\_id\_2. Disable them.

After that you have to use this code:

```
function MYMODULE_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
    // Convert to lowercase, trim spaces, replace spaces with underscore and then truncate to 60 chars.
    if($entity->getEntityTypeId() == 'commerce_product'){
        //aggiungo URL sezione store
        $aliasStorage = \Drupal::service('path.alias_storage');
        $langcode = $entity->language()->getId();
        $source = '/product/' . $entity->id();

        $alias = MYMODULE_get_product_alias($entity, 'pattern_id_1');

        if($alias){
            if ( !$aliasStorage->aliasExists($alias, $langcode, $source) ) {
                $path = $aliasStorage->save($source, $alias, $langcode);

            }
        }

        $alias = MYMODULE_get_product_alias($entity, 'pattern_id_2');

        if($alias){
            if ( !$aliasStorage->aliasExists($alias, $langcode, $source) ) {
                $path = $aliasStorage->save($source, $alias, $langcode);

            }
        }
    }

}

```

and this to create alias with second pattern.

```
function MYMODULE_get_product_alias($entity, $pattern_key){

    $pattern = \Drupal::entityTypeManager()->getStorage('pathauto_pattern')->load($pattern_key);

    $tokenEntityMapper = \Drupal::service('token.entity_mapper');
    $aliasCleaner = \Drupal::service('pathauto.alias_cleaner');
    $storage = \Drupal::service('path.alias_storage');
    $token = \Drupal::service('token');

    $langcode = $entity->language()->getId();

    // Build token data.
    $data = [
        $tokenEntityMapper->getTokenTypeForEntityType($entity->getEntityTypeId()) => $entity,
    ];

    // Replace any tokens in the pattern.
    // Uses callback option to clean replacements. No sanitization.
    // Pass empty BubbleableMetadata object to explicitly ignore cacheablity,
    // as the result is never rendered.
    $alias = $token->replace($pattern->getPattern(), $data, array(
        'clear' => TRUE,
        'callback' => array($aliasCleaner, 'cleanTokenValues'),
        'langcode' => $langcode,
        'pathauto' => TRUE,
    ), new BubbleableMetadata());

    // Check if the token replacement has not actually replaced any values. If
    // that is the case, then stop because we should not generate an alias.
    // @see token_scan()
    $pattern_tokens_removed = preg_replace('/\[[^\s\]:]*:[^\s\]]*\]/', '', $pattern->getPattern());

    if ($alias === $pattern_tokens_removed) {
        return NULL;
    }

    return $aliasCleaner->cleanAlias($alias);
}

```

Without disable patterns, the URL created programmatically was overriden by pathauto.
> 0 votes

---
Tags: 8, commerce, path-aliases
---


# Question
Title: How to copy data from one field to another in same content type using hook_update_N
Trying to copy data from field A (plain text field) to field B (entity reference field with taxonomy) within the same content type. The taxonomy terms used in field B are the same terms used in old field (field A).

Below is my first attempt in writing a hook for field copy (using hook\_update\_N) but its not working.

```
function mymodule_update_8001() {
   $node_type = "test_content_type";
   $nidArray = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);

  foreach ($nidArray as $nid) {
    $node = node_load($nid);
    $termString = $node->field_a;
    $termObject = taxonomy_term_load_multiple_by_name($termString);
    $node->field_b->target_id = $termObject->tid;
    $node->revision = TRUE;
    node_save($node);
  }
}

```

Any help on this would be greatly appreciated.

# Answer
> 4 votes
The code doesn't work because it uses `node_save()`, which is a function Drupal 8 doesn't implement. (If you click on *Same name and namespace in other branches* on the documentation page, you will notice there isn't a link for any Drupal 8.x version.)
In Drupal 8, where a `$node` is an instance of a class implementing `EntityInterface`, a node is saved with `$node->save()`.

The code is also using functions that are still implemented by Drupal 8, but they are deprecated and they will be removed on Drupal 9 or future Drupal versions.

The hook to implement isn't `hook_update_N()`. As the documentation for that hook says, loading, saving, or performing any other CRUD operation on an entity is never safe to do inside `hook_update_N()`.
The correct hook to implement in this case is `hook_post_update_NAME()`, which receives the same arguments `hook_update_N()` gets. The expected return values are the same values expected from `hook_update_N()`.

Since updating all the nodes could possibly cause PHP to time out, depending on the number of nodes the site has, the operation needs to be executed in batches, using the argument `hook_post_update_NAME()` gets.

The code I would use is the following one.

```
// Add the following lines at the begin of the mymodule.post_update.php file,
// where this hook is expected to be.
// (Replace mymodule with the machine name of the module you are using to
// implement the hook, in the hook name and in the name of the file containing
// it.)
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Drupal\taxonomy\TermInterface;

function mymodule_post_update_update_taxonomy_references(&$sandbox) {
  $content_type = 'test_content_type';
  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
  $entity_type_manager = \Drupal::entityTypeManager();
  /** @var \Drupal\Core\Entity\EntityStorageInterface $node_storage */
  $node_storage = $entity_type_manager->getStorage('node');
  /** @var \Drupal\Core\Entity\EntityStorageInterface $taxonomy_term_storage */
  $taxonomy_term_storage = $entity_type_manager->getStorage('taxonomy_term');
  if (!isset($sandbox['total']) && !isset($sandbox['count'])) {
    $sandbox['current'] = 0;
    $sandbox['count'] = 0;
    $sandbox['max'] = array_shift($node_storage->getQuery()
      ->accessCheck(FALSE)
      ->sort('created', 'DESC')
      ->pager(10)
      ->execute());
    $sandbox['total'] = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', $content_type)
      ->count()->execute();
  }
  if (!empty($sandbox['total'])) {
    $nids = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->pager(50)
      ->condition('type', $content_type)
      ->condition('nid', $sandbox['current'], '>')
      ->sort('nid', 'ASC')
      ->execute();
    $nodes = $node_storage->loadMultiple($nids);
    /** @var \Drupal\node\NodeInterface $node */
    foreach ($nodes as $node) {
      $sandbox['current'] = $node->id();
      $sandbox['count']++;
      $taxonomy_terms = $taxonomy_term_storage->loadByProperties(['name' => $node->field_a]);
      if (!empty($taxonomy_terms) && is_array($taxonomy_terms)) {
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        $taxonomy_term = reset($taxonomy_terms);
        $node->field_b->entity = $taxonomy_term;
        $node->setNewRevision();
        $node->save();
      }
    }
  }
  if (empty($sandbox['total']) || $sandbox['current'] >= $sandbox['max']) {
    $sandbox['#finished'] = 1;
  }
  else {
    $sandbox['#finished'] = $sandbox['count'] / $sandbox['total'];
  }
}

```

---
Tags: 8, hooks
---


# Question
Title: "You don't have permission to access / on this server"
I'm running my local development sites on a Windows machine with Uniserver. I have them all set up as vhosts and they work fine with Drupal 7. Recently I decided to install a vhost with Drupal 8, but when I go to the site I get the following error:

> 403 Forbidden - You don't have permission to access / on this server

The error log for the site says:

> Options FollowSymLinks and SymLinksIfOwnerMatch are both off, so the RewriteRule directive is also forbidden due to its similar ability to circumvent directory restrictions

If I add `Options +FollowSymLinks` to the vhost's .htaccess file, it works fine. How should I be doing this? I can't imagine Drupal 8 is supposed to have this done on every installation. For reference, I'm running the site on:

* Apache 2.4.18
* PHP 5.6.18
* MySQL 5.6.28

# Answer
> 3 votes
> I can't imagine Drupal 8 is supposed to have this done on every installation.

You're right, it only needs to be done in .htaccess where altering the web server config isn't an option (think shared hosting).

In a local dev environment you don't have that problem, so just update the vhost with something like

```
<Directory "/var/www/site/public_html">
  Options FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>

```

and re-start/load Apache for it to take effect.

# Answer
> 0 votes
I've also had a problems with "You don't have permission to access / on this server", but for completely different reason - I've forgot to put the domain in /etc/hosts file (as explained here).

Sharing here for those who are forgetful as me :)

---
Tags: 8, .htaccess
---


# Question
Title: User resetting password, week later needing to reset it again
I have a develop and a production version of a site running behind a firewall. In production the users passwords are somehow being reverted and once the user resets it, they get a random amount of time and are required to reset it again. I cannot track this down. Looking for any suggestions on what is going on. I have looked in the logs, but don't see any flags.

Setup consists of 3 servers. One for Drupal App, One for MySql DB, One for Solr.

# Answer
> 0 votes
Here are some suggestions/things to check based on your description:

1. If the user passwords on production are reverting after a recent deployment, check to make sure that your settings.php file on production doesn't point to the development instance's database (you may be inadvertently repointed production to a backup copy/development copy of the database by pushing changes in settings.php).
2. Check to see if your site is utilizing a password management module. If so, doublecheck/resave expiration settings (as well as if any security/recommended updates are available). Common password management/expiration modules include:
3. Check to see if there are any custom rules (either using Rules module or programmatically implemented with a custom module) in place that force a user to reset password after a set duration/period of time/number of logins.
4. Check to see if the site's user accounts are tied to an external user account provisioning/login system such as LDAP or a Single Sign On service (as well as if any security/recommended updates are available). If one of these are in place, then you may need to check password expiration policies at the account provider. Examples SSO service modules for Drupal include:

* Janrain - integration with the commercial Janrain service
    * Google Apps Authentication
    * SimpleSAMLphp Auth - integration with the open source library SimpleSAMLphp
    * HybridAuth Social Login - integration with the HybridAuth library
    * Bakery - SSO among Drupal installations on the same parent domain
    * Account Sync - provides SSO functionality and account info synchronization among Drupal installations.

---
Tags: 7, users
---


title: How do I uninstall Drush?

text:
# Question
Title: How do I uninstall Drush?
There is a method of installing Drush via Composer.

```
composer global require drush/drush:dev-master

```

How do I uninstall it using Composer?

# Answer
> 28 votes
It seems there is no single remove command, so you need to:

1. Edit your `composer.json` file, e.g.

```
vim ~/.composer/composer.json

```

and remove line containing drush. Save the file.
2. Update Composer PHP packages by:

```
composer global update

```

It will remove a globally installed `drush`.

If you don't have `composer` command in your PATH, try `php composer.phar` instead.

See: How to remove a package from composer?.

# Answer
> 16 votes
You can use `composer global remove drush/drush` to uninstall a global Drush.

Or use `composer remove drush/drush` to uninstall a project-local Drush.

---
Tags: drush, composer
---