# Question
Title: How do I set BCC in the email I am sending?
I am using Drupal 8. How can I add the BCC field in the mail function.

Using below code Bcc not working

```
$params['body'] = 'test body';
$params['subject'] = 'test subject';
$params['Bcc'] = 'test@gmail.com';
$message =  \Drupal::service('plugin.manager.mail')->mail('test', 'test_email_form', $to, $langcode, $params, $from);

```

hook\_mail function code:

```
function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'test_email_form':
      $message['headers']['Bcc'] = $params['Bcc'];
      break;
  }
}

```

# Answer
Your `hook_mail` implementation needs to set the subject/body for the email to send; `$params` is just passed for context.

Given your first snippet, this should work:

```
function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'test_email_form':
      $message['headers']['Bcc'] = $params['Bcc'];
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}

```
> 7 votes

# Answer
In Drupal 8, you can use the mail manager service to invoke the hook\_mail(), you have to use any mail server for the same also (example: mailsystem, swiftmailer), so first you have to define the variables and invoke the same and then add necessary parameters to the mail message using hook\_mail. The following codes used to invoke the mail,

```

$reciever_email = 'youremailid@xyz.com';
// The language code.
$langcode = 'en';
// Key for hook_mail.
$key = 'mykey';
// Your module name.
$module_name = 'mymodule';
$reply = NULL;
$send = TRUE;
$params = array(
  'subject' => $subject,
  'body' => $body,
);

// Send mail.
$mail_manager = \Drupal::service('plugin.manager.mail');
$result = $mail_manager->mail($module_name, $key, $reciever_email, $langcode, $params, $reply, TRUE);
if ($result['result'] != TRUE) {
  $message = t('There was a problem sending your email notification to @email.', array('@email' => $reciever_email));
  drupal_set_message($message, 'error');
  \Drupal::logger('mail-log')->error($message);
}
else {
  $message = t('An email notification has been sent to @email.', ['@email' => $user_email]);
  drupal_set_message($message);
  \Drupal::logger('mail-log')->notice($message);
}

```

Then in your hook\_mail you can use the key value to identify the mail message and other settings for the mail,

```

YOUR_MODULE_NAME_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );
  // Specify the headers if necessary.
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
  // Create cases for different kinds of mails.
  switch ($key) {
    case 'mykey':
      $email_id = 'sampleemail@xyz.com';
      $valid = \Drupal::service('email.validator')->isValid($email_id);
      if ($valid == TRUE) {
        $message['from'] = $email_id;
      }
      else {
        $message = t('Invalid email-id is given in from address.');
        drupal_set_message($message, 'error');
      }
      $bcc_mail = 'mybcc@xyz.com';
      $valid_bcc = \Drupal::service('email.validator')->isValid($bcc_mail);
      if ($valid_bcc == TRUE) {
        $message['headers']['bcc'] = $bcc_mail;
      }
      $message['subject'] = t('@title', array('@title' => $params['subject']), $options);
      $message['body'][] = $params['body'];
      break;
  }
}

```

Hope this helps.
> 1 votes

---
Tags: 8, emails
---


# Question
Title: How to tag content by users and filter the content in a view?
I have a content type Meeting Minutes. I'd like to tag users in the minutes. There will be a view to the list of minutes only for the logged in user.

For example:

* Meeting 1, tags Peter, Mary
* Meeting 2, tags Paul, Mary
* Meeting 3, tags Peter

When Mary logs in, the view shows:

* Meeting 1
* Meeting 2

When Peter logs in, the view shows:

* Meeting 1
* Meeting 3

Is there a user tags module for a content type and good for view-filter?

# Answer
Add `entity reference` field in `Meeting Minutes` use entity type `user` and then tag users from there with you content of Meeting
now in views
use `Contextual filters`
add `Contextual filters` select you user reference field like if your field name is

```
Content: user in meeting

```

then select

```
Provide default value

```

from check boxes a select list will be appear then select from them

```
User ID from logged in user

```

and done
Now when page load content should be filtered with current user id
i think this will solve your problem
> 1 votes

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


title: Is hook_boot() deprecated?

text:
# Question
Title: Is hook_boot() deprecated?
I created a module in Drupal 7. Two years ago, that was working for me. Right now, it is not working, as well as `drupal_add_js()`. It is also giving me an error when I implement `hook_boot()`.

Is `hook_boot()` deprecated?

# Answer
> 1 votes
Deprecated? I suppose yes, technically, it was. `hook_boot()` was completely removed in Drupal 8, so you could take that to mean that it was deprecated in 7, even though it doesn't look like it was formally documented in the usual way (for example by adding `@deprecated` to the doc block in the system.api.php file).

However it was never, and won't ever be, *removed* from Drupal 7. Plenty of core and contributed modules are still using it just like they always have done. If your code is suddenly not working, check what else has changed that might be affecting it; `hook_boot()` hasn't gone anywhere.

---
Tags: hooks
---


# Question
Title: Load external php library in custom module
I’ve read a lot of topic on this but i can’t figure why it is not working for me.

I’ve built a custom module. It is working fine since `return $output;` in my controller class is working : I can see in front-end a page with my custom html.

I’ve written a script outside Drupal in order to test. Basically, i connect to a webervice and retrieve all the datas. It’s working fine.

Now, i want to execute that script inside the controller class.

I need to load an external php library to instantiate an object.

In my test php file (outside Drupal) a simple `require_once` is working.

```
require_once('nusoap.php');

```

But it is not working in my controller class.

So, i’ve activated the library module and do :

```
$path = libraries_get_path('nusoap') . DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php';

require($path);

```

It’s still not working.

Error message indiquactes :

> Error: Class 'Drupal\webservices\_dc\nusoap\_client' not found

I’m sur the file path is correct because if i do this, i can see the content of the file.

```
echo file_get_contents(DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php');
die();

```

I’ve also tried this :

in nusoap.php (where there is the class i need to include),

```
namespace Drupal\webservices_dc;

```

and in module controller class :

```
use Drupal\webservices_dc\nusoap_client;

```

But it is still not working.

Finally, i’ve copied the content of the external php library inside the module controller and it is working.

So i’m nearly sure the issue is related to the loading of that external library.

What is the correct way to load external php library (and wait it is fully loaded) in order to use it in a custom module ?

# Answer
You cannot require classes with require or library hooks. Nor should you be editing external packages.

You are supposed to require external php packages with Composer. Composer will update the autoloader. Then in your class, you can say:

`use ExternalPackage\namespace\Foo;`

In the header and `Foo` class is then usable. Furthermore, you can inject it to the constructor with a little more work.

I would advise using SoapClient instead of nusoap as that is very old.

Regarding SoapClient, here is something I solved recently injecting it proper to my class, because that's the same road you're heading down.

Dependency inject a class with values from a config object?
> 4 votes

# Answer
You can use module\_load\_include like we use it in Drupal7. Put your Php file in you module directory and use

```
  module_load_include('php', 'modulename','filename');

```
> 0 votes

---
Tags: 8, theming
---


title: How do I use Xdebug?

text:
# Question
Title: How do I use Xdebug?
I have enabled Xdebug in my PHP installation and tried it with Drupal 7. I am interested in profiling, which function runs how many times and where are called (whole tree). There are php.ini settings:

```
zend_extension="D:\xampp\php\ext\php_xdebug.dll"
xdebug.remote_enable=1
xdebug.remote_port="9000"
xdebug.profiler_enable=1
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir="D:\xampp\tmp"
xdebug.profiler_trigger=on
xdebug.profiler_append=on
xdebug.max_nesting_level=1000

```

In Drupal 7 it generates cachegrind.out.XXX file, which i was able to open in PHPstorm, or in wincachegrind.

But in Drupal 8, it generates aprox. 400MB file and when i try to open it (PHPstorm or wincachegrind), it throws errors. These are different `Incorrect profiler snapshot format`, `incorrect function parameters`, ...

Have someone successfully profiled Drupal 8 functions with Xdebug? Is there some special setting, which I am missing? I wonder, that in Drupal 7 it worked smoothly. Or if you have better tool for this purpose, I would be happy, if you could post it here.

I use windows and PHP 5.6. That is why I choose xdebug and asked this question. Xhprof is not for PHP 5.6 and Tideways for windows is "crap"...

# Answer
> 2 votes
The format shouldn't dependent on the Drupal version, most likely you're running Drupal 7 and 8 on different PHP version which may use different Xdebug.

Since XDebug 2.3, the format of cachegrind files changed and WinCacheGrind does not support this new Callgrind format yet.

So you should use XHProf, or different software which may support it, depending on your operating system.

See also: Missing function names when opening CacheGrind file in WinCacheGrind.

---
Tags: 8, debugging
---


# Question
Title: How do I send an email when users update their email address?
If users update their email address, an email should be sent to the old and new email addresses to confirm the transaction.

How can I achieve this in Drupal 8?

# Answer
> 0 votes
You could add a HOOK\_user\_presave method in your custom module.

Example:

```
function mymodule_user_presave(\Drupal\user\UserInterface $user) {
    if ( !($user->isNew()) ) {
        //check if the value in the db is different to the value in $user
        if ($user->original->getEmail() == $user->getEmail()) {
            // send email
        }
    }
}

```

---
Tags: 8, emails
---


title: How to detect 404 in THEME file

text:
# Question
Title: How to detect 404 in THEME file
I'd like to attach a library to a custom 404 page. I'd like to do this in my theme file. How can I know if the current response will be a 404 Page Not Found?

# Answer
Got it.

In your hook within your theme file:

```
  $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
  if ($status && $status->getStatusCode() == 404) {
    $page['#attached']['library'][] = 'themename/notfound';
  }

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Render an entity reference in a twig template
I have a field that is an entity reference. I would like to print the entire entity in my controller.

I know I can print a particular field of the entity using something like

```
{{ teacher.field_classrooms.entity.field_classroom_one.value }}

