# Question
Title: Pass custom variable to an entity reference templete
i have the following problem in Drupal 8.

In custom content type there is a field, which is a multiple entity reference to the same content type. The field is set to use custom view mode, where only title and body fields are displayed. Kind of sub-pages structure. Also the content type has a boolean field, which determines whether the body field of sub pages (entity reference) should be displayed or not. So in my theme\_preprocess\_field() hook i can get the boolean value, but i don't know how to pass it to the entity references, so in my node--mypage--grid-item.html.twig i could check for that flag and determine should be content.body be rendered or not.

Thank for any hints.

# Answer
Create two view separate modes for your entity reference, one for each boolean value. In preprocessing, modify the view mode of the entity reference depending on the value of the boolean field.

This is a code example I'm using for paragraphs to change the view mode of a referenced media entity:

```
function mytheme_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_imageratio')) {
    $imageViewMode = str_replace('media.', '', $paragraph->field_imageratio->target_id);
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode;
    }
  }
}

```

I think you can largely reuse the logic above, `field_imageratio` should be replaced by your boolean field, `field_image` should be replaced by your entity reference field.
> 0 votes

---
Tags: 8, theming
---


title: How do I set the tab title?

text:
# Question
Title: How do I set the tab title?
How do I set the title of the tab from a controller in Drupal 8? This is the code I am using:

### Controller

```
class myController extends ControllerBase {

    public function node($nId) {
        $nodeObj = Node::load($nId);
        $elements = getRequiredDetails($nodeObj);

        return [
            '#theme'    => 'my_mod',
            '#title'    => 'This is the Tab Title'
            '#contents' => $elements,
            '#attached' => [
                'library'=> [
                    'my_mod/my_mod',
                ],
            ],
        ];
    }

    /**
    * Returns a page title.
    */
    public function getTitle() {
        $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();

        return $route->getDefaults('#title');
    }
}

```

### Route

```
my_mod.node:
 path: '/node/{nId}'
 defaults:
   _controller: 'Drupal\my_mod\Controller\myController::node'
   _title_callback: 'Drupal\my_mod\Controller\myController::getTitle'
requirements:
   _permission: 'access content'

```

But the `'#title'` in my controller sets the title in the page, not in the tab. Is there anything I am doing wrong?

If I put something like `die('Title Here');` in `getTitle()`, it will show in the tab. I need to call that method from the route.

# Answer
> 0 votes
If you use Meta tag module, you can use following method. From this method you can get Meta tag title and other Meta tags for view section also.

my\_module.services.yml

```
services:
my_module.route_subscriber:
class: Drupal\my_module\Routing\RouteSubscriber
tags:
  - { name: event_subscriber }

```

my\_module/src/Routing/RouteSubscriber.php

```
namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {

        if ($route = $collection->get('entity.node.canonical')) {
            $route->setDefaults(array(
                '_controller' => 'Drupal\my_module\Controller\MymoduleController::view',
            ));
        }
    }
}

```

MymoduleController.php

```
namespace Drupal\my_module\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Entity\Node;
use Drupal\node\Controller\NodeViewController;

class MymoduleController extends NodeViewController {

    public function view(EntityInterface $node, $view_mode = 'full',
    $langcode = NULL) {

        $elements = getRequiredDetails($node);

        return [
            '#theme'    => 'your-theme',
            '#contents' => $elements,
            '#attached' => [
                'library'=> [
                    'my_content/my_content',
                ],
            ],
        ];
    }
}

```

---
Tags: 8, nodes, routes
---


# Question
Title: How to alter storageSettingsForm in a custom Field Type definition, set default cardinality and not allow change
Trying to set `Allowed number of values` always to be 1 and not allowing multiple values for a custom Drupal 8 field. How to do that? Do I need a form\_ID\_alter or a storageSettingsForm/defaultStorageSettings implementation?

I see this field is not included in the storageSettingsForm `$form` or `parent::defaultStorageSettings()`

Not sure if the best way is to set it as configuration or alter the form. Is there an annotation for this or something? Any example module that does this?

Thanks

# Answer
> 0 votes
Problem solved in 8.4.0 :)

Full list of changes

---
Tags: 8, entities
---


# Question
Title: Help needed getting out of the habit of using TWIG as my Controller and Template files
I'm currently using TWIG to manipulate variables that have been created in Drupal 8. For example, I have a template that contains the following logic:

```
{% if item.field_main_images[0] %}
  {% if item.field_main_images[0]['#item'].entity.uri.value != "" and item.field_main_images[0]['#item'].entity.uri.value is not empty %}
    {% set main_image_uri = item.field_main_images[0]['#item'].entity.uri.value %}
    {% set main_image_zoom = main_image_uri | image_style('item_zoom') %}
  {% endif %}
{% endif %}

```

and

```
{% set featured_content = '' %}
{% if item.field_item_specification.0['#text'] is not empty %}
  {% set featured_content = item.field_item_specification %}
{% endif %}

```

Am I missing something here because i'm getting caught in spending a lot of time figuring out the data structures of the objects and manipulating the logic within my TWIG templates. I've got a feeling that I should be doing this in either a preprocess function on the content type or by some other means.

How could I perform this same procedure using the drupal framework i.e. symphony to create/manipulate the variables **before** the use of a twig template.

Can anyone shed some light on this?

Thanks in advance.

# Answer
You are right, this kind of code should be in your controller or in preprocess functions. You should generate a render array for each twig template, to be able to have a simple :

```
{{ image_with_zoom }}

```

In your twig file. Your controller could have something like :

```
  $renderArray = [];
  /* @var $item \Drupal\node\Entity\Node */
  if($item->field_main_images->count()){
    $image = File::load($item->field_main_images->target_id);
    $renderArray['image_with_zoom'] = [
      '#theme' => 'image_style',
      '#style_name' => '...',
      '#uri' => $image->getFileUri(),
      '#attributes' => [
        'data-zoom-url' =>  ImageStyle::load('item_zoom')->buildUrl($image->getFileUri())
      ]
    ];
  }

```

Have also a look at field formatters, it allow you to get your own controls for each field you wish to display. You can generate some skeleton with the drupal command :

```
$ drupal gpff

```

Have a look at documentation on this point, and the one in the drupal console. That's quiet important if you wish to reuse some display for a particular field as it looks like.
> 1 votes

# Answer
Disclaimer: This is going to be a bit "ranty"

I'm quite new to Drupal to, having the same issues, and my resumee is: That's an architectural flaw of Drupal itself and cannot be solved with a reasonable time budget.

For me it seems Drupal tries to provide a point-and-click interface to what would be a combination of view and controller in other systems ("view modes"). When you can't solve your problems using view modes (which happens at *every* of my projects), the clean, drupalesque solution would be creating a field formatter module (containing the logic), so you can keep using view modes and clean templates. As soon as you start doing logic in preprocessing or twigging, you often have to mess with render arrays, and render arrays are ... well ... not so super-intuitive.

My conclusion is: If you have got big budget, write field formatters. On a tight budget use preprocessing for fetching additional data and for more complex logic (e.g. cross-field-dependencies). Use Twig for simple logic and for small variations of the same data (use/extend/embed/...). If I find myself altering render arrays in Twig, I know that I need to refactor and switch to preprocessing.

Personally I would use template preprocessing for your first example, and keep the second in Twig.
> 1 votes

# Answer
I agree that this kind of logic should be handled in preprocessing, rather than within the TWIG templates. This keeps the templates simple and ensures themers being able to focus on theming without having to deal with too complex program logic (that might even break when you or the related modules rename fields or alter entities).

Fortunately, your ability to do your tweaks within TWIG templates shows, that field formatters/blocks/... are not rendering and returning static HTML (which unfortunately still happens far too often in modules migrated from older Drupal versions).

The output is rendered utilizing Drupal's theming registry.

This allows you to alter/extend this registry and use hook\_theme\_registry\_alter() to add your own preprocessing to the templates within a custom module's .module file (the theme hook key 'the\_theme\_hook\_to\_extend' most often matches the template name with underscores instead of the dashes):

```
/**
 * Implements hook_theme_registry_alter().
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  // Add custom preprocessing.
  if (isset($theme_registry['the_theme_hook_to_extend'])) {
    $theme_registry['the_theme_hook_to_extend']['preprocess functions'][] = 'MYMODULE_preprocess_for_the_theme_hook_to_extend';
  }
}

```

Then add the above defined preprocess function to your module to add your program logic:

```
/**
 * Custom preprocess for the_theme_hook_to_extend.
 *
 * Used to do some additional magic.
 *
 * @param array $variables
 *   Theme variables.
 */
function MYMODULE_preprocess_for_the_theme_hook_to_extend(array &$variables) {
  // Alter your variables accordingly, add additional
  // variables, or do whatever else preprocessing you
  // need.
}

```

I hope, this is the light you've been asking for.

EDIT:

The above example is a simple one that adds a preprocessing to the theme registry. You can actually use that hook for removing other module's preprocessing, or replace templates, and even controllers.

If you are looking for adding your own preprocessing only, you can simply utilize hook\_preprocess\_HOOK() in your module or theme to alter variables.
> 1 votes

---
Tags: 8, theming
---


title: CSS customization won't work

text:
# Question
Title: CSS customization won't work
Recently, I signed up with the Amazon's Lightsail service that comes with a version of Drupal (8.3) provided by Bitnami. I am not sure how this is different from any other installations, but when I tried to increase the font size of my site name, it wouldn't work.

The file I updated is style.css under ~/apps/drupal/htdocs/themes/zircon/css. (I am using the Zircon theme.)

The CSS ruleset I added is the following.

```
.site-name {
  font-size: 30px;
}

```

I tried clearing the cache, unchecking the "Aggregate CSS files", but none of them works.

Googling, I learned that adding a sub-theme is recommended for the job, that I tried, but the admininistration pages of the site simply wouldn't load after I created a folder (with the .yml file in it) under the themes(~/apps/drupal/htdocs/themes) directory.