```

but I need to print the whole entity rather than just one field.

How can I accomplish this?

# Answer
> 3 votes
If you install twig\_tweak, you can load an entity directly from twig:

{{ drupal\_entity('node', node.field\_classrooms.entity.id) }}

But I would recommend against this. Drupal has a built in way to render fields, as explained by zhilevan

# Answer
> 2 votes
first you should select show *Rendered Entity* in your content type field *Manage Display* section in `admin/structure/types/manage/teacher/display` (I supposed your content type is teacher based on your question), then in your node template try to render the content field with something like

```
{{ content.field_classrooms }}

```

---
Tags: theming, 8
---


title: Using 3rd party libraries

text:
# Question
Title: Using 3rd party libraries
I'm trying to load https://github.com/PHPOffice/PHPExcel in a custom module. I've successfully added the library dependency to the composer.json file and Composer correctly downloads it into the 'vendor' folder.

The PHPExcel library doesn't use namespaces. How do I access the library? The following line

`PHPExcel_IOFactory::load($excel_filepath);`

results in

`Fatal error: Class 'Drupal\mymodule\Form\PHPExcel_IOFactory' not found in /home/me/webs/client/myhomedir/modules/custom/mymodule/src/Form/ImportProductsForm.php on line 60`

If possible, I'd prefer not to use the Libraries module.

# Answer
You are in your own namespace, that means PHP by default tries to load the class from your current namespace.

To load a non-namespaced class, you need to explicitly refer to the global namespace with a :

```
\PHPExcel_IOFactory::load($excel_filepath);

```
> 3 votes

---
Tags: 8, composer
---


# Question
Title: Views "Load More" replacing results instead of appending
Views load more is replacing the results rather than appending those below the existing ones.

I am using block for content listing and need a append more option to load more content below the existing one. I tried views show more and views load more extensions.

# Answer
> 3 votes
You can also try Views Infinite Scroll module.

> Views infinite scroll allows you to load and display pages of any view inline, using AJAX (this has been called infinite scrolling, load more, autopaging, endless pages and more). The pager can be triggered with the press of a button or automatically as the user scrolls to the bottom of the view's content.

# Answer
> 3 votes
I think you have to add `.view-content` in Advanced Options, see the attached screenshot.

Not sure it is a bug or not, when I put that it starts working as expected.

# Answer
> 0 votes
Consider using GD Infinite Scroll module. Does exactly what you are wanting to do.

# Answer
> 0 votes
Use "Views Load More" and set "Use AJAX" option to Yes under Advanced view settings.

# Answer
> 0 votes
I just encountered this same issue, and it appears that views\_infinite\_scroll will replace, rather than append, if you have theme\_debug on. i.e. `$conf['theme_debug'] = TRUE;`. Turning this off returned it to its normal append behavior.

---
Tags: views, theming
---


# Question
Title: How to validate a field value programatically in Drupal 8?
I've created a module for Drupal8 that checks against values in the user register and set an error if the values do no match with something you have entered in a custom form.

My module has got a form where you add a list of username you don't want the user to take and a custom message to display as an error.

Forms works perfectly, I can store data, edit it etc... It is stored under `src/Form/` and settings are under config/install

Now when I'm trying to hook the user register form validate I got an error regarding `form_set_error()`:

> PHP Fatal error: Call to undefined function form\_set\_error()

Also I think I'm not using `$form_state` in the right way (but it does the job)

Here's the code in `my_module.module`:

```
function my_module_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#validate'][] = 'my_module_user_validate';
}

/**
 * Custom validation function.
 */
function my_module_user_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // get module settings
    $config = \Drupal::config('my_module.settings');

    // Convert $form_state to an array as it has been passed as object, it looks wrong but I could not find any documentation at the moment
    $form_state = get_object_vars($form_state);
    $name = $form_state['values']['name']);
    $usernames = $config->get('my_modules_usernames');
    // Username are inserted in a text area separated by an enter key
    $usernames = $usernames != '' ? explode("\r\n", $usernames) : array();
    foreach ($usernames as $username) {
      if ($username == $name[1]) {
        //apparently in Drupal 8 form_set_error does not work anymmore
        form_set_error('mail', $config->get('my_module_message'));
      }
    }
  }

```

# Answer
> 6 votes
The `$form_state` now become a classed object as documented here

You can use getValue() to get field value instead of converting it into an array

```
$form_state->getValue('name');

```

instead of:

```
$form_state = get_object_vars($form_state);
$name = $form_state['values']['name']);

```

Same thing for `form_set_value`.

And `form_set_error()` became `$form_state->setErrorByName()`.

# Answer
> 2 votes
The `form_set_error()` has been dropped in favor of the following $form\_state class methods:

```
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);

```

So the code would look like:

```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Use this to find out about the current form id.
  drupal_set_message('Form ID: ' . $form_id);
}

/**
 * Implements hook_form_FORM_ID_alter() for the FORM_ID() form.
 */
function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#validate'][] = '_mymodule_form_validate';
}

/**
 * Validates submission values in the FORM_ID() form.
 */
function _mymodule_form_validate(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValue('field_myfield');
  foreach ($values as $value) {
    $plain_value = is_array($value) ? current($value) : NULL;
    if (empty($plain_value)) {
      $form_state->setErrorByName('field_myfield', t('Please enter a value!'));
    }
  }
}

```

---
Tags: users, forms, 8
---


title: Errors found Entity/field definitions

text:
# Question
Title: Errors found Entity/field definitions
In my "Administration Dashboard" there are several errors. I do not understand how to correct them. An idea ?

# Answer
> 1 votes
Sometimes in custom or contrib module updates, the schema for entities can become incorrect or have problems

If you have drush, running drush entity-updates should fix this. See this question for extra information.

---
Tags: 8
---


# Question
Title: How do I redirect to a route with POST method?
I want to redirect to a route and also want to send some parameters which I don't want to expose on URL.

So, I need to redirect with a post method. How to do this?

```
$form_state->setRedirect('route.name', array('key' => 'value'));
new RedirectResponse(\Drupal::url('route.name',array('key' => 'value')));

```

all these above procedure to redirect is done through GET methods.

So, is it possible to do this with POST method?

# Answer
Normally, you cannot redirect through a HTTP "POST" response. A normal Drupal RedirectResponse (or whatever redirect response you send) will be a 302 or 301 redirect, which is done through the GET method.

Basically, you can do a subrequest, as suggested by Eyal, or you can add some server validation to grant a "200 OK" response through your "hidden" route, such as a CSRF token. To keep alive some posted information, you can use your Session service to flash them for the next request, then flush them in your hidden route after your validation
> 0 votes

---
Tags: 8, redirection
---


# Question
Title: Hook Form Alter not saving results on form submit
UPDATE: Select list saves data, changed the way it was attached to ajax.. Multiselect form thats gets populated once ajax fires, those values are empty upon node save.

I'm using hook form alter to do 2 things. First I'm adding an ajax callback on a select list. Based upon the selection I'm calling a function to pull in data that I'm then using to populate the multiselect list.

All is visually working fine and the data is properly going in as a key =\> value for the multiselect.

The problem I'm having right now is when I submit the form those form values set for multiselect are not saved with the node.

This is Drupal 7.. am I missing something.. do I need to programmatically populate the fields, do I need to do something with #after\_build

Structure:

* Hook form alter
* -- overriding 2 form elements
* --- 1 select list with ajax call back
* --- 2 Multiselect with key value data added based upon the results from the select list
* ajax callback function that returns the $form
* function to pull in the data I need for the multi select.

suggestions?

code: hook form alter block

```
/**
 * Implements hook_form_alter().
 */
function lm_groups_form_alter(&$form, $form_state, $form_id) {

  if($form_id == 'group_node_form') {

    // ajax callback for org type value to populate help populate tags multiselect
    $group_type = isset($form_state['values']['field_group_type']) ? $form_state['values']['field_group_type'] : NULL;
    // return select list array for multiselect to filter tags by group type
    if($group_type != NULL) {
      // function to return key => value from a custom view
      $tags = lm_groups_get_likemojis($group_type['und'][0]['tid'], TRUE);
      dsm($form);
      dsm($form_state);
    } else {
      $tags[0] = NULL;
    }

    //dsm($form);
    //dsm($form_state);

    // Add Ajax callback to parent field.
    $form['field_group_type'][LANGUAGE_NONE]['#ajax'] = array(
        'callback' => 'lm_groups_ajax_callback',
        'wrapper' => 'checkboxes-div',
    );

    $form['field_group_tags'] = array(
      '#prefix' => '<div id="checkboxes-div">',
      '#suffix' => '</div>',
      '#type' => 'multiselect',
      '#title' => t('tags'),
      '#options' => $tags,
      '#default_value' => _lm_groups_options(),
      '#multiple' => TRUE,
      '#size' => 15,
      '#weight' => 3,
      '#required' => TRUE,
    );

    $form['#attached']['css'] = array(
      drupal_get_path('module', 'multiselect') . '/multiselect.css',
    );

    $form['#attached']['js'] = array(
      drupal_get_path('module', 'multiselect') . '/multiselect.js',
    );

  }
}

```

2 blocks of code, one to pull in (eventually default values for the multi select on edit node)

```
function _lm_groups_options() {
  return variable_get('multiselector', array());
}

function lm_groups_ajax_callback($form, $form_state) {
  return $form['field_group_tags'];
}

```

The callback is for the multiselect to prep it for values from the function below which just pulls some data from a view and provides the key-\>value for select lists.

The key is on the callback the form $group\_type is set which calls the function lm\_groups\_get\_tags the below function.

```
// function to get key->value from a view and some extra magic I need for the display name
function lm_groups_get_tags($tid, $filter = FALSE) {
  // custom view = tags Filter Tax which contains a tid argument that can be passed in.
  $data = views_get_view_result('tags_filter_tax', $display_id = NULL, $tid);

  foreach($data as $key => $value) {
    $nid = (int)$value->nid;
    // show tags filters on select lists if set to TRUE
    if($filter == TRUE) {
      // get taxonomy id out of the array, check if we had more than one filter
      $tids = $value->_field_data['nid']['entity']->field_filters['und'];

      foreach($tids as $key => $value2) {
        $name = taxonomy_term_load($value2['tid']);
        $filters[] = $name->name;
      }
      // build the actual output for the title including filters in ( )
      $title = trim($value->node_title) . ' - (' . implode(",",$filters) . ')';      unset($filters);
    } else {
      $title = trim($value->node_title);
    }
    $tags[$nid] = $title;
  }

  return $tags;
}