Is it still possible to update a given style.css file from a given theme?

# Answer
> 2 votes
It seems like you updated the CSS semi-correctly. Semi because, it does look like Zircon's CSS is built using SASS/Compass and not directly. You might want to look at how to set this up properly.

You are also correct that you really need to set up a sub-theme first. The reason to do this is that when updates to the Zircon theme come out, you will need to figure out what you changed, save it, update the theme and then re-merge your changes.

See the documents on how to set up a sub-theme.

As to why your CSS change did not take effect, these are some possibilities:

* First, your rule was added, but is being overridden by a more specific rule. Inspect the element and see if the rule shows up but it's red lined. A quick hack is to just add !important to your rule. This *should* make it most specific, unless someone else added it to their rule.
The best way would be to get SASS/compass set up, find where the .site-name is themed in the SASS files, change it there, and rebuild the CSS with Compass.
* If it's not a CSS rule thing, it might be an external caching system. First, I assume you did a FULL reload of the page (Generally Shift F5) to clear the local browser cache.
* Next, did you set up Varnish with your site? If so, you might need to clear the Varnish cache, or set up some rules so that logged-in users don't use cache.
* Are you using something like Cloudflare? This can also cache CSS. You can check for external caching by using Chrome's Network tab (inspect something on the page or select the Network tab). Look for the CSS file that you modified, click on it, then check the headers. See if there are any tags like CF-xx or X-varnish with values like hit or miss. (A hit means it was served from cache).

That said, while you are developing a site, you probably want to do what you did:

* Turn off all aggregation
* Turn off caching (Config -\> Devel-\> performance)

This might seem a bit daunting but it's really not.

---
Tags: theming
---


# Question
Title: Form not receiving a CSS class, it's block wrapper does instead
I have a custom form built with Form API that I am trying to add a class to on the form tag.

In the `buildForm` method, I have:

```
$form['#attributes']['class'][] = 'hl__single-input-form__form';

```

But the class doesn't appear on the form tag. Instead, the class appears on the div wrapper for the block that outputs the form.

In the block, the `build` method has:

```
  /**
   * {@inheritdoc}
   */
  public function build() {
    return $this->formBuilder->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup');
  }

```

The only way I have been able to solve this is with a custom twig file with the following:

```
<section class="hl__single-input-form">
  <form{{ attributes.addClass('hl__single-input-form__form') }}>
    {{ children }}
  </form>
</section>

```

But the twig shouldn't be necessary. I also notice that the form id as a css class also goes on the block wrapper, too. What is happening here?

# Answer
> 2 votes
Obviously the block plugin thinks the #attributes key in the returned array is meant for the block wrapper. So I would try to put the form in a subkey, this should prevent that the block plugin can access the attributes of the form:

```
  return ['form' => $this->formBuilder->getForm(...)];

```

By the way the core search block is also returning the form array directly like you did in the question and indeed, the resulting form tag in the search block has no classes too. I'm not sure, but this seems to be the same issue.

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


title: Redirect contact form on submit

text:
# Question
Title: Redirect contact form on submit
Using Drupal 8 and trying to get the contact form to redirect to the same page after submitting. By default it seem to redirect to the home page.

I have edited my themename.theme file

```
function themename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  //contact page form
  if ($form_id == 'contact_message_feedback_form') {
    $url = Url::fromRoute('contact.site_page');
    $form_state->setRedirectUrl($url);
  }
}

```

This throws a bunch of mysql errors. Like so:

```
Uncaught exception thrown in session handler.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes: UPDATE {sessions} SET uid=:db_update_placeholder_0, hostname=:db_update_placeholder_1, session=:db_update_placeholder_2, timestamp=:db_update_placeholder_3 WHERE ( (sid = :db_condition_placeholder_0) ); Array ( [:db_update_placeholder_0] => 1 [:db_update_placeholder_1] => ::1 [:db_update_placeholder_2] => _sf2_attributes|a:1:{s:3:"uid";s:1:"1";}_sf2_flashes|a:0:{}_sf2_meta|a:4:{s:1:"u";i:1454074283;s:1:"c";i:1452243053;s:1:"l";s:7:"2000000";s:1:"s";s:43:"dVseXv540u6wL5GZm_gs6fzuP9qtck-j5A5lexqnaQE";}authorize_page_title|O:48:"Drupal\Core\StringTranslation\TranslatableMarkup":3:{s:9:"*string";s:14:"Update manager";s:12:"*arguments";a:0:{}s:10:"*options";a:0:{}}messages|a:1:{s:6:"status";a:2:{i:0;O:25:"Drupal\Core\Render\Markup":1:{s:9:"*string";s:1020035:"<script class="-kint-js">(function(){if("undefined"===typeof kintInitialized){kintInitialized=1;var e=[],f=-1,g=function(b){var a=window in Drupal\Core\Session\SessionHandler->write() (line 89 of /Users/timmcdonald/Code/waypoint/v3/core/lib/Drupal/Core/Session/SessionHandler.php).

```

and other errors. Is there something I am missing?

# Answer
Here is what I ended up doing in a custom module if anyone else needs to do this

```
use Drupal\Core\Url;

function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  //contact page form
  if ($form_id == 'contact_message_feedback_form') {
    $form['actions']['submit']['#submit'][] = 'custom_module_contact_submit';
    dpm($form['actions']['submit']);
  }

}

function custom_module_contact_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    drupal_set_message('we sent a form woohoo');
    $url = Url::fromRoute('contact.site_page');
    $form_state->setRedirectUrl($url);
}

```
> 5 votes

# Answer
And to make it even better

```
/**
 * hook_form_FORM_ID_alter
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function minimal_form_contact_message_contact_me_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'minimal_contact_submit';
}

/**
 * Contact form submit handler
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function minimal_contact_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  drupal_set_message('we sent a form woohoo');
  // From URL to URL object
  $url = \Drupal\Core\Url::fromUserInput('/node/16');
  $form_state->setRedirect('contact.site_page');
}

```

I found it useful, so maybe other people could find it useful too
> 4 votes

# Answer
Tim's solution will also work from a theme.

In this case the theme is called 'minimal', and the code below is in the minimal.theme file. I'm calling hook\_form\_FORM\_ID\_alter on a form with ID: contact\_message\_contact\_me

Also note the signature on the submit handler, as well as the direct call to redirect with the default site-wide route for the contact form (my form above is set to the default). You don't need to build the Url first.

```
/**
 * hook_form_FORM_ID_alter
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function minimal_form_contact_message_contact_me_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'minimal_contact_submit';
}

/**
 * Contact form submit handler
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function minimal_contact_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setRedirect('contact.site_page');
}

```
> 1 votes

# Answer
To redirect to the same page, whatever it is (if you use contact block module for instance), you can use this in your submit callback:

```
$form_state->setRedirectUrl(\Drupal\Core\Url::fromRouteMatch(\Drupal::routeMatch()));

```
> 1 votes

# Answer
I created a custom module for my form. In the submit function, I did not set a redirect URL, in which the submit function will not redirect to any page, and therefore show the form page again. This because the form submits to the same page the form is on.

Edit: After I posted this answer I noted that you asked about the Drupal contact form. So naturally this answer is wrong. Always read the brief twice and then two more times.

```
<?php
/**
 * File: ContactForm.php
 */

namespace Drupal\module_name\Form;

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

class ContactForm extends FormBase
{
    /**
     * {@inheritDoc}
     */
    public function getFormId() {
        return 'module_name_contact_form';
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        // Form
        return $form;
    }

    /**
     * {@inheritDoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        // Form validation
    }

    /**
     * {@inheritDoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message('Form submitted');
    }
}

```
> 0 votes

---
Tags: forms, 8, redirection, emails
---


# Question
Title: How to delete all Taxonomy terms of particular vocabulary using entity_delete_multiple?
I want to delete all taxonomy terms of particular vocabulary using `entity_delete_multiple`. For node it is working fine

```
$result = \Drupal::entityQuery('node')
      ->condition('type', 'page')
      ->execute();
  entity_delete_multiple('node', $result);

```

If i am changing taxonomy\_term and type to `tags or any other vocabulary`, or replaced `type by bundle`

```
$result = \Drupal::entityQuery('taxonomy_term')
      ->condition('type', 'tags')
      ->execute();
  entity_delete_multiple('taxonomy_term', $result);

```

it is throwing error like this.