```

Visually in the form as stated above, the select list has an ajax callback, and multiselect form is populated.. when I submit this and look at the node on presave or just devel both field\_group\_tags are empty..

Please note these are already set up on the content type as a select list and a multiselect, im just over-riding and hoping to get the values to save.

excuse the mess :P

# Answer
> 0 votes
The values won't automatically be saved. You need to created database tables using hook\_schema() in an .install file, then save those values manually in hook\_node\_insert() and hook\_node\_update().

Or, if I recall correctly, you can add the fields to the {node} table in hook\_install(), define the fields in hook\_schema\_alter(), and use hook\_update\_n() to actually add the fields since it sounds like your site is already up and running. Then, if you name the form keys with the same names as the columns you created, they should automatically save and update.

---
Tags: hooks
---


# Question
Title: Is there a workaround to post inline JS code at any time?
In Drupal 7 this worked:

```
drupal_add_js("jQuery(document).ready(function () { console.log('Hello!'); });", 'inline');

```

which aims to print the messages from the PHP code onto DevTools JS console in realtime (on each page request), however in Drupal 8 the above function has been removed in favor of `#attached`.

I'm aware that I should use `#attached` in my library, but sometimes the `$form` is not accessible and I'd like to invoke some JS code on certain functions and conditions (e.g. in `hook_tokens`) for debugging purposes (like injecting some PHP variables into the JS message during the processing).

Is there any other way of doing this?

# Answer
> Sometimes the `$form` is not accessible and I'd like to invoke some JS code on certain functions and conditions for debugging purposes.

Not sure if this will do for you, but posting this anyways just in case.

I use Greasemonkey for Firefox and Tampermonkey for Chrome which allows your browser to load any js file that you write locally on this app/your computer.
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: How do I add a menu item to the main navigation from a custom module in Drupal 8?
For my custom Drupal 8 module I want to add a link to the default *main navigation* menu of the site.

What parent ID do I have to give to insert my menu item into the main menu?

I currently have the following config in `my_module.links.menu.yml`:

```
entity.sss_topic.collection:
  title: 'Topic: Listing'
  route_name: entity.sss_topic.collection
  description: 'List Topic'
  parent: main

```

But that only adds a menu item into the "Tools" menu (the same effect as specifying no *parent* whatsoever). However, `parent: system.admin_structure` does work correctly.

Do I have the wrong parent ID? Or maybe a bug?

# Answer
You are missing the "menu\_name" key as said on : https://www.drupal.org/node/2122241

this example should work :

```
demo.demo:
  title: Demo Link
  description: 'This is a demo link'
  parent: main
  route_name: demo.demo
  menu_name: main

```
> 6 votes

# Answer
Beware: Build a Drupal 8 Module: Routing, Controllers and Menu Links is outdate, for example on demo.routing.yml is no longer \_content, now is \_controller.

Relate to add a menu item to the main navigation you can try with the parent `main`, like this:

```
demo.demo:
  title: Demo Link
  description: 'This is a demo link'
  parent: main
  route_name: demo.demo

```
> 2 votes

# Answer
I can confirm when set the "parent" property to be "main" in menu.link.yml will get your menu item display below in the default "Tools" as a submenu which is pretty weird. Anyone know how to make it happen to set up a menu item in the main menu?

If anyone come to this page just for add a simple menu item to the main menu list which created by a module configured by module.links.menu.yml.

Like I have a catalogue module which need to add a menu item titled "catalogue" to the main menu so I can get to that page quickly.

```
# add below code to catalogue.links.menu.yml
catalogue.page:
  title: 'Catalogue'
  description: 'some description about the catalogue menu item'
  route_name: catalogue.page
  weight: -20
  menu_name: main
  options:
    attributes:
      target: _blank

```

Note the "menu\_name" defines which menu should the item be put in.
> 2 votes

---
Tags: routes, 8
---


# Question
Title: Config sync directory outside of webroot causes open_basedir restriction warning
Hello all and thank you for taking the time to help. In following this tutorial and many others like it, I've successfully moved the configuration sync directory outside of my webroot, both locally and on production. I can confirm that it's working using `drush cex` and `drush cim` in both locations.

## *Hopefully* Helpful Info

* Drupal 8.3.5
* On production, I have the config directory set with **775 permissions** (and export/import still worked with 755).
* in settings.php, I have `$config_directories[CONFIG_SYNC_DIRECTORY] = '../config/sync'`
* since it couldn't be created by Drupal, I created a .htaccess file for this directory on my own.
* config is being version controlled, but due to how/where Drupal was installed, I'm having to maintain a separate git repo for this single directory, which doesn't bother me. Drush still seems to work with no complaints.

## The Problem

Within the UI, I get the following status report errors:

* Warning: is\_writable(): open\_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in config\_requirements() (line 24 of core/modules/config/config.install).
* Warning: file\_exists(): open\_basedir restriction in effect. File(../config/sync/.htaccess) is not within the allowed path(s): (/home/cathchar/www:/tmp) in file\_save\_htaccess() (line 367 of core/includes/file.inc).
* Warning: file\_exists(): open\_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in file\_save\_htaccess() (line 374 of core/includes/file.inc).
* Warning: is\_dir(): open\_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in system\_requirements() (line 600 of core/modules/system/system.install).
* Warning: is\_dir(): open\_basedir restriction in effect. File(../config/sync) is not within the allowed path(s): (/home/cathchar/www:/tmp) in system\_requirements() (line 603 of core/modules/system/system.install).
* (and below these) CONFIGURATION DIRECTORY: SYNC - *The directory ../config/sync does not exist.*

## What I do/don't understand

I'm swimming in deeper waters here than I'm used to, but I sincerely want to understand errors like this and be able to get to bottom of issues. From what I understand, Drupal is warning me that my newly created /home/cathchar/config/sync directory is not in a path, namely /home/cathchar/www (the webroot) or the account root /tmp directory, that it can work with/write to. It's also warning me that that it doesn't see this directory as existing.

## My question

The directory obviously exists, but what am I missing? PHP should have no problem with seeing outside of and jumping out of the webroot, correct? Do I have to inform Drupal somewhere else about a new path to work in? None of the tutorials/instructions I've read ever mention issues regarding directory access, paths, or open\_basedir restrictions. The ones I encountered make it seem like adjusting settings.php and creating the non-webroot directory is really all it takes. I'm a bit stumped.

Any help that anyone could provide would be greatly appreciated!

# Answer
> 0 votes
> PHP should have no problem with seeing outside of and jumping out of the webroot, correct?

Very much not! As the errors are telling you, your server config explicitly doesn't allow that to happen. You have PHP locked down to only be able to read from certain paths; `/home/cathchar/config` and/or `/home/cathchar/config/sync` don't belong to that list, so PHP can't read files from them.

> Do I have to inform Drupal somewhere else about a new path to work in?

No...Drupal doesn't need to be told about file system restrictions, it just consumes the environment it finds itself in, and invariably complains if it can't access what it's (implicitly) been told it can have access to.

This should ideally be solved in your vhost/FPM config by setting an open\_basedir which includes all of the paths that PHP needs to be able to read from (separated by a `;`).

> None of the tutorials/instructions I've read ever mention issues regarding directory access, paths, or open\_basedir restrictions

The docs don't really try to cover every possible configuration scenario, it's probably assumed that if you're doing something more advanced like moving a folder out of the web root that you're happy configuring the rest of the server to allow it to happen.

---
Tags: configuration
---


# Question
Title: Unable to get variable facebook_publication_id, it is not defined
I am using Facebook Autopost module for drupal 7.

Following the instructions in from here, I went up with rules scheduler to delay posting of nodes to facebook by few minutes but it is not posting to facebook and showing

My current rule definition is:

```
{ "rules_facebook_post_delay_post" : {
"LABEL" : "Facebook Post delay post",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_switch_user", "rules_scheduler" ],
"ON" : { "node_update--article" : { "bundle" : "article" } },
"IF" : [
  { "NOT data_is" : {
      "data" : [ "node:field-category:0" ],
      "op" : "IN",
      "value" : { "value" : {
          "17" : "17",
          "19" : "19",
          "26" : "26",
          "27" : "27",
          "20" : "20",
          "15" : "15",
          "18" : "18",
          "24" : "24",
          "23" : "23",
          "22" : "22",
          "16" : "16",
          "21" : "21",
          "14" : "14",
          "25" : "25"
        }
      }
    }
  },
  { "NOT data_is_empty" : { "data" : [ "node:field-media-new" ] } },
  { "node_is_published" : { "node" : [ "node" ] } }
],
"DO" : [
  { "rules_switch_user_action_switch_to" : { "account" : [ "node:author" ] } },
  { "schedule" : {
      "component" : "rules_post_to_facebook_rule",
      "date" : { "select" : "node:changed", "date_offset" : { "value" : 1 } },
      "param_fb_article_post_rule" : [ "node" ]
    }
  },
  { "rules_switch_user_action_switch_back" : [] }
]

```

} }

And current rule component definition is:

```
{ "rules_post_to_facebook_rule" : {
"LABEL" : "Post to Facebook Rule",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules_switch_user", "rules", "fb_autopost_entity" ],
"USES VARIABLES" : { "fb_article_post_rule" : { "label" : "Post to Facebook Article compoent", "type" : "node" } },
"DO" : [
  { "rules_switch_user_action_switch_to" : { "account" : [ "fb-article-post-rule:author" ] } },
  { "entity_create" : {
      "USING" : {
        "type" : "facebook_publication",
        "param_type" : "link",
        "param_user" : [ "fb-article-post-rule:author" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-link" ],
      "value" : "[node:url_www]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-picture" ],
      "value" : "[node:mdm_facebook_picture]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-description" ],
      "value" : "[node:mdm_facebook_description]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-message" ],
      "value" : "[node:mdm_facebook_message]"
    }
  },
  { "variable_add" : {
      "USING" : { "type" : "integer", "value" : "105777439461526" },
      "PROVIDE" : { "variable_added" : { "fb_pub_id" : "FB Publication ID" } }
    }
  },
  { "publish_to_facebook" : {
      "USING" : { "publication" : [ "entity-created" ], "pages" : "105777439461526" },
      "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:facebook-id" ],
      "value" : [ "facebook-publication-id" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } },
  { "entity_fetch" : {
      "USING" : { "type" : "node", "id" : [ "fb-article-post-rule:nid" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "rules_switch_user_action_switch_back" : [] }
],
"PROVIDES VARIABLES" : [ "fb_article_post_rule" ]

```

} }

I have also used rules switch user to switch users based on posted author so that this anonymous issue during cron run can go but not working for me as facebook publication id and facebook authentication is not working for me.

# Answer
Ok the problem was I set value incorrectly in rules component. Instead of \[node:url\_www\] it should had been \[fb-article-post-rule:url\_www\] which was causing facebook authentication issue as there was no link to post to facebook what is defined in their facebook app.
> 0 votes

---
Tags: 7, rules, social-network
---


title: Get node URL path using entity query

text:
# Question
Title: Get node URL path using entity query
I want to get a node path/URL via entity query. So far I've managed to fetch the title of the node.

```
$facultyPostings = $query->get('node')
  ->condition('status', 1, '=')
  ->condition('type', 'careers')
  ->condition('field_career_directory', 'Faculty Postings', '=')
  ->sort('created')
  ->execute();

foreach ($facultyPostings as $key => $careers) {
  $careersNode = _nodeLoad($careers);
  $variables['faculty_postings'][$key]['title'] = $careersNode->get('title')->value;
  $variables['faculty_postings'][$key]['path'] = $careersNode->get('path')->value;
}

```

# Answer
> 7 votes
It depends on what you want to generate. To get the \Drupal\Core\Url object for the node:

```
$node->toUrl();

```

To get a URL string:

```
$node->toUrl()->toString();

```

To get a \Drupal\Core\Link object:

```
$node->toLink();

```

To get an HTML string for the link:

```
$node->toLink()->toString();

```

`toLink()` can optionally take an argument providing a different node link. For example, the following can be used to get a link to the node edit page;

```
$node->toLink('edit-form');

```

Or to the delete page:

```
$node->toLink('delete-form');

```

The values that can be passed to `toLink()` can be determined by looking at keys of the `links` section of the annotation for the entity type. The node class lists these as:

```
*  links = {
*    "canonical" = "/node/{node}",
*    "delete-form" = "/node/{node}/delete",
*    "delete-multiple-form" = "/admin/content/node/delete",
*    "edit-form" = "/node/{node}/edit",
*    "version-history" = "/node/{node}/revisions",
*    "revision" = "/node/{node}/revisions/{node_revision}/view",
*    "create" = "/node",
*  }
?>

```

# Answer
> 1 votes
Once you get the node id you can retrive it via

```
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);

```

---
Tags: 8, entities, uri
---


# Question
Title: Attaching libraries to specific controllers
I want to include the google charts js library to a specific (or set of) controller(s). In my library file, `gcharts.libraries.yml`, I have the following:

```
google_charts:
  remote: https://developers.google.com/chart
  version: current
  license:
    name: apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0
    gpl-compatible: true
  js:
    https://www.gstatic.com/charts/loader.js: { type: external, minified: true }
  dependencies:
    - core/jquery

```

Which, unless I copied something incorrectly, should be correct.

***Question 1***: is the `dependencies` tag allowed here? The documentation isn't expressly clear on that.

---

My controller (`GoogleChartsController`) correctly instantiates and looks like:

```
<?php
array(
  '#theme' => 'custom_theme',
  '#attached' =>
    array(
      'library' =>
        array('company/google_charts')
    ),
  // For testing purposes
  '#cache' => array(
    'max_age' => 0,
  )
);
?>

```

However, when I look through the source I don't see the library that I told my controller has a dependency for. My library never loads.

***Question 2***: Do I have *have* to use the `hook_page_attachement` or the `hook_preprocess_page` hooks? If so, how do I limit it to use just my set of controllers I want (I don't need or want this loading on every page)? Can I get the path, check to see that it is what I want and then add it conditionally, like so? Or is there some other way?

---

My `custom-theme.html.twig` looks like:

```
<div id="testing-div">Are we here?</div>
<!-- inflate chart here -->
<div id="chart-div"></div>

```

The documentation isn't crystal clear as to when and where to include inline js. From the google charts api, I'm to include something like:

```
<script type="text/javascript">
  // Load the Visualization API and the piechart package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);
  // issue google charts api call to inflate chart at "chart-div"
  // omitted rest for brevity
</script>

```

Now, my intuition is that I can actually abstract each of the charts I want into their own "library" and add the dependency, because of the way I designed things, this will be fairly trivial. But I'm not certain if this is the best way to do it. But I've read that you *can* dump inline js into twig files; but I'm not 100% certain this applies here...

***Question 3***: Is adding the js into twig best practices or is libraries the way to go? Assuming libraries, can I include several libraries into one library file and just include the one(s) that I want/need? So I would have one library for `customized_charts.libraries.yml` and in there there would be declarations for `pie_chart`, `bar_chart`, etc. And then I would load `module/bar_chart` when I wanted to display bar charts, etc?

# Answer
You are not indenting parts of the yml file that you need to indent.

Look at this example from token.libraries.yml at /modules/contrib/token/token.libraries.yml:

```
jquery.treeTable:
  remote: 'http://plugins.jquery.com/treetable/'
  version: 3.2.0
  license:
    name: MIT
    url: https://github.com/ludo/jquery-treetable/blob/3.2.0/MIT-LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery.treetable.js: {}
  css:
    component:
      css/jquery.treetable.css: {}
      css/token.treetable.theme.css: {}
  dependencies:
    - core/jquery

```

Also, pay attention to colons, since they are part of YAML syntax.

use:

```
remote: 'remote: https://developers.google.com/chart'

```

not

```
remote: remote: https://developers.google.com/chart

```
> 2 votes

# Answer
To answer two of your questions:

> Question 2: Do I have have to use the hook\_page\_attachement or the hook\_preprocess\_page hooks?

No, you can attach libraries to a controller.

> Question 3: Is adding the js into twig best practices or is libraries the way to go?

It's not a good practice to add JS into a template. It should be added to whichever render array represents the data the script belongs to.
> 1 votes

---
Tags: 8, javascript, charts
---


title: Path to translated content of a node

text:
# Question
Title: Path to translated content of a node
I need to find the url path to the translated node of a page , the Multilink Module seems to do just this, is there something similar for Drupal 8? How do I find the path to the translation of a node in Drupal 8?

thanx for your help

# Answer
I believe you can use:

```
$japanese_node = $node->getTranslation('ja');
$japanese_link = $japanese_node->toUrl()->toString();

```

Adjust accordingly.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How to add css classes into a specific image field in responsive edit mode
I have created a custom content type that has an **image field** which is required for each of this node type.

It works well in desktop mode. But not so in **responsive mode**.

So when a person is editing a node of that type **in a smartphone of tablet**, the **select image button** changes to a simple text "Attach a file". And nothing clearly indicates the user that it is a button.

**So I want to edit my css in order to change the view of that text to a button when the screen comes to responsive mode**.

**The question is : What it the class or ID that that I must access to do that ?**

Can you help me ?

# Answer
Create a simple custom module to alter the image field, To add a class or any other changes.

```

function MYMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'page_node_form') {
    //Adds a class to 'my image' field in the node edit form of content-type page.
    //print_r($form);
    $form['field_my_image']['#prefix']=''; //div class="myclass_name"
    $form['field_my_image']['#suffix']='';//Close div here
    //OR
    $form['field_my_image']['#attributes']['class'][]='myclass_name';
  }
}

```

Then use media queries for class 'myclass\_name' in your CSS file.
> 0 votes

---
Tags: nodes, entities, media, theming
---


# Question
Title: How do I render the block login on the front page?
I start making my own custom theme and I want to add the login page in mytheme, if the user is not logged-in; then show the block login on the front page.

How to render a block for the login in Drupal 7?

# Answer
> 2 votes
Themes should not directly render blocks on its own, nor have an hard-coded list of blocks to render. Drupal provides a configuration page on admin/structure/block, which allows to set which blocks show for every every theme, and in which region.

>

The cases are two:

* The theme is used only on your own sites, or the ones you maintain. In this case, you can simply use the UI to set the blocks to show for that theme. If you need to enable the same blocks on different sites, and manually setting them for each site would be prohibitive, you can export the list of blocks as a feature, and import it for every site you need. (It requires the Features module.)
* Everybody can download the theme and use it. In this case, having a theme that renders blocks without giving the possibility to the users to select if rendering them can create an issue in at least two cases:

+ The user that can administer the blocks already selected the login block to be shown in a specific region. If the theme is always rendering the login block, users would see two login blocks.
    + The administrator user selected the theme as administrative theme, where trying to show the login block doesn't probably make sense. (The administrative theme is normally shown to logged-in users, for which the login block is never shown from Drupal.)

That said, you could render the login block from a template file using the following code.

```
$block = module_invoke('user', 'block_view', 'login');
print render($block['content']);

```

An installation profile (and a distribution) can enable blocks for a theme. See what the Standard profile does in `standard_install()`. (I edited the code to show a shorter list of blocks.)

```
  // Enable some standard blocks.
  $default_theme = variable_get('theme_default', 'bartik');
  $admin_theme = 'seven';
  $blocks = array(
    array(
      'module' => 'user',
      'delta' => 'login',
      'theme' => $default_theme,
      'status' => 1,
      'weight' => 0,
      'region' => 'sidebar_first',
      'pages' => '',
      'cache' => -1,
    ),
    array(
      'module' => 'system',
      'delta' => 'navigation',
      'theme' => $default_theme,
      'status' => 1,
      'weight' => 0,
      'region' => 'sidebar_first',
      'pages' => '',
      'cache' => -1,
    ),
    array(
      'module' => 'system',
      'delta' => 'powered-by',
      'theme' => $default_theme,
      'status' => 1,
      'weight' => 10,
      'region' => 'footer',
      'pages' => '',
      'cache' => -1,
    ),
  );
  $query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
  foreach ($blocks as $block) {
    $query->values($block);
  }
  $query->execute();

```

Using code similar to that, a module or an installation profile can enable any block, knowing which module implements that block. Of course, 'theme' needs to be the machine name of the theme, so you need to change it to match the machine name of your theme.

Creating a distribution is an alternative of using features. I would suggest either one of them over having a theme that renders blocks on its own.

# Answer
> 2 votes
If you want to do it using admin panel -

The Drupal block for signing in and signing up are the same. In the blocks area of the admin, the block is titled: "User login"

You could assign it to only show up on (for the front page), and move it to whatever region you want.

---

You can render user login block with php using -

```
print(drupal_render(drupal_get_form("user_login"));

```

Got it from https://stackoverflow.com/questions/18194414/display-login-block-and-registration-block

Or if you want to do it using template.php there refer Programatically retrieve a block and print it in a page

Though not exaclty what you wanted but you can render login block the same way described in above url:)