> Drupal\Core\Entity\Query\QueryException: 'type' not found in Drupal\Core\Entity\Query\Sql\Tables-\>ensureEntityTable() (line 304 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

And also i need a same query to delete user(s), watchdog and profiles.

Is there any way to do it?

# Answer
Try to use `vid` instead of `type`. I haven't tried the code, but try the following

```
$result = \Drupal::entityQuery('taxonomy_term')
      ->condition('vid', 'tags')
      ->execute();
  entity_delete_multiple('taxonomy_term', $result);

```

Here is a good example for using entityQuery.

For deleting users, you can use `entity_delete_multiple` or `user_delete_multiple`

To delete user with uid 10

```
entity_delete_multiple('user', \Drupal::entityQuery('user')->condition('uid', '10', '=')->execute());

```

or pass an array of uids to `user_delete_multiple`

```
user_delete_multiple(array $uids);

```

I'm not aware of how to delete comments.
> 13 votes

# Answer
I know the question specifically asks about entity\_delete\_multiple, but the function is deprecated, scheduled to be removed "before" Drupal 9. Here's a version without entity\_delete\_multiple

```
/**
 * Delete all taxonomy terms from a vocabulary
 * @param $vid
 */
function delete_terms_from_vocab($vid) {

  $tids = Drupal::entityQuery('taxonomy_term')
    ->condition('vid', $vid)
    ->execute();

  if (empty($tids)) {
    return;
  }

  $term_storage = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term');
  $entities = $term_storage->loadMultiple($tids);

  $term_storage->delete($entities);
}

```
> 7 votes

# Answer
For taxonomy use `vid`:

```
$result = \Drupal::entityQuery('taxonomy_term')
      ->condition('vid', 'tags')
      ->execute();

```

Which is the bundle of taxonomy.
> 3 votes

# Answer
For delete all taxonomy terms of particular vocabulary.

Try

```
 $vid = 'name_of_the_vocabulary';
      $tids = \Drupal::entityQuery('taxonomy_term')
          ->condition('vid', $vid)
          ->execute();
      entity_delete_multiple('taxonomy_term', $tids);

```
> 2 votes

# Answer
You can try below code,which works for me

```
 $vids = Vocabulary::loadMultiple();
    foreach ($vids as $vid) {
      if ($vid->label() == 'YourVocab') {
        $container = \Drupal::getContainer();
        $terms = $container->get('entity.manager')->getStorage('taxonomy_term')->loadTree($vid->id());
        if (!empty($terms)) {
          entity_delete_multiple('taxonomy_term', $terms);
        }
        break;
      }
}

```
> 1 votes

---
Tags: 8, taxonomy-terms, entities
---


title: Grouping query results

text:
# Question
Title: Grouping query results
I have this small and simple sql query.

```
  $query = \Drupal::database()->select('users_field_data', 'ufd');
  $query->fields('ufd', ['uid', 'name', 'mail', 'status']);
  $query->orderBy('ufd.status', 'Desc');

  $result = $query->execute()->fetchAll();

```

Result of this is an array of Objects which include the fields from the query above. Here's a sample:

```
[
stdClass Object
(
    [uid] => 2
    [name] => Test 1
    [mail] => test@test1.com
    [status] => 1
)
stdClass Object
(
    [uid] => 3
    [name] => Test 3
    [mail] => test@test2.com
    [status] => 0
)
]

```

So my question is how can i group the results by the field status, so that i have and array of results with the index of the status? I think i can get the results with GroupBy, but no luck so far.

Example/Result wanted:

```
[status_key_1] => [
stdClass Object
(
    [uid] => 2
    [name] => Test 1
    [mail] => test@test1.com
    [status] => 1
)stdClass Object
(
    [uid] => 3
    [name] => Test 2
    [mail] => test@test2.com
    [status] => 1
)
]
[status_key_0] => [
stdClass Object
(
    [uid] => 4
    [name] => Test 4
    [mail] => test@test4.com
    [status] => 0
)stdClass Object
(
    [uid] => 5
    [name] => Test 5
    [mail] => test@test5.com
    [status] => 0
)
]

```

Where `status_key_0` and `status_key_1` are essentially 0 and 1, since those are the only two values drupal allows, but i didn't want to put them directly in the example as some would think i wanted a auto-incremented associated array.

~p.s. i know i can sort the result of the query, and that's what i'm doing, but having an already sorted array is best practice and a good solution.

Thanks.

# Answer
SQL GroupBy is generally used with expressions to get counts and other stats. I'm not sure it will be more efficient than just sorting. That said...

You should be able to add a groupBy clause to your query. You will have to add all fields to it in order to keep SQL happy. E.g.:

```
$query->groupBy('udf.status')->groupBy('udf.uid')...

```

Note: I believe that the SQL standard is deprecating the use of groupby without an aggregation function in the select clause.
> 0 votes

# Answer
To get this result, you must do two SQL queries.

Please, try this code:

```
$query = \Drupal::database()->select('users_field_data', 'ufd');
$query->fields('ufd', ['status']);
$query->groupBy('ufd.status');
$query->orderBy('ufd.status', 'Asc');
$results_query1 = $query->execute()->fetchAll();

$results=array();

foreach ($results_query1 as $delta => $result) {
  $query = \Drupal::database()->select('users_field_data', 'ufd');
  $query->fields('ufd', ['uid', 'name', 'mail', 'status']);
  $query->condition('ufd.status', $result->status);
  $query->orderBy('ufd.status', 'Desc');
  $result_query2 = $query->execute()->fetchAll();

  $results['status_key_'.$result->status]=$result_query2;
}

print_r($results);

```

The result will be:

```
Array
(
    [status_key_0] => Array
        (
            [0] => stdClass Object
                (
                    [uid] => 0
                    [name] =>
                    [mail] =>
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [uid] => 21
                    [name] => b
                    [mail] => b@b.com
                    [status] => 0
                )

        )

    [status_key_1] => Array
        (
            [0] => stdClass Object
                (
                    [uid] => 1
                    [name] => admin
                    [mail] => localhost@localhost.com
                    [status] => 1
                )

            [1] => stdClass Object
                (
                    [uid] => 3
                    [name] => a
                    [mail] => a@a.com
                    [status] => 1
                )

        )

)

```

An example of how to access the information of this variable:

```
$results['status_key_1'][1]->uid

```

The result is:

```
3

```
> 0 votes

---
Tags: database
---


# Question
Title: How to render a custom entity in a controller?
I created a custom entity called foo. This entity has a unique `name` field as well as the standard `id` key. I would like to build a page where the user can see the entity rendered similarly to how it would be on the admin page, but instead of referencing it by the `id`, I would like to use the `name`.

I have the following in my controller:

```
public function content($name) {
  $output = [];
  //Add a couple things to the $output array
  $output['first thing'] = [/*stuff*/];

  $sql = "SELECT id FROM foo WHERE name=:name";
  $sql_params = [':name' => $name];
  $results = db_query($sql, $sql_params)->fetchAll(PDO::FETCH_ASSOC);
  $render_array = [];
  if (count($results) > 0) {
    $id = $results[0]['id'];

    $entity_type = 'foo';
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $controller = \Drupal::entityManager()->getStorage($entity_type);
    $entity = $controller->load($id);
    $build = $view_builder->view($entity);
    $render_array = render($build);
    $output['entity'] = $render_array;
  }
  return $output;
}

```

However, I receive an error: `User error: "entity" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).`

What do I need to do differently to make my entity render to the page?

# Answer
> 4 votes
Controllers should return a render array (or a custom response), you almost never need to render anything yourself outside a template.

Just replace this:

```
$build = $view_builder->view($entity);
$render_array = render($build);
$output['entity'] = $render_array;

```

with:

```
$output = $view_builder->view($entity);

```

to return a render array and let Twig handle the rendering.

But going further, you don't need to (and shouldn't) go into the database directly for this; the entity type manager works for all entity types, including your own, and entity storage classes have methods to help with this.

(As an aside, that service should also be injected rather than loaded from the static `Drupal` class method, your controller class is container aware).

Once that's available the code would be simplified to something like this:

```
public function content($name) {
  $build = [];
  $entity_type = 'foo';

  $storage = $this->entityTypeManager->getStorage($entity_type);
  $entities = $storage->loadByProperties(['name' => $name]);

  if ($entity = reset($entities)) {
    $build = $this->entityTypeManager->getViewBuilder($entity_type)->view($entity);
  }

  return $build;
}

```

To go one step further, you can add a `loadByName()` method to your entity class with a slight variation of the above, might save you some time and repetition further down the line.

---
Tags: 8, theming, entities, page-controller
---


# Question
Title: Drupal 8 add javascript and pass data in a hook with custom module
I am building a custom module with Drupal 8. One of the requirements of the module is that it sets up a javascript file based on the configuration settings, which the user of the module sets up in module configuration.

The javascript which needs to be added to the page depends on the configuration settings. Hence I can not add it using Libraries as mentioned in this article: Adding assets to Drupal module.

I first implemented it using a block. I use Twig templates to pass the configuration variables in PHP to the twig file, and in the twig file, I have a `<script>` tag to add the javascript based on the config variables. Refer Using twig templates.

The problem with this approach is that user needs to add the block on the page, and there is no UI facing element on that block. I also find it very messy.

Is there a cleaner way to add my javascript using hook and pass variables to it? I looked around and found hook\_install and hook\_page\_attachments. So I can add Javascript, but don't know how I can pass any php variables to it.

I am new to Drupal development. Any help with this is really appreciated.

**TL;DR I need to find a way to add Javascript using Drupal hook and pass some PHP variables to it.**

# Answer
You can add variables into the scope without generating a Javascript file and then use a hook like preprocess\_html to add them in:

```
$variables['#attached']['drupalSettings']['mymodule']['config']['color'] = $config->get('mymodule.color');

```

These value(s) are then available in the `drupalSettings` scope, which you can read out in your module Javascript file in order to do things. Just pass `drupalSettings` into it.
> 2 votes

---
Tags: 8, hooks
---


# Question
Title: Using Rules to send an email to all Simplenews subscribers
On a Drupal 8 site I'm working on, we are using Simplenews to allow users to subscribe to a mailing list for blog posts. The client would like us to set up a rule to automatically send an email to everyone on this specific blog post subscriber list whenever a new blog post is published.

I have gotten to the point where Rules will send out an email to a specific email every time a new node of type Blog Post is published, but I can't figure out how to reference a specific list of Simplenews subscribers through Rules' data selector. Does anyone know how to create that? Or maybe a work around for this?