---
Tags: 7, theming
---


# Question
Title: twig to print paragraph field in controller
new to d8. I have a result page where I need to print the field values of a paragraph field into my controller. The paragraph field is called `field_classrooms`.

text values print fine for example
`{{ teacher.field_last_name.value }}`

but when I need to print
`{{ teacher.field_classrooms.value }}`

I get

> User error: "target\_id" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

# Answer
> 6 votes
You have to get the paragraph entity with `.entity`

```
{{ teacher.field_classrooms.entity.field_in_paragraph.value }}

```

where you can get the fields inside of the paragraph.

# Answer
> 0 votes
I came accross the same issue while trying to add paragraph field content manual in simplenews email twig template

I too did not find a way to use one twig statement so i used a loop...

Check how many values we have in paragraph

`{{ teacher.field_classrooms|length }}`

Getting 1st value of paragraph field

`{{ teacher.field_classrooms[0].entity.field_in_paragraph.value }}`

And this is how I used it finally: Loop trough paragraph items

`{% for entity in teacher.field_classrooms %}
 {{ teacher.field_classrooms[loop.index0].entity.field_in_paragraph.value }}
{% endfor %}`

---
Tags: theming, 8
---


# Question
Title: How can I modify pagination to restrict shown page numbers?
I have a pagination for list of articles within a Drupal site e.g.:

```
<<first <previous ... 3 4 5 6 7 8 9 10 11 ... next> last>>

```

So at the moment there are always nine page links shown. Basically I want to find out how to modify this so there are (for example) only five links and the text for labels for the controls in the pager like this:

```
<< < ... 6 7 8 9 10 ... > >>

```

I wrote this code with not result:

```
/**
 * Implements template_preprocess_pager().
 */
function MYTHEME_preprocess_pager(&$variables) {
  $variables['quantity'] = 5;
  $variables['tags'] = ["«", "‹", "›", "»"];
}

```

# Answer
It would seem that at the point you're trying to modify the quantity, the pager items have already been generated so your quantity value doesn't have any effect.

Similar to Drupal 7, I believe you're going to need to implement the full pager function, just copying the core pager function to your theme and changing the quantity.

```
function MYTHEME_preprocess_pager(&$variables) {
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = 5; // hardcode your quantity here
  global $pager_page_array, $pager_total;

  // Nothing to do if there is only one page.
  if ($pager_total[$element] <= 1) {
    return;
  }

  $tags = $variables['tags'];

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  // Create the "first" and "previous" links if we are not on the first page.
  if ($pager_page_array[$element] > 0) {
    $items['first'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, 0),
    );
    $items['first']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[0])) {
      $items['first']['text'] = $tags[0];
    }

    $items['previous'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
    );
    $items['previous']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[1])) {
      $items['previous']['text'] = $tags[1];
    }
  }

  if ($i != $pager_max) {
    // Add an ellipsis if there are further previous pages.
    if ($i > 1) {
      $variables['ellipses']['previous'] = TRUE;
    }
    // Now generate the actual pager piece.
    for (; $i <= $pager_last && $i <= $pager_max; $i++) {
      $options = array(
        'query' => pager_query_add_page($parameters, $element, $i - 1),
      );
      $items['pages'][$i]['href'] = \Drupal::url('<current>', [], $options);
      if ($i == $pager_current) {
        $variables['current'] = $i;
      }
    }
    // Add an ellipsis if there are further next pages.
    if ($i < $pager_max) {
      $variables['ellipses']['next'] = TRUE;
    }
  }

  // Create the "next" and "last" links if we are not on the last page.
  if ($pager_page_array[$element] < ($pager_max - 1)) {
    $items['next'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
    );
    $items['next']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[3])) {
      $items['next']['text'] = $tags[3];
    }

    $items['last'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_max - 1),
    );
    $items['last']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[4])) {
      $items['last']['text'] = $tags[4];
    }
  }

  $variables['items'] = $items;
}

```
> 4 votes

# Answer
With Drupal 8 it's just a simple setting. You can change the number of pages shown (defaults to 9).

Structure \> Views \> Select your view

Click edit

It's in the center options area.
> -1 votes

---
Tags: 8, paging
---


title: Creating multiple temporary sites

text:
# Question
Title: Creating multiple temporary sites
I have to evaluate multiple different third-party modules. I figured the easiest way to evaluate each one would be to create a site featuring one module at a time so nothing could possibly conflict.

Is this efficient? If so, what would be the fastest way I could do this without going through the Drupal 8 installation process tons of times?

I'm running Fedora 25 with Apache, and Drupal 8.3.5.

# Answer
I think too that the easier way is using simplytest.me, which allows to install more than one module and apply patches. (Click on *Advanced options*, which at first sight could not seem clickable.)

>

Consider that:

* As of July, 2017, simplytest.me runs on Ubuntu and PHP 5.5.12-2ubuntu4.4
* Some PHP extensions aren't installed, so some Drupal modules cannot be installed (e.g. the LDAP module)
* As of March, 2017, it uses the Composer Manager module, so it can install any Composer requirements a module has
* Some distributions, like OpenChurch, fail to install

If you don't need to have a fine control over the environment, simplytest.me is perfect for testing modules and combination of modules. It is surely faster to test modules on simplytest.me than using a virtual machine on your computer. The second option has the pro of allowing you to better control what you install at server level, and it helps if you need to reproduce more accurately the production server you are using.

The site is being ported to Drupal 8. You can see the progress on https://new.simplytest.me/. I am not sure it can be used for extended test of modules.

### Reference
> 1 votes

---
Tags: 8
---


# Question
Title: Really really need help debugging this dpm(). It's an error from trying to create a new Message | Fixed by reinstalling Reply module
The Message module was working fine but I noticed one of the messages wasn't getting created by Rules. I suspect it's due to locale being enabled recently and creating with the UI gives this error.

For message types where I haven't created a different language, it seems to work fine.

2 errors in log:

```
Warning: array_flip(): Can only flip STRING and INTEGER values! in EntityAPIController->load() (line 219 of /usr/share/nginx/html/sites/all/modules/entity/includes/entity.controller.inc).

```

.

```
EntityMalformedException: Missing bundle property on entity of type message. in entity_extract_ids() (line 7930 of /usr/share/nginx/html/includes/common.inc).

```

The relevant lines in common.inc are:

```
// Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
        dpm($info);// My dpm
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }

```

You can see where I added dpm(). `$entity` is empty but `$info` gives the below screenshot.

Any pointers for someone who just isn't used to debugging things like this? I've deleted every message in on the site with VBO but the error persists.

After two and half years of dev, this site was supposed to go into a proper beta next week in a friend's business but the entire UI relies on the Message module. :/

And here is a dpm of the ids for the flipping error.

Any help appreciated. I didn't expect it to all fall apart this weekend.

Edit: Closed as it is indeed a duplicate. I don't have the skills to deal with it so will just rewrite to use node functionality instead.

Edit 2: Calmed my head today and looked at things that weren't my own code. Turns out it was the Reply module which I use on Message. Reinstalling it gets rid of the errors. I don't know why it happened. It's been a part of Message for like a year during development.

# Answer
> 1 votes
Exception `EntityMalformedException` is triggered, because (as you mentioned) your `$entity` is empty, and based on `$info['entity keys']['bundle']` *Entity* module expects to have `$entity->type` property, but it doesn't exist.

You should check the backtrace and find which module is responsible for this invalid call, e.g. by adding this line instead of `dpm`:

```
var_dump(debug_backtrace()); exit; // Show the backtrace and exit.

```

in order to identify and fix the broken code. The most relevant part from the backtrace is `function` which is called, so starting from the top `[0]=>`, then `[1]=>`, so once you find the custom code or contrib module responsible for this exception. If there is no custom module apart of `messages` module, you should report this bug to the maintainer of this module.

Here is the related bug: Fatal errors when content types are deleted before messages are.

---

For further explanation, check: How to debug EntityMalformedException?

---
Tags: 7, entities
---


title: Admin menu disappearing

text:
# Question
Title: Admin menu disappearing
I'm running `Drupal 7.54` and for some strange reason my admin menu on top disappears. This happens sporadically, no telling what's going to happen next. I've done some searching and found

```
$conf['admin_menu_cache_client'] = FALSE;

```

I added this line of code to the `settings.php` file and that didn't help.

I was wondering if anyone else had experienced the same problem and tried any solutions.

below is the javascript error

```
GET https://www.nokidhungry.org/modules/comment/comment.css?otg3j2
smiah:18 Uncaught TypeError: Cannot read property 'prototype' of undefined
    at HTMLDocument.<anonymous> (js_lfuW81Xw_ijrPfg5E_XWjUDemAzqGwWRZunpwj_BL20.js:1032)
    at c (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at Function.ready (jquery.min.js:4)
    at HTMLDocument.q (jquery.min.js:4)
    at HTMLDocument.nrWrapper (smiah:18)
(anonymous) @ js_lfuW81Xw_ijrPfg5E_XWjUDemAzqGwWRZunpwj_BL20.js:1032
c @ jquery.min.js:4
fireWith @ jquery.min.js:4
ready @ jquery.min.js:4
q @ jquery.min.js:4
nrWrapper @ smiah:18

```