# Answer
> 0 votes
Assuming your question is about D7, and looking at the available integration of Simplenews with Rules, there is no out-of-the-box solution (at least not that I'm aware of). So as per your "*... maybe a workaround for this?*", below is a blueprint of how to get it to work anyhow ...

* Create a custom rule in which you use Rules Event "A user has been subscribed", with a Rules Action to *flag* such user, using the Flag module, and by using a global flag. Label the flag something like "Subscribe to Blog posts Newsletter".
* Create a similar custom rule in which you use Rules Event "A user has been unsubscribed", with a Rules Action to *unflag* such user (for the same flag as described above).
* Use the Views module to create a list of all users flagged by the flag described above.
* Use the Views Rules module to create an additional Views display in the view described above, of type "Rules".
* Improve your existing rule by adding a Rules Action to load the list of all users included in the Rules display created as described above. That should be the list you're asking about in your "specific list of Simplenews subscribers".

True, 3 extra modules (Flag, Views and Views Rules) needed to get this to work. But zero custom code required ... (together with 2 extra rules, and a refinement of your existing rule).

---
Tags: 8, rules, emails
---


# Question
Title: How to add a rule condition from select-list in a webform
This an export of my rule

```
{ "rules_webform_to_simplenews" : {
    "LABEL" : "Webform to simplenews",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules", "simplenews_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "webform-client-form-113",
          "selected_webform" : { "value" : {
              "webform-client-form-27" : "webform-client-form-27",
              "webform-client-form-113" : "webform-client-form-113"
            }
          }
        }
      }
    ],
    "DO" : [
      { "simplenews_rules_action_subscribe" : { "mail" : "[data:e_mail-value]", "tid" : "211", "confirmation" : "2" } }
    ]
  }
}

```

When a webform is submitted, the e-mailadres is added to the newsletter-subscriptions. But there should be an extra condition that the submitter agrees the subscribing by checking a select-option on the webform.

when i use the data-selector *data:newsletter-value* or *data:newsletter-key* for parmeter, it is refused.

# Answer
You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your `[data:newsletter-value-raw]` (assuming `newsletter` is the form component containing your select-option) and with a data type which equals the data type of your Webform component. In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).
* Use the Conditional Rules module to perform a data comparison. In this case to check the value of your select-option. If so, and only then, perform your Rules Action to add the email address as a subscriber.

PS: Instead of using the Conditional Rules module, you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".
> 0 votes

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


# Question
Title: Programmaticaly remove a member from a group
Using the Group module, what is the function to remove a user from a group using its user ID and the group ID?

# Answer
> 4 votes
The entity type interface (`GroupInterface`) has a `removeMember` method; all you need are the relevant entity objects:

```
if ($account = \Drupal\user\Entity\User::load($user_id)) {
  if ($group = \Drupal\group\Entity\Group::load($group_id)) {
    $group->removeMember($account);
  }
}

```

---
Tags: 8, group
---


# Question
Title: Simplenews condition results in double email
I've got a simple rule sending a notification email to site admin on the event 'A user has been subscribed'.

I'm however getting 2 emails on a signup. Any idea why and how to fix so the admin only gets notified once on each signup?

SimpleNews Version: 7.x-1.1 Core Version: 7.39

# Answer
> 0 votes
@Kristoffer Rom, I've just tested and I've got the same duplication.
So, I suggest you create such notification rule based on:

* "After saving new user account" event.
* "Send mail" action from "System" actions group.

# Answer
> 0 votes
### Understanding what's happening

Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

> some other module code is calling a `user_save` on `hook_user_update` triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

### Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

### Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like \[account:last-login\] = never?". More specifically:

* Add a Rules Condition like: ***User does NOT (!!!) have a role with role id = "`4`"***.
* Add a Rules Action like: ***Grant User the role with role id = "`4`"***.

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "`4`" (adapt to whatever role id that fits your case). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

* The **1st time** your Rules Actions will still be performed (and grants the designated role).
* the **2nd time** not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.

---
Tags: rules, emails
---


# Question
Title: What are all the steps to have a user-selectable second language in Drupal 8?
I want to add a second language to my site. What all do I have to do to enable a language and make it selectable by the user? Also, how can I keep from having all of the content show up twice-- once for the default language (in my case, English) and once for the other language?

I'm using Drupal 8

# Answer
To allow a user to select other languages, you need to first enable other languages and then place a selector somewhere on the site. Here are the steps:

1. Enable other languages from Manage \> Extend \> Multilingual (check all four boxes-- Configure Translation, Content Translation, Interface Translation, Language)
2. Configuration \> Languages \> Add language – whatever language
3. Configuration \> Content Language and translation \> check the box next to what you want to be able to have a translated version (like articles or basic page, etc.)
4. add a language switcher for the end user:

a. Go to Admin \> Structure \> Blocks

b. Click "Place blocks" on the desired region

c. Click "Place block" next to the "Language Switcher" block

d. Click "Save block"

e. Go to a translated node and the Language Switcher will be working

Now if you translate an article it will make a second version of that article, so to prevent both versions from showing up in any lists you have, make any of the Views filter by language:

Under Structure \> Views - find any views your site uses and Add "content: translation language" then select the option to filter by "interface text language selected for page"

This is a compilation from How to allow the user to change the language? and https://www.drupal.org/docs/8/multilingual/translating-content and https://www.drupal.org/node/1346242

See also https://www.drupal.org/forum/support/translations/2014-01-27/menu-translation-in-drupal-8#comment-11454369 (in this context https://www.drupal.org/node/2182497) to make sure you enable all items like menus to be translatable

NOTE: selecting all four modules in Multilingual may not be necessary for just displaying a different language option for end users, start with just Language and Content Translation
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Enable CKEditor on a field with a custom widget
I have a custom widget for a field that hides the field if certain conditions are not met. My custom widget field extends the `StringTextareaWidget` class as a base. When it renders, my widget never displays ckeditor.

If I change the display widget to "Text Area (multiple rows)" ckeditor displays as expected.

To test my code, I commended out everything except the class declaration that extends StringTextAreaWidget, and this also prevents the ckeditor from displaying when the widget is rendered. How do I get my custom field widget to display with ckeditor?

# Answer
> 0 votes
I was extending the wrong class from my field widget. The proper class to extend if you're looking to use CKEditor is `TextareaWidget`

---
Tags: 8, wysiwyg
---


# Question
Title: How can I programmatically add members to a group?
I am trying add members to a group programmatically using Groups module in Drupal 8, and I am doing the following to achieve this:

```
use Drupal\Core\Entity\ContentEntityBase;
$roles = array('test_role');
$values = ['group_roles' => $roles, 'gid' => 1];
$account = $this->createUser();
$group = \Drupal\group\Entity\Group::load(1);
$group->addMember($account, $values);

```

So, users are already present in the site. I want to add only those users to a group who have successfully paid for it. Hence, I am trying to write a custom solution that I add a user to an already existing group on the site. I came across this addMember($account, $values) function in the group module, however am still not sure on what values its arguments ($account and $values) take. Above piece of code does not add users to my group. Can someone please suggest what wrong I am doing here?

# Answer
So, modifying the code a little bit and saving the group after adding member to it worked for me. Pasting the updated code below:

```
use Drupal\Core\Entity\ContentEntityBase;
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$group = \Drupal\group\Entity\Group::load($group_id);
$group->addMember($account);
$group->save();

```
> 5 votes

# Answer
Without 'gid' code below works for me:

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$group = \Drupal::entityTypeManager()->getStorage('group')->load(127);
$group->addMember($user, ['group_roles' => ['podrazdelenie-admin']]);
$group->save();

```
> 3 votes

---
Tags: 8, users, group
---


title: rating of multiple items

text:
# Question
Title: rating of multiple items
I need to create a rating entry on a profile that needs to have 5 items that the user can rate in order from 1 to 5 (most to least important). Does anyone know of a module that can do this or can point me in the right way to make my own (I've never done that before)

Thanks!

# Answer
If you are trying to implement this for a Drupal 7 site, you could:

1. enable webforms on the "profile" content type
2. install/enable https://www.drupal.org/project/webform\_draggable\_list
3. setup a webform attached to every profile with the draggable list.

Other Drupal 6 & 7 options for this are noted in this prior thread: Ranking/polling field or webform module

For Drupal 8, you could potentially do a similar setup as the webform\_draggable\_list option.
> 1 votes

---
Tags: rating
---


# Question
Title: How to get menu title inside menu--main.html.twig file
I created a suggestion for menu and using menu--main-sidebar.html to render menu.

I want to include menu title (title of block added to specific region from admin side) as first child of menu

I tried to use configuration (configuration.label shows menu title in block--menu-block--main.html.twig file) like below

```
{{ menus.menu_links(items, attributes, menu_level, menu_name, configuration) }}

```

That does not work.

So, how to get the menu title inside menu\_links in menu--main.html.twig file?

# Answer
> 0 votes
You could try using the Simplify Menu module (which extends twig to support direct access to Drupal's menus for overriding markup).

See the example in this related thread: https://drupal.stackexchange.com/a/228982/79832

---
Tags: 8, navigation
---


# Question
Title: Using Event Subscriber change the product custom field value after first checkout of that product
Using 'Event Subscriber', I'm able to get `$order` and `$items` from the order after completing the checkout.

How can I get the product id from the `$items`and modify the product custom field value?

Scenario: I want to change the status of the product after completing the first checkout of that product.

# Answer
Do you really want to change the status of the product or the product variation?

`$items` is an array of OrderItems. If you loop over the items, you can get the referenced purchased entity of the single item with `$purchasedEntity = $item->getPurchasedEntity();`. If you only want the first item you can access it like so `$purchasedEntity = $items[0]->getPurchasedEntity();`. In case the PurchasedEntity is a ProductVariation you can get the product with `$product = $purchasedEntity->getProduct();`

In case you want to change the status of the product:

```
$product->setUnpublished();

```

Or for the variation:

```
$variation->setActive(false);

```

If you want to set any custom field on the product variation:

```
$variation->set('your_custom_field_name', $value);

```

docs This assumes you use the default commerce2 product architecture. It is absolutly possible that you get other purchasable entities than ProductVariations back from the OrderItem.
> 1 votes

---
Tags: 8, commerce, event-subscribers
---


# Question
Title: How to add webform to existing content type?
I have installed Webform and would like to add it to my custom content type. I have checked my content type under `admin/config/content/webform` and saved the webform settings but I still don't get the option to add a `webform` to my content type.

# Answer
> 2 votes
Go to Content type edit page : /admin/structure/types/manage/\[ContentTypeName\]. There you can see the `webform` under the `Menu Settings`. Just enable it from there. Adding screenshot :

# Answer
> 2 votes
To add a webform to your content type you should add a field to your content type and choose other as a type of this field ---\> Reference /other then save after that when you choose the type of reference you must choose webform and save Now in your content type when you add content you find a field for your webform and in that you put one of your webform

---
Tags: nodes, webforms
---


# Question
Title: t() and {% trans %} show no effect although rest of site is translated
I'm a bit hesitant to ask this, but I have a drupal 8 site with 2 languages enabled - English as default and German. I have URL prefixes 'en' and 'de' to detect the chosen language. When setting German as default, the menus are translated, fields etc. It all works reasonably well. However, none of strings I use in my custom modules are translated. A very simple example

```
class testController extends ControllerBase {

...
drupal_set_message(t("Sorry, that does not work"));
....
}