I think the error below is causing the issue and I don't know how to get rid of it.

# Answer
> 1 votes
Here's a checklist of things to look at:

* Drupal simply concatenates files during aggregation. Malformed scripts may cause the entire thing to blow up. Disable aggregation first to see the code in plain so it's easier to debug.
* Aggregation can also lead to some weird issues together with caching. Ensure that you've refreshed the cache for both Drupal, browser and any external file systems (i.e. S3) to ensure that you're working with updated code and content.
* Malformed CSS, believe it or not, can also cause aggregation to blow up. Chrome does not show any error of this happening. However, Firefox prints a warning if it does. Debug in Firefox to see some errors not shown by Chrome.
* If you're using S3 for storage, ensure that all of your resources are present. Sometimes, the file may not be accessible from S3, fail to upload to S3, or just be missing (i.e. deleted accidentally).
* You already mentioned disabling admin menu caching. That has solved this problem for me in two projects.
* Clear all caches (`drush cc all`). Always worked. :D

---
Tags: 7
---


# Question
Title: How to format an integer field as Date/Time using Views module
I created a custom Entity with one of the properties named 'created' and set with the Drupal `REQUEST_TIME` in seconds. I want to display this property using the Views module as a formatted Date/Time field. The Date/Time format option is not offered on the Views field settings dialogue.

# Answer
> 1 votes
Implement `hook_entity_property_info_alter()` to describe your custom entity type's properties to the Entity API module, which will then automatically create Views integration based on the types of fields in your database table.

http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.api.php/function/hook\_entity\_property\_info\_alter/7

An example of this can be found in the Log module, which has three timestamps (timestamp, created, and changed). It gives each of these a "type" of "date" in the entity property info, which automatically makes them visible to Views as date fields. http://cgit.drupalcode.org/log/tree/log.module#n242

---
Tags: 7, views
---


# Question
Title: What parts go under source code version control?
I am wondering what the best practices are for putting Drupal code under version control. I'll be mostly using core and standard Drupal modules. I'll be developing a custom theme, and one or two custom modules.

As far as I see it, I have 3 options:

1. Put the entire Drupal folder under version control. Developers can directly check out the folder in the Apache htdocs folder and go from there.
2. Check in only my custom code (modules + themes). Developers checkout the code in the appropriate folders.
3. Set up something like Docker.

# Answer
There are different ways to approach this, depending on what you need. The easiest approach is the one you described in #1 (Put the entire Drupal folder under version control).

That allows you to easily checkout the full working copy of the codebase with just Git. The downside is that you are storing a lot of code in your Git repo which already exists in other Git repos (ie: Drupal core, contrib modules, etc).

With Drupal 8, the community is generally moving towards using Composer for managing dependencies and building the Drupal codebase. Then, you only need a composer.json file (which points to specific versions of Drupal core and contrib projects), and your custom code in the Git repository. More information: https://www.drupal.org/docs/develop/using-composer/using-composer-with-drupal

Another option is to create an installation profile, and use Drush Make. This method is deprecated in favor of Composer in Drupal 8, but still works nicely for Drupal 7 projects. This is better suited to common code/configuration that you might use to set up lots of similar sites, rather than one highly-customized and specific site.

Regarding Docker - that's sort of a separate decision. You'll still need to choose one of the above options, and then build the codebase accordingly inside the Docker container (or mount it in a volume).
> 3 votes

# Answer
You should build with Composer as it is the recommended approach. Even Drush recommends installing Drush via composer, on a per-project basis. drupal-composer is a good starter which pretty much sets up an ideal Drupal setup. Drupal and all your modules are defined as Composer dependencies.

What you check in depends more on your workflow than anything else.

* If you deploy to services like Acquia, Pantheon, OpenShift or some other PaaS where your repo *is* your web root or has limited deploy scripting, then you have no choice but to check in everything. It's pretty straight-forward, but also the least flexible.
* If you run a build server, then drupal-composer's default setup is ideal for this. You only check in *your* code (modules, themes, libs). On each commit, have the build server pull in dependencies, process code, package artifacts, and send them off.

This setup is great if your workflow involves one or more of the following:

+ You're doing CSS/JS pre-processing (i.e. SCSS, ES modules). You commit the manifest (i.e. `package.json`, `bower.json`) and the raw files and the server does the building for you.
    + You're dealing with custom environments (i.e. AWS) that need special deployment procedures.
    + Your environments are containers spawned from images from a registry (i.e. Docker Hub). Build server builds the images for you.

Docker has nothing to do with how you commit code. However...

If you're simply building themes/modules and your repo setup is like the project repos found in Drupal.org (where the module/theme is the only thing in the repo), you could use the official Drupal Docker image for development. Simply run a container, mount the project directory as a directory in modules/themes, enable the module/theme, and start writing code. No Drupal core code will exist on the host nor the repo, only your module/theme.
> 1 votes

---
Tags: 7, version-control
---


# Question
Title: Date display differences in node templates
In a node template, if I use the following:

```
{{ content.field_event_start_date }}

```

The correct localized date and time will be displayed. For example:

Tuesday, February 14, 2017 @ 9:00am EDT

However, if I only want to display the time part and use the following:

```
{{ node.field_event_start_date.value|date("g:ia") }}

```

The incorrect time is displayed:

1:00pm

There appears to be a +4h offset when using the TWIG date() filter.

Drupal's Timezone is set to "America/New York".

How can I display only the time part so that it correctly displays the following?

9:00am

Also, can you please explain what conversion Drupal is performing on the time under the covers?

Thank you.

# Answer
> 3 votes
The proper thing to do here is to configure your field output to use the proper formatter. On the **Manage Display** for your content type, eg admin/structure/types/manage/page/display, change the formatter for your `field_event_start_date` field to **Custom**, then click on the gear and change the format to 'g:ia'. You should then be able to use `{{ content.field_event_start_date }}` in your template.

The standard Twig `date()` filter doesn't use the `date.formatter` service, so timezones and localization settings will not be honored.

`TwigExtension` defines a custom filter for Drupal that will call out to `DateFormatter::format()` called `format_date()`. This should work

```
{{ node.field_event_start_date.value|format_date("custom", "g:ia") }}

```

This apparently only works for Timestamp fields and not datetime or daterange fields.

# Answer
> 0 votes
You can preprocess your node in THEME.theme (or in a module if you prefer, note that my field is 'field\_date' you will need to adapt to your field machine name).

I copy the field using another display formatter. I'm using datetime\_custom formatter, but you can use whatever you want.

```
function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Extract the hour from the field_date so we can easily display concert_time
  if(!empty($node->field_date)){
    $variables['concert_time'] = $node->field_date->view([
      'type' => 'datetime_custom',
      'settings' => ['date_format' => 'H:i'],
    ]);
  }
}

```

Then in your twig

```
{{ concert_time }}

```

---
Tags: theming, 8
---


# Question
Title: How to run entity field query in cron without getting undefined stdClass::$roles notice?
I've got a cron job which executes an **entity field query** to count the number of some nodes associated with a user (for each user in the system). Whenever this runs I get the following in the watchdog logs:

> Notice: Undefined property: stdClass::$roles in user\_access() (line 820 of \[…\]/Drupal/modules/user/user.module).

Is there anything specific I need to do to avoid this happening (not involving changing log levels or otherwise ignoring the issue)? Any particular best practices when using Drupal queries outside the context of a "real" session? The reason I'm doing this is to get rid of any spurious noise in the logs, and reduce the chance of breaking things in case of change to both my own and Drupal code.

Query code:

```
$q = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $content_types, 'IN')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $uid)
    ->propertyCondition('type', $content_types, 'IN')
    ->fieldCondition('field_something', 'value', $code, '=');

$award_count = $q->count()->execute();

```

Stack trace:

```
[…]/Drupal/modules/node/node.module(3334): user_access('bypass node acc...', Object(stdClass))
[…]/Drupal/modules/node/node.module(3296): _node_query_node_access_alter(Object(SelectQuery), 'entity')
[…]/Drupal/includes/module.inc(1163): node_query_entity_field_access_alter(Object(SelectQuery), NULL, NULL, NULL)
[…]/Drupal/includes/database/select.inc(1253): drupal_alter(Array, Object(SelectQuery))
[…]/Drupal/includes/database/select.inc(1261): SelectQuery->preExecute()
[…]/Drupal/includes/database/select.inc(1275): SelectQuery->preExecute()
[…]/Drupal/includes/entity.inc(1389): SelectQuery->execute()
[…]/Drupal/modules/field/modules/field_sql_storage/field_sql_storage.module(652): EntityFieldQuery->finishQuery(Object(SelectQuery), 'entity_id')
[internal function]: field_sql_storage_field_storage_query(Object(EntityFieldQuery))
[…]/Drupal/includes/entity.inc(1216): call_user_func('field_sql_stora...', Object(EntityFieldQuery))
[…]/[my code path]: EntityFieldQuery->execute()

```

Running Drupal 7.56.

# Answer
> 1 votes
As you can see in the cron doc, cron runs as anonymous user so you have to run the query as admin user.

In the EntityFieldQuery DO doc you can see examples, but essentially you just need to add the addMetaData code to the end of your query:

```
 $q = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $content_types, 'IN')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $uid)
    ->propertyCondition('type', $content_types, 'IN')
    ->fieldCondition('field_something', 'value', $code, '=')
    // Run the query as user 1.
    ->addMetaData('account', user_load(1));

```

---
Tags: 7, database
---


# Question
Title: Javascript & Ajax failed to load on many pages like field editing & views editing pages.
The site I'm managing is runs by Drupal 7.53 with many contributed modules.