```

The string is not translated when using german as the site's default language. Furthermore in my twig templates `{% trans %} Hello {% endtrans %}` have absolutely no effect.

Is there something I am missing here or I have to specifically set up ? I have used google for hours but do not find any solution to this weird problem. I've also tried all kinds of language detection methods in the Drupal settings - no effect. I have modules: Configuration Translation, Content Translation, Interface Translation and Language enabled.

# Answer
If the strings in your custom module are in **English** but the site's default language is in **German**, you will need to translate the strings in the admin UI:

`/admin/config/regional/translate`

If you search for the string on this page but don't see it, you will need to first visit the page/path on the site that causes the string to be displayed so that the string will be created for translation purposes. Then you can return to the translation page and translate the string.

To translate strings in a twig template, do it like this:

```
{{ 'This is a string to translate.'|trans }}

```
> 4 votes

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


# Question
Title: On a content page that references a taxonomy term, how can I display only content that references that taxonomy term's immediate children?
In Drupal 8, I have a hierarchical taxonomy vocabulary called "Living Things" containing these terms:

```
Animals
--Fishes
----Blennies
------Yellow Blenny
------Green Blenny
----Gobies
------Blue Goby
------Red Goby

```

I have created a custom content type called "Taxon Page" which includes a single reference to the "Living Things" vocabulary.

Using the "Taxon Page" content type I have created a page for each of the terms in the "Living Things" vocabulary. So for example, my "Yellow Blenny Facts" content page contains a reference to the "Yellow Blenny" taxonomy term.

On those "Taxon Page" content pages, how can I display only content that references that taxonomy term's immediate children (if there are any)? For example, the "Fishes Facts" content page should display data from the "Blennies Facts" and "Gobies Facts" content (not just a link to those taxonomy terms), but not their children.

I have tried to achieve this by creating a view for "*Content type (= Taxon Page)*" and adding a "*contextual filter: Content: Has taxonomy term ID (with depth)*" (depth of 1) but it did not work.

Note that this question is related but different, as it only refers to taxonomy terms, not content referencing those taxonomy terms.

# Answer
I think you may be confused about how Views works. To give a custom display to taxonomy terms, you don't need to create a content type to reference a taxonomy and then use Views to override how the content type is displayed; you can simply create pages with a view that display the taxonomy directly.

This means you may not need the **Taxon Page** content type; depending on what you intend to do, you could add any fields you need for your fish pages to the **Living Things** taxonomy and then display this taxonomy as pages by using a view that overrides how the taxonomy is displayed.

For an example, see the `taxonomy_term` view included in core:

`/admin/structure/views/view/taxonomy_term`

Another way to do this is to use Panels, which (with Page Manager) allows you to override the display for all taxonomy terms and attach a custom view (and whatever else you want) to those terms.

Yet another option is Display Suite.
> 0 votes

# Answer
I start by guessing that you want to show the taxonomy term descriptions of child terms on the "taxon pages".

Best way to achieve this is to creating a new block view.

As you supposedly want to show taxonomy data, choose "Taxonomy term" as data to show; save and edit.

Next you have to pull in the parent term's ID, that is referenced from the node (Content page) this block will be placed in. So add a contextual filter "Taxonomy: Parent". In "if filter value is NOT available", choose to provide a default value, taxonomy term ID from URL, and make sure to tick "load default filter from node page".

You can optionally fine-tune the settings by limiting it to your taxonomy vocabulary and define multiple value handling.

Next, save this view and place the newly created block on your content page. You do so in "Structure / Block layout". Go to the region you like to show the block in, e.g. "Content". Click the "Place block" button and find your view block.

Configure it to display only at your content type.

EDIT:

And if you like to show fields of content that has the child terms assigned, then you can add a relation in "Advanced / Relations" to content that has the term, change the view type to be a field view (if not already), and add the fields from your related content. (Didn't try this one, but should work as well.)
> 0 votes

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


# Question
Title: list links to nodes in another node with Views
I'm currently struggling with the following scenario:

There are two different Content Types:

* Offer
* Event

What I want to achieve is this:

There are 6 offers and each of those offers have several events that are nodes as well, in those event nodes there's a field for the date when the event takes place. For example: one of the offers is a photography workshop and I want a section in this node where the dates of the events (as a link to the event node) are listed.

~~I was thinking about creating a taxonomy with all the offers, whenever a event is created you have to select one of the tags. In a second step I thought Views would be a good way to create this list of all the event dates to a specific offer by showing Content of type Event but I don't know where to go from there because I can't specifiy that it should only show the events with a specific tag.~~

**EDIT**

Alright I think I'm a bit closer to the solution, but I'd still need some assistance from you guys.

What I did: Besides Views, I installed EVA. Created a View that is neither a Page nor a Block with the following settings:

Fields
– Filter Criteria
–– Content: Type (=Event)

Added an Entity Content with the following settings:

Entity content settings
– Entity type: Node
– Bundles: Offer

Not sure where to go from there though. Can I add some kind of `Contextual Filters` or `Relationships` between the Offer and the Events?

# Answer
> 1 votes
Assuming the offer node holds a reference to the event node, this can easily be done without any custom modules.

* Create a view with content type = offer.
* Create a relationship to the event using 'A bridge to the Content entity that is referenced via', not 'A bridge to the Content entity that is referencing Content via'.
* Add the date field into the field and use the relationship.

So for example, if it's a table view and you have one offer and two events, you should have two rows. offer 1 and event 1 date, and offer 1 and event 2 date. If you want them combined into offer 1 and event 1 date + event 2 date, then you can combine them using views distinct filter.

# Answer
> 0 votes
You can use node reference field for this scenario nodereference\_field

---
Tags: 7, views, entities
---


# Question
Title: How to substitute a value of an exposed filter for views?
I have a view with an exposed filter with taxonomy tree. Each term can be selected or unselected. If some parent term is selected but every of its child terms isn't selected then all the children terms also should be added to view filter.

But if I select one children term after it, the view should be filtered only by this children term (not by all children terms).

I decided to solve this problem trying to add children terms in the view parameters. By my idea, the view should use this parameters for its execution.

But, unfortunately, I can't understand where to add these params. I tried to use different view hooks, having tried to add them in vars `$view->exposed_data`, `$view->exposed_raw_input`, `$view->exposed_input`. No result.

I also tried to add them in the submit function of the exposed filters form. No positive result also.

Could you clarify me, where can I add new params into the view ?

For example, a user selected term1. In this case term2 and term3 should be added to the view parameters programmatically. And after it, views should use parameters term1, term2 and term3.

I hope, I've described the problem clearly

# Answer
> 0 votes
I solved a similar issue using hook\_views\_pre\_render(&$views).

---
Tags: 7, views
---


# Question
Title: Change the product status after checkout_complete
I have one 'select' field in product page it has value 'Open', 'Closed'.I want to changed to 'Closed' after completing the first order of this product.

There is one issue which someone answered for Drupal 7 and it is done by using 'Rules' module. How I can change the value of a commerce product field after Completion process?

How I can do that using Hooks and without Rules module?

EDIT: I feel we can use below hooks. But how we can find the product and change the custom field value of the product?

```
function hook_commerce_checkout_complete($order) {
  if($order->status == 'completed') {
  }
}

```

hook\_commerce\_checkout\_complete

EDIT 2:

Got the solution for Order Complete event - https://medium.com/@sumanthkumarc/writing-event-subscriber-for-order-complete-event-in-drupal-8-commerce-2-x-196292330b1c. Now question is How I can modify the product custom field value?

```
public function orderCompleteHandler(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();
  $items = $order->getItems();
}

```

How can i get the product id from the order items and change the custom field(`field_prodstat`) value

# Answer
> 0 votes
You'll want to use the commerce hook\_commerce\_checkout\_complete which runs after a order is complete (AKA paid for)

http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21checkout%21commerce\_checkout.api.php/function/hook\_commerce\_checkout\_complete/7

That provides the order and you'll just need to get the product ID from that $order variable, load it with product\_load(), change the value you want and then save

# Answer
> 0 votes
1) Use Event Subscriber for 'Order Complete' event.

2) You can get the purchased product from the `$order` and use below code to update product custom field.

```
public function orderCompleteHandler(WorkflowTransitionEvent $event) {

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  // Order items in the cart.
  $items = $order->getItems();

  //I just hard coded index. You can write foreach loop for getting multiple products.
  $purchasedEntity = $items[0]->getPurchasedEntity();

  $product = $purchasedEntity->getProduct();
  $product->set('field_custom_field', 'Updated field');
  $product->save();

}

```

---
Tags: 8, commerce
---


# Question
Title: How to restrict users to certain Content Types?
A site that I'm working on will have lots of users managing the content. Unfortunately their workflow dictates that certain people only have access to certain content types. There isn't a method to their madness, so using roles to do this will result in a nightmare to maintain really fast.

The Content Access module will not work for this. It mentions Authors, but there doesn't seem to be any configuration for this. And managing on a per node basis won't cut it.

I'm thinking the most logical way would be checkboxes on the edit user account page for admins to set. This should limit them to creating and updating content that they have been explicitly allowed to. And the admin menu should only show the content types they were assigned to.

Is there a way to implement this? Or any pointers in the right direction for the appropriate hooks?

# Answer
It looks like you should give it a try to use the Group module. You'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

From the details included in your question, it seems that possibly you'd only need 1 group type. And if you then would create 1 group for each of the Content Types involved, you might be close to a working solution.

***More info:*** What's the purpose of the Group module and how to get started with it?
> 0 votes

# Answer
Lots of ways to skin this cat, but in a custom implementation: A hook\_form\_alter and hook\_node\_view\_alter that calls a custom function that checks the user's privileges before displaying the node page or node edit page. Now the user privilege can be stored in many ways of your choosing, whether it's an actual table you store access in (UID, content\_type, access boolean), or a user field that can store information like \['content\_type\_1'=\>true,'content\_type\_2'=\>false'\].
> 0 votes

# Answer
You can try Node View Permissions
> 0 votes

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


# Question
Title: Register a custom AttributeBag to the SessionManager
How can I register a new custom AttributeBag into the session manager? I have this custom module and want to contain the session stuff in a specific attributeBag.

But when I try to call the registerBag() method from my code I get an error that it's not possible due to the session already being started.

Can I hook into the session manager service from my service container definition file? The session manager does not seem to support a service\_collector.

Thnx.

# Answer
The preferred way of storing user specific information to the session is using the user's private tempstore. You don't have to go down to the attribute bags.

You can access this tempstore through the `user.private_tempstore` service:

```
// Get tempstore. Within classes use dependency injection instead.
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
// Set my_variable_name.
$tempstore->set('my_variable_name', $data);

```

You can then retrieve the values again from session by using the get method:

```
// Get tempstore. Within classes use dependency injection instead.
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
// Get my_variable_name data.
$data = $tempstore->get('my_variable_name');

```

Please note, that the private tempstore is available for logged-in users only, not for an anonymous session. (An according core change request to allow anonymous session private tempstore is in review.)
> 1 votes

---
Tags: sessions
---


# Question
Title: How to inject the database connection into a custom service?
I have a custom module that pulls data from several different external databases that have been defined as connections in settings.php. The current setup includes a series of controllers that have a service I have created called DataAccess injected into them. My DataAccess service has several methods that accept a `$schema` parameter and based on this I use the following each time:

```
$connection = Database::getConnection('default', $schema);

```

I can then query each database as needed with this setup. I thought about injecting Database into my service from the Drupal container, but I would then need a base class like ControllerBase's create method to get that service in the first place. What would be the correct way to do this as it isn't a controller - would I use a different base class here? I am new to Drupal 8 development and trying to ensure I am following the best practices, but at the same time I don't want to overcomplicate things.

Any advice?

# Answer
You can't inject `Drupal\Core\Database\Database`, it's a container of static functions, constants, & variables for core database functions.

If you'd like to inject the `Connection` object, that is be possible, and is more like something you want (unless you have scenario where **setting.php** is dynamic an all possible values of `$schema` can't be known).

You can follow the example Drupal sets with the default `@database` class in **core.services.yml**:

```
  database:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default]

```

In your **mymodule.services.yml** you can define the factory/arguments for each database connection you have, plus your `DataAccess` service class with the injected connections.

```
services:
  mymodule.database_schema:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema]
  mymodule.database_schema2:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema2]
  mymodule.data_access:
    class: Drupal\mymodule\DataAccess
    arguments: ['@mymodule.database_schema', '@mymodule.database_schema2']

```

From there you can store the database connections in `DataAccess`'s constructor and reference them as required by `DataAccess`'s methods.
> 7 votes

# Answer
As commented on another answer, the answer here is probably, you can't.

The database API isn't fully converted to use services. I tried to do it for quite some time, in https://www.drupal.org/node/1811730, but didn't succeed and neither did others.

So, for now, you need to use the static methods. The best you can do is wrap it in a method or another service that does just that to simplify mocking it when you want to write unit tests.
> 6 votes

# Answer
At this moment I'm using this code to inject the database service:

**\*.services.yml**

```
services:
  onlyone:
    class: Drupal\onlyone\OnlyOne
    arguments: ['@entity_type.manager', '@database', '@language_manager']

```

**Drupal\onlyone\OnlyOne**

```
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Language\LanguageManagerInterface;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, Connection $connection, LanguageManagerInterface $language_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->connection = $connection;
    $this->languageManager = $language_manager;
  }

```
> 4 votes

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


title: admin/content/file missing

text:
# Question
Title: admin/content/file missing
I have some problems with files. Everyone is talking about admin/content/file, but I just don't have the link under /admin/content, and going to the url by hand returns me to admin/content.

I seem to be pretty much up to date (drupal 7.50, file\_entity 7.x-1.5) and media is working (it's just buggy in strange ways).

Where should I look to find why the link is not showing under /admin/content ? Iow, who should be providing the view ? That would give me a clue.

# Answer
You have to install and enable the File Entity (fieldable files) module:

https://www.drupal.org/project/file\_entity

7.x-2.12 works flawlessly.
> 1 votes

---
Tags: 7, views, files
---


# Question
Title: Drupal 8 Commerce 2 Trigger custom mail to product author
We can get the `uid` for purchased product after checkout using Event Subscriber.

How to sent mail to product author with product details when someone checkout the product. We can get all the details in `$order`.

# Answer
> 0 votes
This is described in the Commerce 2 documentation:

> In our case we want to send the email after the transition to the Fulfillment state has occurred. We therefore need to create an event subscriber that listens to the commerce\_order.fulfill.post\_transition event.

```
// my_module/src/EventSubscriber/OrderFulfillmentSubscriber.php

    namespace Drupal\my_module\EventSubscriber;

    use Drupal\state_machine\Event\WorkflowTransitionEvent;
    use Drupal\Core\Language\LanguageManagerInterface;
    use Drupal\Core\Mail\MailManagerInterface;
    use Drupal\Core\StringTranslation\StringTranslationTrait;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;

    /**
     * Sends an email when the order transitions to Fulfillment.
     */
    class OrderFulfillmentSubscriber implements EventSubscriberInterface {

      use StringTranslationTrait;

      /**
       * The language manager.
       *
       * @var \Drupal\Core\Language\LanguageManagerInterface
       */
      protected $languageManager;

      /**
       * The mail manager.
       *
       * @var \Drupal\Core\Mail\MailManagerInterface
       */
      protected $mailManager;

      /**
       * Constructs a new OrderFulfillmentSubscriber object.
       *
       * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
       *   The language manager.
       * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
       *   The mail manager.
       */
      public function __construct(
        LanguageManagerInterface $language_manager,
        MailManagerInterface $mail_manager
      ) {
        $this->languageManager = $language_manager;
        $this->mailManager = $mail_manager;
      }

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = [
          'commerce_order.fulfill.post_transition' => ['sendEmail', -100],
        ];
        return $events;
      }

      /**
       * Sends the email.
       *
       * @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
       *   The transition event.
       */
      public function sendEmail(WorkflowTransitionEvent $event) {
        // Create the email.
        $order = $event->getEntity();
        $to = $order->getEmail();
        $params = [
          'from' => $order->getStore()->getEmail(),
          'subject' => $this->t(
            'Regarding your order [#@number]',
            ['@number' => $order->getOrderNumber()]
          ),
          'body' => $this->t(
            'Your order with #@number that you have placed with us has been processed and is awaiting fulfillment.',
            ['@number' => $order->getOrderNumber()]
          ),
        ];

        // Set the language that will be used in translations.
        if ($customer = $order->getCustomer()) {
          $langcode = $customer->getPreferredLangcode();
        }
        else {
          $langcode = $this->languageManager->getDefaultLanguage()->getId();
        }

        // Send the email.
        $this->mailManager->mail('commerce_order', 'receipt', $to, $langcode, $params);
      }

    }

```

---
Tags: 8, commerce
---


# Question
Title: Custom field: process submitted before storing
I've created custom field type and widget plugins in D8.

I am presenting an element in my widget as checkboxes, but I need to transform the resulting array into text delimited by pipes. i.e. `a|b|c`.

How would I approach this in the field widget?

# Answer
> 0 votes
`messageFormValues` in the widget class did the job.

```
class MyDefaultWidget extends WidgetBase {
  ...
  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // Change the format of $item['sections'] from array to pipe delimited string.
    foreach ($values as &$item) {
      $sections = [];
      if (is_array($item['sections'])) {
        foreach ($item['sections'] as $s) {
          if ($s !== 0) {
            $sections[] = $s;
          }
        }
      }
      $item['sections'] = implode('|', $sections);
    }
    return $values;
  }
  ...
}

```

---
Tags: 8, entities
---


# Question
Title: Have Select Dropdown of Taxonomy but allow user to enter new term
Is there a way to have my Taxonomy Terms in Dropdown but also allow the user to enter a new term (Like autocomplete widget does) if they don't see their term in the select list?

So essentially I would have a backup to allow the user to create one.

My use-case is I have a bunch of businesses, when someone adds a new one, if they don't see their business type, they can just add a new one.

# Answer
> 0 votes
**Install the Select or Other module**

You can use the Select or Other module to add a dropdown with an *Other* option.

Selecting *Other* prompts the user to enter the new value in a separate field.

Your question asked to add the new business type directly; this module adds it to a separate field (however, an admin can later add the business type as a taxonomy term if you wish).

**Advantages of this approach**

* You get admin approval of user input. This way a bad user can't enter something like *Sex sex sex* which then appears as a business type on your site.
* You have control over how long the list gets instead of letting users add an unlimited number of terms.

**Coding it yourself**

You can also code this yourself pretty easily using the States API instead of installing the Select or Other module.

Add a new text field, `field_businesstype_other`, to store the *Other* values for `field_businesstype`.

Create a taxonomy term named *Other* in your "business type" vocabulary.

Then, in `hook_form_alter()`, add something like this:

```
  $form['field_businesstype_other']['#states'] = array(
    'visible' => array(
      'select[name="field_businesstype"]' => array(
        array('value' => '123'),
      ),
    ),
  );