I don't know what happened from yesterday, ajax queries in field editing pages and views editing pages throwing errors or not loading at all. Clearly I can see what is causing this error in JQuery and Ajax. All the modules installed are contributed modules except one custom module, which doesn't have any Javascript code in it. Cleared the cache few times . No javascript and CSS aggregation. But still wherever JQuery & Ajax is needed , the pages are breaking . How can I solve this problem. How can I figure out what is causing problem?

I'm unable to alter any of the views due to ajax error throwing up. All help is appreciated.

# Answer
Jquery Update module is very helpful but new jquery versions can cause issues with other dependent modules. The module is important not only to keep your site up to date but also allow for theme-specific control to ensure compatibility. So the module's settings page is something you might want to visit and test when a new jquery version is released.

Also, the CDN option can cause load issues if the provider you choose is offline for some reason or overloaded. From the jquery update settings warning:

> "NOTE: Using one of the "CDN Provider" options below is the preferred method for loading Bootstrap CSS and JS on simpler sites that do not use a site-wide CDN. Using a "CDN Provider" for loading Bootstrap, however, does mean that it depends on a third-party service."

So use this option with caution.
> 1 votes

---
Tags: 7, javascript, ajax
---


# Question
Title: Value modified with form_alter revert after check_cache
Using Drupal 7.x. Not much experience with Drupal.

I have a core form in which I need to append some data to a field after it's been submitted by the site visitor. I have found I can alter the submitted data with a form\_alter function added to my own custom module. It works fine as far as that, but after the "prepare", $check\_cache reverts values.

Is there a way to make this work?

Is there a way to manipulate the "uncacheable keys" to include my item?

Is there a different way to massage submitted data other than hacking the code?

Any other suggestions?

# Answer
> 0 votes
Submitted form values are stored in $form\_state\['values'\], and can be modified in a custom validation function.

So in your custom module, implement hook\_form\_alter() and add a validation function:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'id_of_form_to_alter') {
    $form['#validate'][] = 'mymodule_custom_form_validate';
  }
}

/**
 * Custom form validation handler.
 */
function mymodule_custom_form_validate(&$form, &$form_state) {

  // Append value to submitted field.
  if (!empty($form_state['values']['myfield'])) {
    $form_state['values']['myfield'] .= ' append this string';
  }
}

```

# Answer
> 0 votes
> `form_set_value()` used to change submitted form values during form validation.

Please use `form_set_value()` instead of using `$form_state['values']`

Always look for the best practice. Good luck!

---
Tags: 7, forms
---


# Question
Title: Default Field Value based on another referenced field
I am now learning drupal 8 and I am struggling about 2 weeks to find an answer to this. I am trying to give to a reference field of the comment a default dynamic value. This value is the same with the referenced field of the article that the comment belongs. There are 2 ways to do this:

1) The easiest and cleaner way is to create a view that will show the specific article's field value that the current comment belongs. Easy but the issue is that although the view has only one result, that result cannot be set as default value. The user has to choose it or type in the autocomplete box in order for the value to appear. Is there any way to make that field been automatically completed and make it hidden? I would like the user not to be aware of that field

2) Here is another solution more difficult to me. https://www.drupal.org/node/1797100#comment-11792569 I should create a text widget for my field. I tried this but it is not working. The field has been created from the dashboard. I would like to keep things as cleaner as possible and not to create the field from the beggining with code. I believe that the text base,text widget and text formatter have already been created by core and that's why my text widget is not working. Should I in this case override (alter) the text widget and not create a new one and if yes how could I do that? https://api.drupal.org/api/drupal/core!modules!field!field.api.php/function/hook\_field\_widget\_form\_alter/8.2.x

`function hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
 // Add a css class to widget form elements for all fields of type mytype.
 $field_definition = $context['items']->getFieldDefinition();
 if ($field_definition->getType() == 'mytype') {
 // Be sure not to overwrite existing attributes.
 $element['#attributes']['class'][] = 'myclass';
 }
}`

where should I place the above function?

If you have an answer to 1) or 2) please leave a comment, I am totally desperate as this is very basic for the functionality of my website and I cannot find a solution...

Thank you

# Answer
> 1 votes
You can use a hook\_ENTITY\_TYPE\_create() to prepopulate comment fields with data from the parent entity:

```
  function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
    $node = $comment->getCommentedEntity();
    if ($node && $node instanceof \Drupal\node\NodeInterface) {
      if ($node->hasField('field_example')) {
        $comment->subject->value = $node->field_example->value;
      }
    }
  }

```

---
Tags: 8, forms
---


title: Incorrect time is displayed on the site

text:
# Question
Title: Incorrect time is displayed on the site
I just noticed that incorrect time is being displayed in my website. The time is 6 minutes lagging from the correct time.

For example:

* The current time in Japan/Tokyo is 4:07 PM Saturday, July 22, 2017 (GMT+9)
* The current time as per website is 4:01 PM Saturday, July 22, 2017 (GMT+9)

Any guess? Why is it happening? how to fix it?

# Answer
> 3 votes
Server time? Run the date command on your server if you have cli access or check it in your cPanel.

---
Tags: 7, datetime
---


# Question
Title: How to use a terminate kernel event to log page access statistics?
In Drupal 7 `hook_exit` is implemented in the *Statistics* module to gather statistics for page accesses. This change record suggest the equivalent in Drupal 8 is to listen for kernel.terminate events. Here's my code:

*/mymodule/mymodule.services.yml*

```
services:
  mymodule.page_exit:
    class: Drupal\mymodule\EventSubscriber\PageExit
    tags:
      - {name: event_subscriber}

```

*/mymodule/src/Event/Subscriber/PageExit.php*

```
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;

class PageExit implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::TERMINATE][] = array('logAccess');
    return $events;
  }

  /**
   * Call this method whenever the KernelEvents::TERMINATE event is dispatched.
   */
  public function logAccess(PostResponseEvent $event) {

    // $access_info = $event->getRequest()

    \Drupal::database()->insert('mymodule_table')
      ->fields(array(
        'hostname' => '?',
        'referrer_url' => '?',
        'timestamp' => REQUEST_TIME,
      ))
      ->execute();
  }
}

```

Currently, for a single page request, the method `logAccess` gets called five times. I'm interested in logging the hostname and referrer url of my page visitor, just once.

In essence, I'm trying to port some of this this Drupal 7 code from *statistics\_exit* in *statistics.module*:

```
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

// For anonymous users unicode.inc will not have been loaded.
include_once DRUPAL_ROOT . '/includes/unicode.inc';
// Log this page access.
db_insert('accesslog')
  ->fields(array(
    // 'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
    // 'path' => truncate_utf8($_GET['q'], 255),
    'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
    'hostname' => ip_address(),
    // 'uid' => $user->uid,
    // 'sid' => session_id(),
    // 'timer' => (int) timer_read('page'),
    'timestamp' => REQUEST_TIME,
  ))
  ->execute();