```

Replace `123` with the term ID of the *Other* term you created.

---
Tags: taxonomy-terms, entities
---


title: How to create a Drupal 8 distribution

text:
# Question
Title: How to create a Drupal 8 distribution
So I have this Drupal 8 site with its custom theme, some blocks, menus, content types, views and other more stuff. What I am required to do is create a site distribution of this site for drupal.org, but I have absolutely no idea of how to do it.

I created the profile folder in **doctoot/profiles** and created the info.yml with the profile basic information. I also have the **.install** and **.profile** files but they are empty. These files were created using `drupal generate:profile`

After that I exported the config YAML files using `drush config:export`, but they were created in **config\sync** in the profile folder, but I saw in another distributions that these files are located in **config\install** rather than **sync**,and I don't know if that makes a difference.

I don't have anything besides that and I don't know what to do after that to configure things in the distribution in terms of theme and configuration. I have the project page in drupal.org already with the git configuration. Hope you can help me with this issue.

# Answer
> 1 votes
What you need is to create an installation profile.

Follow the instructions on drupal.

How to write a D8 profile

Move the files from the config/sync folder to config/install folder. Be sure to delete core.extension.yml and remove all UUIDs.

Optionally, you can try this project:project config\_installer

---
Tags: users, distributions, installation-profiles, 8
---


# Question
Title: Front page has a shortened form of my articles
In my Main Page Content block, I'm getting a list of recent articles with a "Read more" link.

What do I do if I want the whole article to appear on the front page?

# Answer
I'm going to make a couple of assumptions that you are using Drupal 8, and that the front page is using the default Frontpage view. In this case, you can edit the view by logging in as an administrator and editing the view page under Structure - Views - Frontpage (or go to the path admin/structure/views/view/frontpage/edit/page\_1). In the first column of this page there is a section called FORMAT. Under the FORMAT section there is a Format and Show row. My guess is Show is set to show content using the teaser view mode. You can change this to show the full content by clicking on "Teaser" and selecting "Full content". After you save the view then you should see the full content of the article on the front page.
> 1 votes

---
Tags: blocks
---


# Question
Title: Create a custom block programmatically and specify region and pages on which created block must shown on
For create block programmatically I use

```
$block = BlockContent::create([
  'info' => 'block 3',
  'type' => 'basic',
  'langcode' => 'en',
  'body' => [
    'value' => '<h1>Block's body</h1>',
    'format' => 'full_html',
  ],
]);
$block->save();

```

It works good enough but is it possible also to specify region and then on which pages created block must shown on?

# Answer
OK, at least I managed to solve this problem.

Below the full code that create block and then bind it to region and also set pages on which created block must shown on. Maybe it can helps anyone.

```
 $block = BlockContent::create([
         'info' => 'block242',
         'type' => 'basic',
         'langcode' => 'en',
         'body' => [

          'value' => '<h1>Block's body</h1>',
            'format' => 'full_html',
           ],
          ]);

     $block->save();

       $placed_block = Block::create([
         'id' => 'block242',
            'theme' => 'scholarly',
'weight' => -7,
'status' => TRUE,
'region' => 'sidebar_second',
'plugin' => 'block_content:' . $block->uuid(),
'settings' => [],
'visibility' => [
  'request_path' => [
    'id' => 'request_path',
    'negate' => FALSE,
    'pages' => '/your_page',
  ],
],
        ]);
    $placed_block->save();

```

And of course, very very BIG thanks to user 4k4. Without his help I'd never do this.
> 5 votes

# Answer
You have to create a block config entity to place a block:

```
use Drupal\block\Entity\Block;

  $placed_block = Block::create([
    'id' => 'block_machine_name',
    'theme' => 'classy',
    'weight' => 0,
    'status' => TRUE,
    'region' => 'footer',
    'plugin' => 'block_content:' . $block->uuid(),
    'settings' => [],
    'visibility' => [
      'request_path' => [
        'id' => 'request_path',
        'negate' => FALSE,
        'pages' => '/path',
      ],
    ],
  ]);
  $placed_block->save();

```
> 5 votes

---
Tags: 8, blocks
---


# Question
Title: HTML tags not supported when sending emails in Drupal 8
This is my code to sending email

```
   function hook_mail($key, &$message, $params) {
     $options = array(
    'langcode' => $message['langcode'],
  );

  switch ($key) {
    case 'create_article':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      // $message['headers']['Cc'] = $params['cc'];

      $message['subject'] = 'SUBJECT';
      $message['body'][] = Markup::create($params['message']);
      break;
  }
}

```

Mails are getting without any issue.But some of the HTML tags are not supporting Eg: **HTML bold,italics....** I have also configured SMTP authentication.

# Answer
You can't send HTML email with Drupal 8/9/10 "out of the box."

## Drupal 9/10

To send HTML email with Drupal 9/10, you should use the Symfony Mailer module. This module replaces the mail system in Drupal core to use Symfony's system, which includes support for HTML among many other things.

## Drupal 8

To send HTML email with Drupal 8, you can use the Swift Mailer module (now unsupported, just like Drupal 8-- time to upgrade people), which has the following features:

> * Sending e-mails directly through a SMTP server of your choice, a locally installed MTA agent such as sendmail or the mail functionality provided by PHP.
> * Sending HTML (MIME) e-mails.
> * Adding file attachments to e-mails.
> * Adding inline images to e-mails.

The Commerce 2 documentation includes a tutorial on how to install and configure the Swift Mailer module.
> 2 votes

# Answer
In D7 you need to install Mime Mail and in your code add:

```
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';

```

Hopefully it's still the same on D8, give it a try.
> 0 votes

---
Tags: 8, emails
---


# Question
Title: How to add block to "add/edit" content page?
is there a way to add views block to add/edit content pages? I have two content types and one of them has Taxonomy term baste with unique terms (one term per node), when creating new node I want to have block with unused terms. I tried to accomplish this using Markup module but no success, and Display suite and Panels didn't worked.

# Answer
Here's how to display a block on node add/edit pages in Drupal 8:

Go to `Structure -> Blocks`. Select the block layout page for the theme you use to add/edit nodes. This is usually the admin theme, but it may also be the standard theme for your site if you want to display the block to non-admin users. If you want to show the block to both admin and non-admin users, you may need to configure the block settings (as described below) for both the admin theme and the standard theme.

On the block layout page, click **Edit** on the block you want to display.

Under **Visibility**, click **Pages**.

In the text field, enter:

```
/node/add/*
/node/*/edit

```

For Drupal 7, don't use the first slash:

```
node/add/*
node/*/edit

```

The `*` is a wildcard that says "any content/value can go here."

Then check the radio button for **Show for the listed pages**.

If you also want to limit the block to only show for certain content types, you can use the **Content types** option above **Pages**.
> 3 votes

---
Tags: blocks
---


# Question
Title: Why Drupal Commerce 2 Installs in a Sub Directory
Why Drupal Commerce 2 Installs in a subdirectory ? Is there any way we can install that in public\_html directory so website can be accessed directly through domain ?

Edit

let me try to clear my question. Actually when we setup commerce 2 through

composer create-project drupalcommerce/project-base mystore --stability dev

it setups the site in mystore directory so if I need to access my site I will need to enter this url mydomain.com/mystore

what I want to know if it's possible to install Drupal commerce 2 directly in public\_html directory ??

# Answer
> 0 votes
`composer create-project drupalcommerce/project-base $PROJECTFOLDER --stability dev` installs Drupal and Drupal Commerce. It's a composer project template.

The webroot than is $PROJECTFOLDER/web. You have to adjust your webserver configuration to point to to correct webroot. You shouldn't install your entire project to an "public" public\_html folder.

---
Tags: commerce, composer
---


# Question
Title: Is Drupal contact form securely encrypted?
In Germany, it is mandatory to by law to use secure contact forms (secured by TLS for example) when you are a website owner. Is the Drupal 7 contact form secure in this regard?

# Answer
> 7 votes
No. No form, in any website, is inherently "secure" or encrypted. If your requirement is to serve and submit the form over TLS, you'll need to set that up on your server/host as a separate task.

Once you have, Drupal will happily serve any page over https, and submit forms in the same manner.

The only thing you might want to consider from a Drupal point of view is to un-comment the lines in the default .htaccess which force-upgrade all requests to https. If your server isn't Apache that'll have to be done elsewhere.

---
Tags: emails
---


title: How to modify an existing view join?

text:
# Question
Title: How to modify an existing view join?
I am trying to modify an existing views join.

Let's say I am trying to remove the 'langcode' condition.

What I have so far:

```
function mymodule_views_query_alter(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\query\Sql $query) {
    $joindata = $query->getJoinData("node__field_joined_whatever", "node_field_data");

//$joindata contains the join I need, so far so good

    foreach($joindata->extra as $ix=>$val) {
      if (isset($val['field']) && $val['field'] == 'langcode') {
        unset($joindata->extra[$ix]);
      }
    }
//here I have modified join object, but there is nothing like '$query->setJoinData()'
...
}

```

Does anybody know how to put my modified join back to the query?

# Answer
Usually, you should control join type using views Advance relationship options. By enabling "Require this relationship" you are telling Views to use "INNER" Join instead of using "LEFT" Join. If this option is somehow not working here is how I would solve this problem.

```
use \Drupal\views\ViewExecutable;
use \Drupal\views\Plugin\views\query\QueryPluginBase;

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   // check your view ID:
if ($view->id() === 'id') {
 //Get your table info object;
  $table = $query->getTableInfo('table');
if (isset($table['join']->type) && $table['join']->type === "INNER") {
//Change your Join type;
 $table['join']->type = 'LEFT';
   }
 }
}

```
> 6 votes

# Answer
Another example, which can be useful. How to add your own extra condition to join. In my case, it checks that joined entity has a title not equal to management.

```
if ($view->current_display === 'my_display') {
  $table = $query->getTableInfo('MY_TABLE');
  // Make 'extra' and array if it's empty.
  $table['join']->extra = empty($table['join']->extra) ? [] : $table['join']->extra;
  $table['join']->extra[] = [
    'field' => 'title',
    'value' => 'management',
    'operator' => '!='
  ];
}

```

You can use an alias of the table instead of "MY\_TABLE".
> 4 votes

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


title: How to add a profile tab via views

text:
# Question
Title: How to add a profile tab via views
On the profile page that is `/user/1` for e.g how to add tab MY ADS to be `/user/1/myads`?

# Answer
Create a view page and add a menu item entry: "Default menu tab" to "Menu tab" and select "User Menu" in dropdown in your view.
> 1 votes

# Answer
* Create a view page
* Change the path to: **user/%user/myads**
* Change menu to '**Menu tab**' and make sure the parent is '**-- My account**'
> 0 votes

---
Tags: views, 8
---


# Question
Title: Why does CACHE_TEMPORARY have the same value as DRUPAL_NO_CACHE
I'm trying to change the cache of my block (hook\_block\_info\_alter) but it seems if I change from CACHE\_TEMPORARY to DRUPAL\_NO\_CACHE, it doesn't make a difference. Drupal declared them like this:

```
define('CACHE_TEMPORARY', -1);
define('DRUPAL_NO_CACHE', -1);

```

Why do we have the same value if they're meant to be different? How can I change the value in hook\_block\_info\_alter?

# Answer
They have different uses. `CACHE_TEMPORARY` and `CACHE_PERMANENT` are values that `cache_set()` accepts as its last parameter. `DRUPAL_NO_CACHE` is used from Drupal only for blocks.

Two variables are allowed to have the same value, and this doesn't create confusion, as long as they are used in different context.

While both the variables have the same value, you should not use them when appropriate, at least because it makes more difficult to upgrade your code to Drupal 8.

In `hook_block_info_alter()`, as with other hooks for blocks, you should use `DRUPAL_NO_CACHE`. Keep in mind how the data passed as first argument to the hook is structured. With `$blocks['forum']['active']['cache'] = DRUPAL_NO_CACHE;` used in `hook_block_info_alter()`, you would avoid the block showing the active forum posts is cached from Drupal.
> 4 votes

---
Tags: 7, caching
---


# Question
Title: Elasticsearch-Connector: can't index with Search-API
Im using latest Drupal 8.x with Search-API 8.x-1.5 und Elasticsearch\_Connector 8.x-5.0alpha1.

I can add a cluster and via Search API I can also connect to the Elasticsearch Server. But when I try to add an Index via Search API the following error comes up:

```
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"No handler for type [string] declared on field [id]"}],"type":"mapper_parsing_exception","reason":"No handler for type [string] declared on field [id]"},"status":400}

```

Does anyone know of such an error and can help me with that?

# Answer
Elasticsearch has deprecated the `string` type in 5.x versions, and is now using `text` or `keyword`. (see https://www.elastic.co/guide/en/elasticsearch/reference/5.5/string.html)

In **/admin/config/search/search-api/`<CLUSTER>`/`<INDEX>`/fields**, you may change `string` by `text` in ID field. Considering this is an integer -id-, you may choose the type `integer`.
> 0 votes

---
Tags: search
---


# Question
Title: I want to enable a disabled input format
I considered 'restricted HTML' as unnecessary and set it ‘disable’. Because I thought it possible to re-enable. However, I have not found a disabled format on UI.

Since there is no choice, I decided to newly register. The same registration as the default machine name 'restricted\_html' conflicts. Imagine the data is left somewhere. I could not find it even if I looked for a database. Is it possible to restore by setting file or something?

I am using Drupal 8.4.2.

# Answer
> 8 votes
This is a known issue, though you are warned before you disable the textformat that this cannot be undone. See the issue Disabled text formats can't be seen in the GUI and the comment #60:

> It is possible to reenable disabled text formats with the configuration manager:
>
> * go to /admin/config/development/configuration/single/export
> * choose Text format as the Configuration type
> * choose the disabled text format as Configuration Name
> * copy the configuration
> * go to /admin/config/development/configuration/single/import
> * again choose Text format as the Configuration type
> * paste the configuration
> * **change "status" from false to true**
> * click on import
>
> Voilá, the text format is available again. This is working but not user friendly :(

# Answer
> 2 votes
More intuitive with drush :

```
drush ev '\Drupal::configFactory()->getEditable("editor.editor.<EDITOR_ID>")->set("status",true)->save(true);'
drush ev '\Drupal::configFactory()->getEditable("filter.format.<EDITOR_ID>")->set("status",true)->save(true);'

```

**Or**

Programmatically :

```
\Drupal::configFactory()->getEditable('editor.editor.<EDITOR_ID>')
                        ->set('status',true)
                        ->save(true);
\Drupal::configFactory()->getEditable("filter.format.<EDITOR_ID>")
                        ->set("status",true)
                        ->save(true);

```

---
Tags: 8, input-formats
---


# Question
Title: Programmatically set property based on other properties in a custom entity
I created a custom entity and want to programmatically set the title based on 2 other properties.

For example, the entity has `year` and `state` properties. When the entity is created, I want to populate the `title` property with `year state`.

How can I achieve this?

# Answer
> 2 votes
For a custom entity type, you can override `EntityStorage::doPreSave()` in your entity class:

```
function doPreSave(EntityInterface $entity) {
  parent::doPreSave();

  // Perform field manipulation here.

  return $entity->id();
}

```

---
Tags: 8, entities
---


# Question
Title: How can I programmatically create a node?
How can I programmatically create nodes with date and image fields?

I know I can do it in Drupal 7 with the following code.

```
global $user;

$node = new stdClass();
$node->title = "YOUR TITLE";
$node->type = "YOUR_NODE_TYPE";
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->status = 1; //(1 or 0): published or not
$node->promote = 0; //(1 or 0): promoted to front page

$existing_filepath = "/home/nzcodarnoc/sites/default/files/imported/picture.jpg";
$new_filepath = "public://picture.jpg";
$drupal_file = file_save_data(file_get_contents($existing_filepath), $new_filepath);
$drupal_file->alt = $node->title;
$drupal_file->title = $node->title;
$node->field_my_file[$node->language][0] = get_object_vars($drupal_file);
$node->birth_date[LANGUAGE_NONE][0]['value'] = time();
$node = node_submit($node);
node_save($node);

```

What is the equivalent code for Drupal 8?

# Answer
> 73 votes
The following code will help you to save an image in a new node.

```
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();

```

# Answer
> 17 votes
I think that object oriented way is more convenient, isn't it?

```
use Drupal\node\Entity\Node;

$my_article = Node::create(['type' => 'article']);
$my_article->set('title', 'My article');
$my_article->set('field_text', 'My text');
$my_article->set('field_image', FID);
$my_article->set('field_user', UID);
$my_article->enforceIsNew();
$my_article->save();

```

# Answer
> 16 votes
In drupal 8 entities are objects and as such, to create an entity is to create an instance of the entity's type class. If you know the class of the entity then you can either use the new keyword or the create function.

I.E. `$foo = new Foo();` or `$foo = Foo::create();`

If you don't know the class of entity (only the machine name) then you can use the request the Storage class like so: `\Drupal::entityTypeManager()->getStorage($entity_type_id)->create();`

To populate the fields of an entity you can either use the `$entity->set($key, $value)` method on the entity object or pass a `key=>value` array to the entity constructor. As such:

```
$foo = new Foo([
  'name'=>'bar',
  'baz'=> TRUE,
  'multi_value' => [
    'first',
    'second',
    'third',
  ]
]);

```

To save an entity you only have to call the `$entity->save()` method on the entity object.

Since files in drupal 8 are also entities you need to either pass the id of the file entity, or the actual file entity, as the value.

```
$file_1 = File::load(1);
$foo->set('bar_files', [
  $file_1,
  2
]);

```

Here is a code for your specific scenario:

```
$node_entity_type = \Drupal::entityTypeManager()->getDefinition('node');
// The [file_save_upload][1] function returns an array of all the files that were saved.
$poster_images = file_save_upload($upload_name, $validators, $destination);
$node = new Node([
  $node_entity_type->getKey('bundle') => 'movie',
  $node_entity_type->getKey('label') => 'Foo',
  'field_release_date' => '1/1/2015',
  'field_poster_image' => $poster_images,
]);
$node->save();

```

# Answer
> 10 votes
If you want to do it in the most clean way (testable), use `entity_type.manager` service:

```
$storage = $this->entityTypeManager->getStorage($entity_type_id);
$my_entity = $storage->create([
   ....
]);

```

The problem with `Node::create` function, that it is static call, and that's why you cannot really unit test your class anymore. Avoid doing static calls whenever it's possible. It will make your code more readable (because dependencies will be clear).

# Answer
> 6 votes
Following code is working for me

```
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

$node = entity_create('node', array(
'type' => 'article',
'title' => $form_state->getValue('title'),
'body' => array(
'value' => $form_state->getValue('body'),
'format' => 'basic_html',
),
'uid' => $uid,
));
$node->save();

```

# Answer
> 5 votes
Another way to create node with image is:

```
use \Drupal\file\Entity\File;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

$node = \Drupal::entityTypeManager()->getStorage('node')->create(array(
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
));
$node->save();

```

# Answer
> 1 votes
```
use Drupal\Core\Language\Language;

$definition = \Drupal::entityTypeManager()->getDefinition('node');
$values = [
    $definition->getKey('bundle') => 'basic_page',
    'langcode'                    => Language::LANGCODE_NOT_SPECIFIED,
    'title'                       => '...',
];
$entity = \Drupal::entityTypeManager()->getStorage('node')->create($values);

```

---
Tags: 8, nodes
---


title: Webform preview page

text:
# Question
Title: Webform preview page
I have a Multistep Webform. I have put Captcha in Preview page. But when i click "previous" button in preview page then Captcha asking for validation.

How do i remove captcha validation when i click previous button. And also how to put "term and condition" field in preview page.

# Answer
There are known issues with the CAPTCHA module on multi-step forms. https://www.google.com/search?q=drupal+captcha+multistep+form.

You can create a custom preview page by placing a Computed Twig/Token Element on the last page of a multi-step form.
> 1 votes

---
Tags: webforms
---