```

Any ideas?

# Answer
The comments you got are golden, my answer is along the lines of what @IvanJaros suggested, but follows a simpler approach. And take care to check the case of external caching (if any is in play).

The following should make your current approach work.

```
public function logAccess(PostResponseEvent $event) {

  $request_format = $event->getRequest()->getRequestFormat();

  if ($request_format === 'html') {
    // \Drupal::database()->
  }
  else {
    // Do other stuff.
  }
  ...

```

This snippet tries to detect requests with the `html` format (i.e. page requests) and will ignore other ones, like e.g. application/json.

Good luck!
> 0 votes

---
Tags: 8, nodes, event-subscribers
---


# Question
Title: How do I migrate from a site using a core version to another one using the same version?
I like to change the web-hosting provider. I want to remove un-necassary and useless stuff (e.g. modules, content types that aren't used from the site).

I have no idea how to do this. Is there a module for migrating only stuff which is in use? The migration modules I found only consider migration from previous versions to Drupal 8, not from Drupal 8 to Drupal 8.

# Answer
For migration of configuration, use *Configuration Management* in Drupal 8 core.

For content, you can use the following approaches:

There are other services which can help you with content staging such as:

Related:
> 0 votes

# Answer
Why don't you just uninstall those modules and remove the configuration you no longer need?

Migration is a complicated task that requires a lot of work.

And to switch the webhost, you just need to copy the files and database, no need to mix those two things together. Clean up your site first and then switch the host. Otherwise you'll never be sure if a problem is caused by the host change or changed configuration
> 0 votes

---
Tags: migrations
---


# Question
Title: How to get product variation of a single product in view
Let's assume I have a product named A, B, C and each of those products have variations.

Now, when I am making a block in views, when I only have the option to select product variations as seen in this image:

After this, there seems to be no way to select a product variation of say product A.

All the variations are there by default.

# Answer
You need to add a context to tell the view which product you want to show. Either from the URL with product id in url, or static product id number, or some other way.

The context filter for views relies on a url or some other way to set a value. In this case you want to select one of your products that has variations. So, if your url is /myproducts/1, the context filter can be set to use 1 for the product id and show only that product along with only its variations.

How to pass Views contextual filter via URL? https://i.stack.imgur.com/8cLtw.png

Use Provide default value from URL, then choose which part of the path will have the product id in it. Then when you link to this view, use the url that way.

On your index page view, you can make the links to products this way so it passes the product id to your page.
> 1 votes

---
Tags: 8, commerce
---


title: Could not open input file: drush

text:
# Question
Title: Could not open input file: drush
I have a relatively fresh instance of Ubuntu 16.04 running a Drupal 7 site, with php5.6 installed instead of php7. The drupal site runs well. I am trying to get drush installed so that I can easily do updates.

I have done the global install per http://docs.drush.org/en/8.x/install/

Specifically, as the ubuntu user (no root login)

wget http://files.drush.org/drush.phar

/usr/bin/php5.6 drush.phar core-status

PHP configuration : /etc/php/5.6/cli/php.ini PHP OS : Linux
Drush script : /home/ubuntu/drush.phar
Drush version : 8.1.12
Drush temp directory : /tmp
Drush configuration :
Drush alias files :

chmod +x drush.phar

sudo mv drush.phar /usr/bin/drush

/usr/bin/php5.6 drush --version

Could not open input file: drush

What am I missing?

# Answer
The only way I have found to fix this problem is to change the default php used by the server. In other words, /usr/bin/php was originally a symlink to /usr/bin/php7.1, and changing it to a symlink to /usr/bin/php5.6 solved the problem.

But it appears that drush will always use the default php even if you install it with an alternative.
> 0 votes

# Answer
The error you are getting when you run `/usr/bin/php5.6 drush --version` is because you are telling /usr/bin/php5.6 to execute the *drush* file present in the current directory, but since you moved it to /usr/bin, it cannot find it. PHP doesn't look for the file in the PATH.

To use a specific PHP version to run Drush you need:

* Set the *DRUSH\_PHP* environment variable to the filename of the PHP executable

+ bash

    ```
    DRUSH_PHP="/usr/bin/php5.6" drush --version

    ```
    + Other shells (e.g. fish, tcsh)

    ```
    env DRUSH_PHP="/usr/bin/php5.6" drush --version

    ```
* Tell PHP where to find the drush file

```
/usr/bin/php5.6 /usr/bin/drush --version

```

Basing on a comment given for Modifying the PHP or PHP configuration that drush runs under, it seems the most recent versions of Drush don't use the *DRUSH\_PHP* variable anymore.
> 0 votes

---
Tags: drush, installation
---


# Question
Title: Programatically render a block in a twig template
I need to render a views block in my page.html.twig template. In D7 I would do this:

```
<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print render($block['content']);
?>

```

In Drupal 8 module\_invoke is deprecated and recommended to use this: (I've added the block's name as the second parameter)

```
Drupal::moduleHandler()->invoke($block, 'views_block__blog_block_1', $args = array());

```

I tried a few things. First tried to do it in a twig template but I don't know how to call php functions in a twig template, so that didn't turn out too well.

Then I called the function in the preprocess\_page() function in the .theme file but before I could get it to work I tried something simpler just to try make a variable work inside the twig template which didn't work either, for example:

In the template\_preprocess\_page(&$vars) function in the .theme file:

```
$test = 'Hello World';
$vars['$my_var'] = $test;

```

I tried to call my\_var inside the twig template but it didn't work and I got an error message saying "The site has an error, please contact the administrator"

So, to summarize, here are my questions:

1. How do I make variables available inside twig templates?
2. How do I call functions inside twig templates?
3. Do I render blocks inside the .theme file or twig template?

# Answer
> 50 votes
You're on the wrong track with module\_invoke(). That's just a fancy way of calling the {$module\_name}\_block\_view() function.

The fact that it changed doesn't matter, the point is that the block system completely changed in 8.x and is now using plugins and config entities, those functions no longer exist.

You have a few options.

a) Re-use an existing block config entity and view it. Very easy, but requires that configuration to exist, e.g. as a disabled block.

```
$block = \Drupal\block\Entity\Block::load('your_block_id');
$variables['block_output'] = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

```

b) Create the block plugin instance directly, pass it the configuration (you can find the block plugin id and configuration easily in an exported block config entity). The downside is that you don't get render caching, but if you display it somewhere that is already cached (like a node template), that doesn't really matter.

```
$variables['block_output'] = \Drupal::service('plugin.manager.block')
  ->createInstance($plugin, $configuration)
  ->build();

```

c) In case of a view, you can also load the view directly and display it.

d) You can also re-think your approach completely and use block regions or Page Manager (which uses standard block plugins in 8.x).

# Answer
> 13 votes
In Drupal 8, this works for rendering a block plugin (that is, one that you've created in a custom module) in a preprocess\_hook:

```
function mymodule_preprocess_something(array &$variables) {
  $customblock = \Drupal::service('plugin.manager.block')->createInstance('my_custom_block', []);
  $variables['content']['custom_block_output'] = $customblock->build();
}

```

You can then render it in your twig template like this:

```
{{ content.custom_block_output }}

```

Note: this will load up a generic version of your block. If you want to load up an instance of your block with variables (after you have created it at /admin/structure/block), you have to load it this way:

```
    // Load Instance of custom block with variables
    $example_block = \Drupal::entityManager()->getStorage('block')->load('example_block_machine_name');
    if (!empty($example_block)){
      $example_block_content = \Drupal::entityManager()
        ->getViewBuilder('block')
        ->view($example_block);
      if ($example_block_content) {
        // Add block content to build array
        $variables['content']['custom_block_output'] = $example_block_content;
      }
    }

```

# Answer
> 9 votes
You can use *Twig tweak* module for that, then you can use the following syntax:

```
  <dd>{{ drupal_block('myblock') }}</dd>

```

Related: How do I programmatically place a block?

---
Tags: blocks, 8
---


# Question
Title: Correct way to call a service in a controller
I'm new to services (and drupal 8!) and trying to figure out services. I think perhaps I'm just doing the create in an outdated way. What I want do is make my 'hello generator' a service and call it in another controller with the following:

DBController.php

```
namespace Drupal\db\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\db\DbServices\HelloGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

class DBController extends ControllerBase
{
private $helloGenerator;

public function __construct(HelloGenerator $x) {
    $this->helloGenerator = $x;
}
public function say($count) {
    $hello = $this->helloGenerator->getHello($count);

    return new Response($hello);
}

public static function create(ContainerInterface $container) {
    $x = $container->get('db.hello_generator');
    return new static ($x);
}
}

```

HellGenerator.php

namespace Drupal\db\DbServices;

```
class HelloGenerator {

public function getHello($count) {
    $foo = 4 + 4 + 4;
    return $foo . ' ' . $count;
}

}

```

db.services.yml

```
services:
  db.hello_generator:
     class: Drupal\db\DbServices\HelloGenerator

db.db_says:
  path: /db/says/{count}
  defaults:
    _controller: '\Drupal\db\Controller\DBController::say'
  requirements:
    _permission: 'access content'

```

# Answer
There are 3 questions here:

1. How to create a controller?
2. How to create a service?
3. How to use services in a controller?

## 1. Create a controller

**1.1 Add a controller class** \- you did it. For others see Drupal documentation

**1.2 Add a routing file** \- it looks like this is missing in your code:

my\_module.routing.yml

```
my_module.my_route_name:
  path: '/my/path'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::myAction'
  requirements:
    _permission: 'access content'

```

see Drupal documentation

## 2. Create a service

**2.1 Add a service class** \- you did it.

**2.2 Add a routing file** \- you did it although it contains extra code that belongs to the routing file. This is all you need:

my\_module.services.yml

```
services:
  my_module.my_service:
    class: Drupal\my_module\Service\MyService

```

see Drupal documentation

## 3. Use services in a controller

You did it. Here's a reference for others:

**3.1 Override the `create()` method**

The controller class inherits this method from `class ControllerBase`. Its role is to create the controller object. Watch the method argument: it is passed the services container. Extract the services you need and pass them to the constructor:

```
public static function create(ContainerInterface $container) {
    $my_service = $container->get('my_module.my_service');
    $other_service = $container->get('other_service');

    return new static($my_service, $other_service);
}

```

**3.2 Initialise services in `__construct()`**

```
public function __construct($my_service, $other_service)
{
    $this->my_service = $my_service;
    $this->other_service = $other_service;
}

```

**3.3 Start using the services**
> 26 votes

---
Tags: 8, services, page-controller, dependency-injection
---


# Question
Title: Alter default value for field settings (allowed_formats)
Please how can I alter the default field settings whenever a new **field** is added?

NB I am **not** asking how to set the default whenever a new entity is added. This is about changing the pre-populated values on the page "Administration-\>Structure-\>Content types-\>XXX-\>Manage fields-\>Add field when a field is added"

NB This question is for D8. In D7 the answer is to use hook\_field\_info\_alter.

Specifically I am using the module allowed\_formats, and I would like every new text\_with\_summary or text\_long field to have defaults of:

* Allowed formats = "Basic HTML" only
* Form display settings "Hide the help link About text formats." and "Hide text format guidelines." enabled.

The defaults need to work even if the new field is created in code. In particular it's important to work for the Body field that is created automatically on a new content type.

I'm struggling because looking at the code, the defaults come from the public static function TextWithSummaryItem::defaultFieldSettings and there doesn't seem to be any hook.

# Answer
Thanks to @Berdir and @4k4 who helped me out several times - I just followed their ideas, tested and wrote up the answers.

This first hook alters the field settings. I've included a second example for image settings.

```
/**
 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
 */
function MYMODULE_field_config_create(FieldConfigInterface $field) {
  if ($field->isSyncing()) return;

  switch ($field->getType()) {
    case 'image':
      $field->setSettings(['file_directory' => 'images', 'max_resolution' => '1080x1080']);
      break;

    case 'text_with_summary':
    case 'text_long':
      $field->setThirdPartySetting('allowed_formats', 'basic_html', 'basic_html');
      break;
  }
}

```

This second hook alters the form display settings. The array\_diff\_key command is used to determine which fields are new.

```
/**
 * Implements hook_ENTITY_TYPE_presave().
 *
 * Override field form display defaults used when a field is added to a content type.
 */
function MYMODULE_entity_form_display_presave(EntityFormDisplay $display) {
  $fields = $display->getComponents();
  $origFields = (isset($display->original)) ? $display->original->getComponents() : [];
  foreach (array_diff_key($fields, $origFields) as $newField => $settings) {
    switch ($settings['type']) {
      case 'text_textarea_with_summary':
      case 'text_textarea':
        $settings['third_party_settings']['allowed_formats'] = ['hide_help' => '1', 'hide_guidelines' => '1'];
        $display->setComponent($newField, $settings);
        break;
    }
  }
}

```
> 2 votes

---
Tags: 8
---


# Question
Title: How to show event calendar with active links and event details underneath
I wanna show a page with calendar by month and all the upcoming events that fall within that month underneath.

So, on the page, I'd have this calendar that shows the current month:

Underneath I want the details of the events that fall in this month.

Any idea which module I should use and how can I achieve that in Drupal 7?

Thanks.

# Answer
> 1 votes
i have not tried this, but i think it will work, with calendar module enebled, go to month view, add a block view and build your underneath view, then add this block view as a footer (middle column in views ui) in your month view (Global: View area), then pass arguments in settings to be the same as your month view.

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