# Question
Title: Custom Theming Bootsrap Carousel with Paragraph Type
# Background Info:

I tried to create a custom theme for my carousel section and I am unable to get it to work. I have tried using the default carousel that Drupal comes with. I have tried using slide show views. Also I already know about Jim Bir's Custom Bootstrap Carousel and Slick Carousel but I am unable to use them since these extensions are still in Beta.

# Problem Statement:

The main avenue that I want to try to do is create a paragraph type called `Carousel Section` that has a reference to another paragraph type called \`Caraousel Slide'.

I wanted to use this design so that way I can organize the slides individually on my pages.

Within the `Carousel Slide` paragraph type it would have the following fields:

1. Slide Image
2. Slide Title
3. Slide Description
4. Slide Link(which is the location of where the slide will take you if you click on it.)

I would like to use a `preprocessor hook` do get grab these values from Drupal and display them in my twigg file.

# Question:

How can I achieve my problem statement? The bare minimal knowledge that I need is to how to at least get these fields to present themselves on my twig file and from there I can use HTML and CSS to make the carousel.

# Answer
> 7 votes
Unless you need some very specific logic, I wouldn't use preprocessing, but use Drupal's template suggestions and Twig instead.

I always use Slick over CDN, adjust for your own needs if necessary. All filenames are relative to the base directory of your theme or module. Replace UPPERCASE\_WORDS with corresponding machine names.

---

Create a library for your carousel:

`MYTHEME.libaries.yml`

```
carousel:
  version: 1.0.0
  js:
    https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js: {type: external, minified: true, defer: true, async: true}
    js/my_carousel.js: {}
  css:
    layout:
      https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.min.css: {type: external, minified: true}
      css/my_carousel.css: {}

```

---

`js/my_carousel.js`

`behaviors` are the drupalesque counterpart to jQuery's `.ready()` handler (e.g. even if your carousel is loaded inside a view with ajaxified paging, it will still trigger `.slick()` after every paging).

```
(function ($, Drupal) {
  Drupal.behaviors.myCarousel = {
    attach: function (context, settings) {
      $('[data-slick]', context).once('myCarousel').slick();
    }
  };
}(jQuery, Drupal));

```

---

`templates/paragraph--CAROUSELCONTAINER.twig.html`

The container template would be the place where you alter your slick options, e.g. if you have a integer field "Autoplay speed" on your container paragraph, you could add to `my_carousel_options` using `paragraph.field_autoplay_speed.0.value`

```
{% set my_carousel_options = '"autoplay": true' %}
{{ attach_library('MYTHEME/carousel') }}

<div{{attributes}} data-slick="{{ my_carousel_options }}">
  {{ content.FIELD_CONTAINING_SLIDES }}
</div>

```

---

`templates/paragraph--CAROUSELSLIDE.twig.html`

Here you can decide what to render on each individual slide

```
{# maybe you also need an additional wrapper <div> around each invidiual slide #}
<a href="{{ paragraph.MY_LINK_FIELD.0.url }}">
  {{ content.MY_IMAGE_FIELD }}
  {{ content.MY_TITLE_FIELD }}
  {{ content.MY_DESCRIPTION_FIELD }}
</a>

```

If necessary you can further adjust the HTML markup of your slide subfields using something like `templates/field--paragraph--MY-DESCRIPTION-FIELD.html.twig`

---

Optional:
If you want to get rid of some container `<div>`s around fields automatically rendered by Drupal, create a wrapper-less field template. E.g. I wanted to remove *ALL* `<div>`s and field labels rendered by any paragraph host field:
(this is global for every paragraph host field, change it to a template suggestion matching only your carousel if you don't want this)

`field--entity-reference-revisions.html.twig`

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

---

Finally create your own CSS styles for your carousel in `css/my_carousel.css` and rebuild the cache so Drupal discovers your new template files.

This basically is how I'm creating carousels on every of my projects. Not tested with Bootstrap theme though, this is some sort of general purpose tutorial.

# Answer
> 2 votes
The Bootstrap Paragraphs module might be your best bet, as a quick and dirty drop-in solution. You say you're using Bootstrap and Paragraphs, and I believe that module might include nearly exactly what you're looking for:

* a "Carousel" paragraph type,
* containing a paragraphs reference field called "Slide Content" that
* references another paragraph type called "Image".

If you'd rather use your own paragraph types, then perhaps the paragraph--bp-carousel.html.twig Twig file contained in that module could be useful for you to copy / paste some implementation details regarding the Bootstrap carousel settings.

For what it's worth, I've implemented a simplified carousel in my IU Paragraphs module, which also uses nested paragraph types, like Bootstrap Paragraphs, just with quite a bit less code in the Twig templates, that might be a cleaner start for you to look at:

* The outer Twig template paragraph--iu-carousel.html.twig renders the wrapper div for the carousel.
* The inner Twig template paragraph--iu-image.html.twig renders the `<img>` tags themselves, and optionally wraps them in a `<figure>` and `<figcaption>` tags if a caption is provided.
* The carousel javascript is a custom implementation to load Slick slider based on a custom class (`rotator`), however that javascript to load the carousel is provided by Indiana University's web framework (http://assets.iu.edu/web/3.x/js/iu-framework.js), so that part of it may not be much help to you, but the Twig and HTML are clean and should get you started.

Anyway, I hope this might help as reinforcement of the general steps outlined above in Hurdi's answer. Good luck!

# Answer
> 1 votes
Since you've organized your data fairly well into paragraphs and paragraphs have standard class names for use with CSS and JS (depending on the theme you're using), a very easy solution will be to include a slider library (I use Slick) and write a behavior in your theme's JS file to initialize the slideshow.

* Include the module which provides the slider - I'll assume it is Slick for the answer
* Include the slick libraries in your theme: `slick/slick`.
    + Alternatively, you can write some PHP to include the `slick/slick` as an attachment to your `carousel` paragraph type with something like `hook_preprocess_paragraph()` or some other hook.
* Write a behavior like `Drupal.behaviors.custom_carousel = { ... }`. And for every `paragraph--type-carousel` initialize a carousel with the parameters you want.

I've done this with many JS libraries, especially when they don't have a nice integration with Drupal.

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


# Question
Title: How can I automate the "Clear Cache" everyday?
Currently we have to clear it manually everyday logging in to admin console and browsing to Home-\>Administration-\>Configuration-\>Development-\>Performance

Is there way we can automate this job in Drupal 8. We tried with "cron", but that didn't help.

# Answer
Despite you saying it didn't work with cron, I would suggest using cron in some way. :)

The CacheFlush module claims to allow configuration of this via its UI (although I haven't used it so cannot personally vouch for it).

If you are implementing custom code, drupal\_flush\_all\_caches() will handle the flushing for you.

The Rules module also allows acting on Cron runs. Using rules you could either write a custom action that uses drupal\_flush\_all\_caches() or find a module that provides one (I haven't seen any for D8 but that doesn't necessarily mean one doesn't exist).

You could also potentially do it outside of Drupal, using a cron job on your server to call `drush cr` for your site.

**Aside:** I would suggest also considering why you need to do this and what alternatives there are. I can't really think of many (any?) cases where I would want to do this instead of just invalidating the cache of specific content entities/pages as they are changed.
> 6 votes

---
Tags: caching, cron
---


# Question
Title: How to render field of one type of node to another type node
I have two types of nodes: `metals` and `prices`.

Metals has two fields:

```
field_gold

```

and

```
field_silver

```

How to render this fields on node--prices.html.twig (not node--metals.html.twig)

Please, help me!

# Answer
After you made reference between `prices` and `metals` implement `hook_preprocess_node` like the following:

```
use Drupal\node\Entity\Node;
/**
 * Implements hook_preprocess_node().
 */
function MyTemplate_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'prices') {
    $price_node = $variables['node'];
    //- Get reference target id
    /**
     * @TODO: change field_reference_metals by the referenced field.
     */
    $metals_node_target_id = $price_node->field_reference_metals->getValue()[0]['target_id'];

    //- Load metals referred node
    $metals_node = Node::load($metals_node_target_id);

    //- Set field_gold from metals node
    $variables['field_gold'] = $metals_node->field_gold->value;
    //- Set field_silver from metals node
    $variables['field_silver'] = $metals_node->field_silver->value;
  }
}

```

In `node--prices.html.twig` template add:

```
   {{ field_gold }}
   {{ field_silver }}

```
1. Change `MyTemplate` by your custom theme/module name.
2. Change `field_reference_metals` by the field from your prices content type referred to metals.
3. clear cache.
> 1 votes

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


# Question
Title: hook_views_pre_render - how to print field x after each loop
I have a grouped view that displaces content containing multiple entity references. I have a field that generates multiple times, because of those entity references. I've looked into modifying views-view-group.html.twig with no luck. Now I'm trying to figure out how to use hook\_views\_pre\_render to accomplish this.

(If it comes up... no, using 'Views Field View' didn't work)

I currently have results like this:

```
Group Title
 - Item one
   -- entity-ref1
   **-- Field-x**
   -- entity-ref2
   **-- Field-x**
```

I want this:

```
Group Title
 - Item one
  -- entity-ref-item1
  -- entity-ref-item2
  **-- Field x**
```

I've already got the hook set up in a module. I'm just trying to figure out how to use it to rearrange fields and output Field x - After the rest of each entry has output. I haven't found anything.

UPDATE: I tried this solution for removing duplicates - BUT.. it's removing the multiple entity references along with the multiple Field X. I just one Field X pared down to one:

```
    function webinar_rearrange_views_pre_render(\Drupal\views\ViewExecutable $view) {
      if ($view->id() == 'webinars') {
        $filtered_nids = array();

        foreach ($view->result as $key => $row) {
          if (in_array($row->nid, $filtered_nids)) {
            unset($view->result[$key]); // remove the duplicate
          } else {
            $filtered_nids[] = $row->nid;
          }
        }
      }
    }

```

# Answer
This isn't the answer I was looking for, but it solves the issue until a better method is found.

Basically, the problem is that a specific field - a custom text 'find out more' field was showing three times (for example) when a row had three authors (entity ref. fields)

Since the 'find out more' field was the last item in each row, I overrode the "views-view-unformatted" twig template and, inside of the 'for' loop I added an extra bit, to change the class of the last item. Then, with CSS, I could hide the fields with 'views-row' class, and display 'views-row-last'

Here's what I added to that twig file:

```
    {% if loop.last %}
        {%
        set row_classes = [
          default_row_class ? 'views-row-last',
        ]
       %}

    {% endif %}

```
> 0 votes

---
Tags: views, 8, hooks
---


title: Add a "footer" to each group?

text:
# Question
Title: Add a "footer" to each group?
I'd like to build a custom "Add more" link under each *group by* in a view. I'd also need the node ID of the *group by* field as a token.

Is this possible?

# Answer
> 0 votes
If you need **nid** of current node as token, then just add **Content: Nid** in field list, and check **exclude from display** before saving it. Move this field at the top of the list & you will be able to use it as token in any other field under **Rewrite Result**.

But if you want to use **nid** of **entityreference** field as token, then you need to a **Relationship** under **Advance** tab in your view. Then after follow the same process which I explained in first paragraph. But this time you will have to use your added relationship.

For custom **Add More** link, just add **Global: Custom text** in field list & put HTML for this Add More link.

# Answer
> 0 votes
You can start by overriding Style Output plugin for your view by copying the default template `views-view-unformatted.tpl.php` to your theme's folder and renaming it to `views-view-unformatted--your-view-machine-name.tpl.php` (machine name of the view is used, so that only the particular view is overridden).

then you could do something like this in the template (comments included):

```
<?php if (!empty($title)): ?>
    <!-- H3 outputs the title of the group -->
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

<!-- adding footer to each group -->
<div class="view-group-footer">
    <?php
        // $id is the number of the view row
        // each row will have data of the entity_refence field as it is used for grouping
        // we need to grab the target_id (node ID) of the entity that is used to form the group
        // because the target_id of each row inside the group will be the same - we only need to grab it once and then form the custom link
        // so we grab it from the last row of the group, otherwise we would grab it inside the foreach loop

        $last_row_in_group = $view->result[$id];

        // NOTE: "field_field_entity_reference" has extra 'field_' prefix at the begining followed by the actual machine name of the entity reference field
        print '<a href="your_url_'.$last_row_in_group->field_field_entity_reference[0]['raw']['target_id'].'">add more</a>';
  ?>
</div>

```

*PS. the link should be generated with l() function, I placed \< a \> tag in the code as a quick example.*

# Answer
> 0 votes
If anyone is interested, I just had to do this same thing - but for Drupal 8. Here's a twig version of the 'if last row' solution above, placed in the while loop of the same file name as in the example above:

```
{% if loop.last %}
    {%
    set row_classes = [
      default_row_class ? 'views-row-last',
    ]
   <!-- or whatever you need to do to the last row -->
    %}
%}

```

---
Tags: 7, views
---


# Question
Title: how to get views field names/values for hook_views_pre_render?
I'm trying to figure out how to modify a view's results with `hook_views_pre_render`.
How do I get the available values to work with?
I've turned on Devel and Kint, but I don't see any array on the page that includes views stuff.

I've tried blindly finding fields using machine names, but it just breaks the page. I'm sure I'm doing the right thing, I have one field `field_byline` that I'm able to get just fine with a simple `set()` to see if I'm able to do anything.

Here's what I've got:

```
function webinar_rearrange_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'viewname' && $view->current_display == 'block_1') {
    foreach ($view->result as $key => $value) {
      $value->_entity->set('title', 'test title'); // worked
      $value->_entity->set('body', 'test body'); // worked
      $value->_entity->set('field_byline', 'test byline');
      $value->_entity->set('field_view_node', 'http://test.com'); // DOESN'T WORK - maybe it's an array? How do I do those?
    }
  }
}

```

# Answer
> How do I get the available values to work with?

To get values from result you can do something like: `$value->_entity->title->getValue()[0]['value'];`
Here is example to get body and title you can do the same with other fields.

```
/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'viewname' && $view->current_display == 'page_1') {
    foreach ($view->result as $key => $value) {
      //- Get title value
      $title_value =  $value->_entity->title->getValue()[0]['value'];
      //- Get body value
      $body_value =  $value->_entity->body->getValue()[0]['value'];
     //- Get Other field values ...
    }
  }
}

```
> 2 votes

---
Tags: views, 8, hooks
---


# Question
Title: How do I set a Boolean field with "yes" and "no" values?
I have a content type, I'm trying to add a field that's a boolean. I want the options to be yes or no. This is something I thought would be relatively simple however, I keep getting an error message. I've attached 2 screenshots. 1 is the configuration for my boolean. The other is the error message my site gets. Can someone help me. What am I doing wrong?

# Answer
> 0 votes
The Boolean field accept only `0` and `1` as value.
if you want to add allowed values by PHP Code should be:

```
0|No
1|Yes

```

I create a Boolean field on Content type and i set the `On value` to `Yes` and
`off Value` to `No`.
As you see In the below screenshot the value of input is `0` for `NO` and `1` for `Yes`.

---
Tags: nodes
---


# Question
Title: Is it possible to unset private_tempstore values?
I have a block that creates a private\_tempstore value (which I understand works exactly like PHP sessions).

How do I unset that value.

This is the code I am using for the block.

```
class SsoSessionBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build(){
        $value = 'dav';
        $session = \Drupal::service('user.private_tempstore')->get('achva_sso');
        $session->set('name', $value);

        return [
            '#type' => 'markup',
            '#markup' => $this->t('The output of super SsoSessionBlock block.'),
        ];
    }
}

```

I saw this method, but I am not sure how I am supposed to use it.

I tried the following code, but I get an error.

```
namespace Drupal\achva_sso\Controller;

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

class SsoController extends ControllerBase{
    public function ssoLogout(){

        $session = \Drupal::service('user.private_tempstore')->get('achva_sso');
        PrivateTempStore::delete('name');

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

    }
}

```

How do I unset a value I previously set?

# Answer
> I have a block that creates a private\_tempstore value (which I understand works exactly like PHP sessions).

No, both are for different use cases.

Private tempstore is used mainly for larger quantities of data. To store a single value it would be too much overhead. Instead use the session object of the current request:

```
$request = \Drupal::request();
// in a class inject RequestStack and $request = $this->requestStack->getCurrentRequest();
// or get the request as controller parameter, see link below
$session = $request->getSession();

// set a value
$session->set('my_value', $my_value);

// unset a value
$session->remove('my_value');

```

This is the official Drupal 8 way to store session data and since you've tagged the question with `sessions` this probably what you are looking for, see Access session data through the Request object
> 5 votes

# Answer
`delete()` is the method to delete a value in the store.

```
$session = \Drupal::service('user.private_tempstore')->get('achva_sso');
$session->delete('name');

```

`'name'` is the value passed as first argument in any call to `set()`.

You don't use `PrivateTempStore::delete()` since it's not a static method and it would throw errors or warnings, if called as static method.

As side note, user.private\_tempstore is a deprecated service. Instead, the tempstore.private service should be used. (See User module's user.private\_tempstore and user.shared\_tempstore services moved to core for more details.) In the latest Drupal 8.5.x version, the service is marked as deprecated directly in the user.services.yml file.

```
class: Drupal\user\PrivateTempStoreFactory
arguments:
  - '@keyvalue.expirable'
  - '@lock'
  - '@current_user'
  - '@request_stack'
  - '%tempstore.expire%'
deprecated: 'The "%service_id%" service is deprecated. You should use the ''tempstore.private'' service instead. See https://www.drupal.org/node/2935639.'
tags:
  - { name: backend_overridable }

```

It should also be better to use dependency injection: A class extending `BlockBase`, or `ControllerBase`, can implement the `create()` method to load new dependencies.
> 3 votes

---
Tags: 8, sessions
---


# Question
Title: Recaptcha dissappears after form submission
I am using webform with ajax and for spam protection I am using recaptcha module. Everything works fine when form is submitted once with all fields filled and recaptcha is also appearing on it. But when some validation error comes or recaptcha is left i.e. not filled the form appears again with error but their is no recaptcha field. Kindle tell me how to solve this as I am new to Drupal world. I am sure this isthis issue has been discussed before but I am unable to understand their solutions. Kindly give me a solution to solve this. I am using drupal 8.5.4.

# Answer
check the "Persistence" option in the CAPTCHA settings? You must choose "Always add a challenge".
> 0 votes

---
Tags: captcha
---


title: View Members Tab of a Group

text:
# Question
Title: View Members Tab of a Group
So I've had my first taste of Drupal Group, and it looks really promising so far. Now I may be missing something totally, but if my user (testuser1) is a member of a group with 2 other members, why can I not see the **Member** tab as *testuser1*?

However, as a site admin I can see the Members Tab:

I already have enabled the Group Type permission: *View individual group members* for both members and outsiders. So my question is, how do I allow members and outsiders to view the members of that group?

# Answer
> 0 votes
Ok, so I have now realised that the *Members* tab I displayed above for the site admin, was actually just a tab to show the User-Group relationship, which in way no way links to the user's profile.

So I've applied a solution (which I'm happy with) using Views module. For now I'll just link to my pastebin for this and explain the solution a little later.

---
Tags: 8, group
---


# Question
Title: Add Mailchimp interests fields into webform_mailchimp signup field
Currently I am using:

* mailchimp 7.x-4.9
* webform\_mailchimp 7.x-4.x-dev
* webform 7.x-4.18

From this issue I applied patch #2 to webform\_mailchimp 7.x-4.x-dev module, and I can see the file `webform_mailchimp.module` has been changed. But it looks like on the Webform configuration page I don't see any changes?

In webform\_mailchimp field configuration I have (see attachment):

**Mailchimp merge fields:**

```
NAME|field_naam
EMAIL|field_email

```

**Mailchimp interests fields:**

```
Gender|field_sexe

```

In webform component radio buttons `field_sexe` I have (see attachment):

```
Man
Woman

```

What I am doing wrong here?

I need to send the `interests fields` values like `Gender` and `Country` from my `webform_mailchimp` form to the Mailchimp list Groups so I am able to segment my Mailchimp list.

# Answer
I fixed it by going to the `webform component radio buttons field_sexe`. Inside this field configuration there is an option `Load a pre-built option list`. Select here Mailchimp's interests field: `Gender`.
> 0 votes

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


# Question
Title: How to sort content in Views by menu weight
I have a D7 Views view which delivers a number of nodes. I would like them to be sorted based on the weight that their relevant menu items have.

I would like to avoid the fine module DraggableViews or any additional weight field for that matter.

How could this be accomplished?

Relevant pages: https://drupal.org/node/313140

# Answer
> 5 votes
1: Referencing a user contributed module: Views menu sort which at #48 has a D7 version. I have not tested this but others report success.

2: Another method you could use is to use a PHP field in your view like in this article on tappetyclick.com. (I have used this method before)

3: Or you can use the module menu node views which requires menu node.

# Answer
> 4 votes
A quick and simple solution without the need of extra modules might be to:

1. alter a view result before rendering using uasort(),
2. use sort callback `YOURMODULE_sort_view_on_menu_link_weight()` and
3. use helper function `YOURMODULE_build_menu_by_path()` to create an array with menu link data keyed on node paths.

NB: This snippet:

1. assumes the menu the nodes are referenced from is the main menu (one can change the menu key `main-menu`),
2. does not take menu depth or Views pagination into account and
3. overwrites any sorting done by Views.

---

```
/**
 * Implements hook_views_pre_render().
 *
 * - Sort view result based on menu link weights.
 */
function YOURMODULE_views_pre_render(&$view) {
  if ($view->name == 'YOURVIEWID') {
    uasort($view->result, 'YOURMODULE_sort_view_on_menu_link_weight');
  }
}

/**
 * uasort() callback to sort a view result on menu links weights.
 */
function YOURMODULE_sort_view_on_menu_link_weight($a, $b) {
  $menu_by_path = &drupal_static(__FILE__, array());

  // Get $menu_by_path once.
  if (empty($menu_by_path)) {
    YOURMODULE_build_menu_by_path(menu_tree_all_data('main-menu'), $menu_by_path);
  }

  // Get menu item weights by node ID.
  $weight_a = isset($menu_by_path['node/' . $a->nid]) ? (int) $menu_by_path['node/' . $a->nid]['weight'] : 0;
  $weight_b = isset($menu_by_path['node/' . $b->nid]) ? (int) $menu_by_path['node/' . $b->nid]['weight'] : 0;

  // Return sort value.
  return $weight_a == $weight_b ? 0 : ($weight_a < $weight_b ? -1 : 1);
}

/**
 * Helper function to get an array with menu link data, keyed by menu link path.
 */
function YOURMODULE_build_menu_by_path($menu, &$menu_by_path, $depth = 0) {
  // Iterate through menu items.
  foreach ($menu as $key => $menu_item) {
    // If menu item links to a node.
    if (strpos($menu_item['link']['link_path'], 'node/') === 0) {
      // Create $menu_by_path entry, store depth and weight.
      $menu_by_path[$menu_item['link']['link_path']] = array(
        'depth' => $depth,
        'weight' => $menu_item['link']['weight'],
      );
    }

    // If menu item has children.
    if (!empty($menu_item['below'])) {
      // Call this function on the menu item's submenu.
      YOURMODULE_build_menu_by_path($menu_item['below'], $menu_by_path, $depth+1);
    }
  }
}

```

# Answer
> 1 votes
The module Views Menu Node Children Filter can also sort by menu weight since version 7.x-1.0-rc3.

# Answer
> 0 votes
One possibility is to use the Views PHP module.

A PHP function is required in order to retrieve the relevant menu item weight:

```
function get_menu_weight($nodeID) {
  $weight = 0;
  $query = "SELECT weight FROM {menu_links} WHERE link_path = :path AND hidden < 1";
  $args = array(':path' => 'node/' . $nodeID);
  $result = db_query($query, $args);
  if ($result->rowCount() > 0)
    $weight = $result->fetch()->weight;
  return $weight;
}

```

This function can reside in a `template.php` file or a custom module.

Then in the view under concern:

* Add a *Content: Nid* field to the list of fields and exclude it from display
* Add a *Global: PHP* field to the list of fields and exclude it from display
* In the *Value code* set `return get_menu_weight($row->nid);` (*without* php tags)
* In the *Output code* set `<?php print $value; ?>` (*with* PHP tags)
* Add a *Global: PHP* field to the *sort* fields of the view and specify:

```
if ($row1->php < $row2->php) return -1;
else return 1;

```

Source: http://tappetyclick.com/blog/2013/01/07/how-order-drupal-view-node-menu-weight#.UyG1St8hGb4

---
Tags: 7, views
---


# Question
Title: How to discover events for event dispatcher
I want to write an implementation of EventSubscriberInterface for an event in commerce, there is a handy example, but

1. How do I find out what events are available (as a whole for my site) and/or
2. How do I know what events are getting hit on a request?

This question is not specific to the commerce module, it is just the context of my current problem.

# Answer
You can simply use the Drupal console.

List all the events that could be debugged:

`drupal debug:event`

`drupal dev`

Show the information for the specific event, for example "commerce\_order.commerce\_order.update":

`drupal dev commerce_order.commerce_order.update`
> 2 votes

# Answer
I was stumped by this for a while, so I was pleased to find an answer in the Devel module

Install the Devel module and look at the toolbar menu item:

"Events info" which links to /devel/events

So for the commerce events I can see the following:

```
Callable    Priority
commerce_order.place.post_transition
Drupal\commerce_order\EventSubscriber\OrderReceiptSubscriber::sendOrderReceipt  0

commerce_order.place.pre_transition
Drupal\commerce_cart\EventSubscriber\OrderEventSubscriber::finalizeCart 0
Drupal\commerce_order\EventSubscriber\TimestampEventSubscriber::onPlaceTransition   1
Drupal\commerce_order\EventSubscriber\OrderNumberSubscriber::setOrderNumber 2

```
> 2 votes

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


# Question
Title: What's the correct way to pass variables to the JavaScript of a custom CKEditor plugin?
I saw that we can pass values to our JavaScript using drupalSettings. However, this is for Drupal custom module JavaScript files. Since a CKEditor plugin file is already attached/loaded in a different way, I am wondering what's the correct way to pass variables to it.

The following is the code that I made, according to the example, but I have the feeling that plugin.js is loaded two times:

* one time in `inline_comment_preprocess_html()`
* and one more time with inline\_comment/src/Plugin/CKEditorPlugin/InlineComment.php

**What's the correct way to pass variables to plugin.js?**

inline\_comment.info.yml

```
name: CKEditor Inline Comment
type: module
description: "Adds the Inline Comment plugin to CKEditor."
package: CKEditor

dependencies:
  - ckeditor
  - core/jquery
  - core/drupalSettings

version: '8.x-1.0'
core: '8.x'
project: 'inline_comment'

```

*inline\_comment.module*

```
function inline_comment_preprocess_html(&$variables) {
  $lotus_height = '300px';
  $variables['#attached']['library'][] = 'js/plugins/inline_comment/plugin.js'; // I think I shouldn't try to load plugin.js two times
  $variables['#attached']['drupalSettings']['lotus']['lotusJS']['lotus_height'] = $lotus_height;

}

```

*js/plugins/inline\_comment/plugin.js*

```
CKEDITOR.plugins.add('inline_comment', {
    //...
});

(function ($, Drupal, drupalSettings) {
    Drupal.behaviors.LotusBehavior = {
        attach: function (context, settings) {
            var lotusHeight = drupalSettings.lotus.lotusJS.lotus_height;
            console.log('lotusHeight' + lotusHeight);
        }
    };
})(jQuery, Drupal, drupalSettings);

```

I noticed if I remove the line with `$variables['#attached']['library'][]` and I `dump($variables)` there is no `drupalSettings` variable in `#attached` array.

# Answer
> 1 votes
You can pass options via `getConfig` option of the class that creates the plugin. See how the module "Color Button" does it:

https://cgit.drupalcode.org/colorbutton/tree/src/Plugin/CKEditorPlugin/ColorButton.php?h=8.x-1.x

This is passed along to the defined plugin when it is loaded up (the one defined in `getFile`.)

See: https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginBase.php/class/CKEditorPluginBase/8.6.x

and:

https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginInterface.php/function/CKEditorPluginInterface%3A%3AgetConfig/8.6.x

The variable names passed or modified in `getConfig` need to be the same names as the ones in the plugin to be overwritten.

---
Tags: 8, javascript, wysiwyg
---


# Question
Title: Add property to ProductVariationType via hook_entity_type_build()
Hy guys,

I'm trying to implement a simple stock management in my e-commerce. The ProductVariation will have a `stock_quantity` field used to track product availability.

I would like that `stock_quantity` field is shown only if user checks an `enable_stock_management` checkbox on ProductVariation bundle edit page. I.e. */admin/commerce/config/product-variation-types/default/edit*

In other words I would like to mimic **Submission form settings**, **Menu settings**, **Display settings** functionalities of Node's bundles.

By Google-ing a bit I think that `hook_entity_type_build()` is the hook to use. But, once I'm in the hook what I'm supposed to do in order to add the property I need and display it in the edit form?

```
 /**
  * Implements hook_entity_type_build().
  */
 function commerce_warehouse_entity_type_build(array &$entity_types) {
     /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
     $entity_types['commerce_product_variation_type']-> # ... And now?;
 }

```

# Answer
Ends up that `hook_entity_type_build()` is not the right way to implement what I want. I found a solution usign `ThirdPartySettingsInterface`, which every `ConfigEntityBase` implements.

First I've altered `ProductVariationType` form via `hook_form_alter()` in order to add a checkbox to the form and register a new `#enity_builder`.

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MY_MODULE_form_BASE_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var ProductVariationTypeInterface $entity */
  $entity = $form_state->getFormObject()->getEntity();

  $form['warehouse_management'] = [
    '#type' => 'checkbox',
    '#title' => t('Enable warehouse management'),
    '#default_value' => $entity->getThirdPartySetting('commerce_warehouse', 'warehouse_management'),
  ];

  $form['#entity_builders'][] = 'MY_MODULE_entity_ENTITY_ID_builder';
}

```

Then I've defined my custom entity builder function where I register my third party setting. Pretty simple! This article helps me out a lot.

```
/**
 * Entity builder for commerce_product_variation_type entity.
 */
function MY_MODULE_entity_ENTITY_ID_builder($entity_type, ProductVariationTypeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->setThirdPartySetting('commerce_warehouse', 'warehouse_management', $form_state->getValue('warehouse_management'));
}

```
> 1 votes

---
Tags: 8, entities, commerce, hooks
---


# Question
Title: How to customize the subject of a Commerce order confirmation e-mail?
Here you can learn how to customize the content of the order confirmation mail, but what about customize the subject of the mail?

# Answer
> 3 votes
In a custom module you can try something like:

```
/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(array &$message) {
  // Order receipt.
  if ($message['id'] === 'commerce_order_receipt') {
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $message['params']['order'];

    // Change the email subject.
    // @todo Remove this if/when it becomes configurable.
    //   https://www.drupal.org/project/commerce/issues/2924159
    $message['subject'] = t('Some other email subject #@number', [
      '@number' => $order->getOrderNumber(),
    ]);
  }
}

```

---
Tags: 8, commerce
---


# Question
Title: Show content with a date after the current one on a view
I'm creating a calendar of events with Drupal 7 using views. At the moment the elements are shown in order of the date of each one (I have a date field where I put the date of the event). Now I need that when the date is passed, it does not appear anymore.

For example, if I have an event that was held yesterday, today it would not have to appear in the view.

Thank you!

# Answer
Just add a filter based on the date field and the criteria should be "**greater than or equal to**", then select "**Enter a relative date**" in the drop down field and enter the word "**now**"

Here is a screenshot from a site that has a Register By date field and I have a list of Upcoming Events that show based on this in a homepage block.
> 1 votes

---
Tags: 7, views, input-formats, datetime
---


# Question
Title: Change the display name of a default field in Contact Form
In Drupal 8, I LOVE that there are default fields in Contact Forms for Name, Email, Subject, and Message...but in several of our forms those labels don't make sense.

For example, one form's primary use is to request an appointment, but I would like to use the Message field to ask if they have any other questions. Saying "Message" at the top of the box doesn't make sense, and I would like to still use the field but change the label to "Questions".

Is that possible to do without making another field and hiding the default field?

# Answer
> 1 votes
AFAICT each contact category has its own form ID, which means you can change it with `hook_form_alter()` in your theme or a custom module. Here's a tutorial about how to implement it, although there are other resources you can find: Learn how to change an existing Drupal form.

If you wanted to do it without coding then creating a new field and adjusting form and display for each contact category is the way to go.

As Hudri mentioned in a comment you could use Webform for a lot more control, including saving the responses in the database. If you don't need to keep record of the correspondence than Webform is probably an overkill.

---
Tags: forms
---


# Question
Title: Views switches to another view on apply or any change
When I'm working on a block display in Views on Drupal 7, and hit the "Apply" button, I'm taken to the master (or first view), instead of staying on the block display that I'm working on.

How do I fix this behaviour and remain on the correct display when applying settings?

# Answer
I finally tracked it down to a setting in Views (where it shows all of the views) and the Settings tab. Under the Advanced Option here, I was able to turn off a "Disable Javascript on Views" setting that had somehow gotten turned on. The Ajax function was not firing and the main URL was resetting for every update of any kind. This meant jumping between views for every change of any field whatsoever.

That setting fixed everything though, so I'm posting in case anyone else has the issue and can't find a reason.
> 1 votes

---
Tags: 7, views, javascript
---


# Question
Title: Video embed field doesn't honor the autoplay settings
So I have an embedded video field inside of a paragraph and want it to autoplay. I have set the settings for the field to have it autoplay, but when the iframe is rendered the url has autoplay=0. Are there other settings I need to enable to get this to work?

>

>

# Answer
> 0 votes
Use the following code to change autoplay to 1 in your template or Javascript file. It works for me.

```
jQuery('.video-embed-field-launch-modal').attr('data-video-embed-field-modal', function(i, oldSrc) {
  var isAutoPlay = oldSrc.match(/autoplay=([^&]*)/);
  if (isAutoPlay && isAutoPlay[1] == 0) {
    return oldSrc.replace('autoplay=0', 'autoplay=1');
  }
});

```

# Answer
> 0 votes
Some extra info to add ... Google has updated their policy around auto play on websites .. To get auto play to work you need to add &mute=1 to the query string so that the sound is muted when the page loads and the video starts

See the policy here:

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Without that parameter .. Chrome won't auto play at all .. Currently auto play with sound on Firefox 63, Edge & IE 11 without the above parameter. Chrome won't auto play without the mute setting. Opera 56 doesn't appear to auto play at all.

---
Tags: 8, entities
---


# Question
Title: Insert date programatically in custom module
I am programatically saving values from an array $customer into a content type. The below code works fine and populates the content type customer\_profile except for the field date of birth. This field is of type date and date type is set as date only (not date and time). The value in $customer\['dob'\] is '19/12/1938'. How do I insert this value?

```
$node_data['type'] = 'customer_profile';
$node_data['title'] = $customer['First Name'].' '.$customer['Last Name'];
$node_data['field_customer_gender']['value'] = $customer['Gender'];
$node_data['field_date_of_birth']['value'] = $customer['dob'];
$node = Node::create($node_data);
$node->setPublished(TRUE);
$node->save();

```

# Answer
> 0 votes
I think correct format is 'yyyy-mm-dd', try to insert '1938-12-19'

# Answer
> 0 votes
I successfully converted and inserted the date by

```
   $node_data['field_date_of_birth']['value'] = Datetime\DrupalDateTime::createFromFormat('d/m/Y', $item['DOB'])->format('Y-m-d')

```

---
Tags: nodes, datetime
---


# Question
Title: Cannot insert images in body of a basic page
I am using CKEditor and WYSIWYG. After updating Drupal core to 8.5.6, I cannot upload an image using the CKEditor's 'image' button anymore saying "Image Field is required."

I have checked CKEditor's plugin settings. Image upload's enabled there.

I have not found a solution yet. Any help will be appreciated.

PS: If I add an image using html "img" tag then it shows up properly, it's only the button that is not working properly.

# Answer
> 1 votes
I found a solution. Suggested by Tech-Tonic:

https://www.drupal.org/forum/support/post-installation/2018-08-24/ckeditor-image-button-cannot-insert-images-in-body-of-a#comment-12854570

> Does your content type have other file fields on it? If so, try temporarily disabling all file/image fields for the content type in "Manage form display" and save. Then enable them again and save. Worked for me, in Drupal 8.6.3.

As mentioned above, I also had an image/file field in the content type. Under 'Manage form display', I disabled the image field and saved. I then went back to 'Manage form display', moved it back to where it originally was and saved again.

After this the error no longer appears. This worked on the production, staging and development copies of the same site.

---
Tags: 8, media, wysiwyg
---


# Question
Title: Syncing Development Site with Production Site
I recently built my first Drupal 8 site. I've updated the production site since it's been launched, and I wanted to sync it with the development site before I create another content type.

Could someone point me in the right direction?

# Answer
You simply need to sync the database and the whole complete Drupal folder. Every single file except for `.htaccess` and `settings.php` as they may be different in every environment.

---

And from now on you start to do things just the other way around.

`git init` a Git repo on your local machine. Then you do every update, every UI change, every site building task on your local machine first.

When you are done locally you do `drush cex` to export the new configuration into YAML files. I think you can do that from the UI as well.

Then you deploy (upload) these YAML files to your live site and start the configuration import, `drush cim` or UI.

Similar with updating Drupal. Wether Composer or manually, you do that on your local machine first. Then deploy the resulting `composer.lock` file or the updated files to your live site and start the database updates once again, `drush updb` or from the UI.

---

From now and then you get a database dump from your live site and import that locally. Maybe you download or `rsync` the whole `sites/default/files` folder to your local machine as well. This one and your `settings.php` are going to be ignored from Git.

That's how things are supposed to go. File changes always upstream, database dumps downstream.

---

After you've set up Git correctly you may start to use Git Flow. Which expects you to work in different Git branches, `master` and `develop`. And `feature/*` branches when developing new features locally.

Basically when you're done with a feature you merge the feature branch into the `develop` branch and push the changes to your Dev server. Once in a while you start a new `release` where the `develop` branch gets merged into the `master` branch. And the `master` branch would be the one that pushes stuff to the Live server.
> 3 votes

---
Tags: 8, deployment
---


# Question
Title: How to define template suggestions for node add and edit form by content type?
I have a content type **Project** and it has a more than 100 fields in the node form. The form fields are grouped in different section and category. I tried to use a field\_group module to group and categories in different sections, but when I add more than 20 groups field I got a problem in field arrangement and save the changes in form display. Also, i am facing difficulty to theme the form as per the design.

So, is it possible to define template suggestions for node add and edit form by content type and add an individual form element in the form template, where I can define my own HTML structure?

Eg: ***from--project.html.twig*** some things like this, and able to add individual form elements in the form template.

```
<form{{ attributes }}>
 {{ form.title }}
 {{ form.field_project_description }}
</form>

```

Thanks for any help.

# Answer
I usually use something like this for template form suggestions : (works for all forms, not only entity forms)

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function <HOOK>_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if (isset($variables['element']['#theme']) && is_array($variables['element']['#theme'])) {
    foreach ($variables['element']['#theme'] as $theme) {
      if (strpos($theme, '_edit_') !== FALSE) {
        $suggestions[] = 'form__' . str_replace('_edit_', '_', $theme);
      }
      $suggestions[] = 'form__' . $theme;
    }
  }
}

```
> 1 votes

---
Tags: 8, theming, nodes, forms, hooks
---


# Question
Title: "Your requirements could not be resolved to an installable set of packages"
Last time I used composer on my project was to update drupal core from 8.6.2 to 8.6.3 using `composer update drupal/core webflo/drupal-core-require-dev --with-dependencies` and to update the webform module from 8.x-5.0-rc24 to 8.x-5.0-rc26 using `composer require 'drupal/webform:^5.0'` and after both successful updates, my website is working perfectly but any Composer command I use is returning the same error.

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package algolia/places 1.13.0 is satisfiable by algolia/places[1.13.0] but these conflict with your requirements or minimum-stability.
  Problem 2
    - The requested package codemirror/codemirror 5.41.0 is satisfiable by codemirror/codemirror[5.41.0] but these conflict with your requirements or minimum-stability.
  Problem 3
    - The requested package jquery/inputmask 4.0.2 is satisfiable by jquery/inputmask[4.0.2] but these conflict with your requirements or minimum-stability.
  Problem 4
    - The requested package jquery/intl-tel-input 14.0.4 is satisfiable by jquery/intl-tel-input[14.0.4] but these conflict with your requirements or minimum-stability.
  Problem 5
    - The requested package jquery/timepicker 1.11.14 is satisfiable by jquery/timepicker[1.11.14] but these conflict with your requirements or minimum-stability.

```

The Composer commands I tried so far are:

* `composer update`
* `composer update drupal/core webflo/drupal-core-require-dev --with-dependencies`
* `composer require "webflo/drupal-finder ~1.0.0"`

As I remember, the following packages are used by the Webform module and this module is updated to the latest stable release version.

* algolia/places
* codemirror/codemirror
* jquery/inputmask
* jquery/intl-tel-input
* jquery/timepicker

I have tried both the solutions mentioned in Conflict between package requirements when updating to Drupal 8.4 but with no success at all.

What is going on?

**UPDATE #1:**

Here is my composer.json file:

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": {
        "0": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        "algolia/places": "1.10.0",
        "ckeditor/autogrow": "4.10.0",
        "ckeditor/codemirror": "v1.17.7",
        "ckeditor/fakeobjects": "4.10.0",
        "ckeditor/image": "4.10.0",
        "ckeditor/link": "4.10.0",
        "codemirror/codemirror": "5.40.0",
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6.5",
        "drupal-composer/drupal-scaffold": "^2.5",
        "drupal/admin_toolbar": "^1.24",
        "drupal/ajax_links_api": "^1.0",
        "drupal/backup_migrate": "^4.0",
        "drupal/barcodes": "^1.8",
        "drupal/better_exposed_filters": "^3.0",
        "drupal/bootstrap": "^3.13",
        "drupal/bootstrap_layouts": "^5.1",
        "drupal/bootstrap_library": "^1.11",
        "drupal/business_rules": "^1.0",
        "drupal/captcha": "^1.0",
        "drupal/color_field": "^2.0",
        "drupal/conditional_fields": "^1.0",
        "drupal/config_split": "^1.3",
        "drupal/console": "^1.0.2",
        "drupal/core": "^8.6.0",
        "drupal/devel": "^1.2",
        "drupal/ds": "^3.1",
        "drupal/entity_reference_views_select": "^1.3",
        "drupal/eva": "^1.3",
        "drupal/field_group": "^3.0",
        "drupal/field_permissions": "^1.0",
        "drupal/fontawesome": "^2.9",
        "drupal/footable": "1.x-dev",
        "drupal/group": "^1.0",
        "drupal/module_filter": "^3.1",
        "drupal/pathauto": "^1.2",
        "drupal/readonlymode": "^1.0",
        "drupal/reroute_email": "^1.0",
        "drupal/search_api": "^1.10",
        "drupal/simplify": "^1.0",
        "drupal/sms": "^1.1",
        "drupal/sms_simplegateway": "^1.1",
        "drupal/telephone_validation": "^2.1",
        "drupal/token": "^1.5",
        "drupal/toolbar_menu": "^2.1",
        "drupal/toolbar_menu_clean": "^1.0",
        "drupal/views_autorefresh_d8": "^1.1",
        "drupal/views_bootstrap": "^3.0",
        "drupal/views_conditional": "^1.0",
        "drupal/webform": "^5.0",
        "drush/drush": "^9.0.0",
        "jquery/image-picker": "0.3.0",
        "jquery/inputmask": "4.0.0",
        "jquery/intl-tel-input": "13.0.0",
        "jquery/rateit": "1.1.1",
        "jquery/select2": "4.0.5",
        "jquery/textcounter": "0.8.0",
        "jquery/timepicker": "1.11.13",
        "progress-tracker/progress-tracker": "1.4.0",
        "signature_pad/signature_pad": "2.3.0",
        "vlucas/phpdotenv": "^2.4",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3",
        "wikimedia/composer-merge-plugin": "^1.4"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "^8.6.0"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": [
            "load.environment.php"
        ]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "web/modules/contrib/webform/composer.libraries.json"
            ]
        },
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "installer-paths": {
            "web/core": [
                "type:drupal-core"
            ],
            "web/libraries/{$name}": [
                "type:drupal-library"
            ],
            "web/modules/contrib/{$name}": [
                "type:drupal-module"
            ],
            "web/profiles/contrib/{$name}": [
                "type:drupal-profile"
            ],
            "web/themes/contrib/{$name}": [
                "type:drupal-theme"
            ],
            "drush/Commands/{$name}": [
                "type:drupal-drush"
            ]
        },
        "drupal-scaffold": {
            "initial": {
                ".editorconfig": "../.editorconfig",
                ".gitattributes": "../.gitattributes"
            }
        }
    }
}

```

# Answer
Webforms should handle these packages on its own, so you don't have to require them.

See: cgit.drupalcode.org/webform/tree/composer.libraries.json

In general if the package you required has its own `composer.json` require section you don't have to require them yourself.
> 3 votes

---
Tags: 8, webforms, composer
---


# Question
Title: How to retrieve ConfigEntity instance from config factory?
I have defined a config entity in my module (schema and class that extends `ConfigEntityBase`) - `MyConfigEntity`.

When I use config factory to get config, Drupal returns instance of `Config` or `ImmutableConfig`. How can I retrieve instance of `MyConfigEntity` instead?

```
$config = \Drupal::config('my_module.config.something');
// Now $config is instance of ImmutableConfig.

```

# Answer
\Drupal::config()

> Retrieves a configuration object.
>
> This is the main entry point to the configuration API.

The configuration API is a different system than the entity API.

```
$entity = \Drupal::entityTypeManager()
  ->getStorage('my_config_entity')
  ->load($id);

```

Configuration entity types should be used to store configurable content like content types or other site builder-esque things that you want to deploy from environment to environment that is not managed content (Something a content author would write).

If you're looking for a complex configuration object, then you should define that in `config/mymodule.settings.yml` and use the configuration API like in your question.
> 9 votes

# Answer
Check this out configFactory.

You just need to do:

`\Drupal::configFactory()->getEditable('my_module.config.something');`
> 6 votes

---
Tags: 8, entities
---


title: Block certain IP addresses

text:
# Question
Title: Block certain IP addresses
How to block certain IP addresses if we receive too many GET requests from particular IP addresses for a Drupal 7 website?

# Answer
> 1 votes
Drupal 7 has IP address blocking feature by default.

1. Login to admin
2. Navigate to configuration page
3. Click on "IP address blocking" which available in under People panel
4. Add IP address which you wanted to block.

OR

Navigate to below page http://\[yourwebsitename.com\]/admin/config/people/ip-blocking

---
Tags: 7
---


# Question
Title: Composer update : Package "drupal/module_name" listed for update is not installed. Ignoring
After hours of struggling to update Drupal with Composer (see my solution here), I have now some difficulties to update some modules. I was able to update with `composer update drupal/bootstrap:3.11 --with-dependencies`, but I could not update a module with `composer update drupal/pathauto:1.1 --with-dependencies`, which returns the following error.

> Package "drupal/pathauto:1.1" listed for update is not installed.
> Ignoring. Nothing to install or update.

The content of the composer.json file is the following.

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/views_slideshow": "^4.6",
        "drupal/metatag": "^1.4",
        "drush/drush": "dev-master",
        "drupal/core": "~8.5",
        "drupal/pathauto": "1.1",
        "drupal/bootstrap": "3.11",
        "drupal/token": "1.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": [
          "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
        ],
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

```

I tried with `composer update drupal/token`, but it gives the following error.

> Nothing to install or update

`composer install drupal/token` gives the following error.

> Invalid argument drupal/token.
> Use "composer require drupal/token" instead to add packages to your composer.json.

Instead, `composer require drupal/token` gives this error

> Using version ^1.1 for drupal/token
> ./composer.json has been updated Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Nothing to install or update

I checked the composer.lock file and its content is the following.

```
    "name": "drupal/token",
    "version": "1.1.0",
    "source": {
        "type": "git",
        "url": "https://git.drupal.org/project/token",
        "reference": "8.x-1.1"
    },

```

So, it seems thats it is correct, but the module page still shows it as requiring to be updated.

How can I solve this and install these modules?

# Answer
I found what was the issue in my case. I post my solution. Even if it is specific to my issue, maybe it could help other users.

I didn’t install these Drupal 8 modules. The developer who installed them used Drush (he should have used `Composer`). So I had the same modules installed twice, in `/module` and in `modules/contrib` I’ve deleted modules previously installed with drush in `/module` and run `composer update`. That fixed the problem.
> 1 votes

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


# Question
Title: How to create a clickable area on the whole block view?
I created a block view that shows *Article* nodes. The display format is *Grid bootstrap*.

How can I create a clickable area on the whole block view?

I want the whole block to be clickable and redirect users to /node/nid.

>

# Answer
Use CSS and custom template structure...

Markup:

```
<div class="views-row">
    // Your various markup.
    {{ content }}
    // Link contains no text and is absolute positioned to cover the entire markup area.
    <a class="link" href="{{ link }}" title="Link to {{ print node title here }}"></a>
    // The span can be absolutely positioned as well so it is on top of the link.
    <span class="flag">This is a flag</span>
</div>

```

CSS:

```
.views-row {
    position: relative;
}

a.link {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
}

span.flag {
    position: relative;
    z-index: 200;
}

```

With this approach, you will avoid having a link that contains a lot of text and markup that makes no sense to browsers and screen readers.
> 1 votes

# Answer
I wouldn't use Javascript to do this. To do this you would have to provide a block twig override file, and wrap the entire output with an `<a href...` tag.

Note that if you do that, the other links won't work, like Flag, since you can't have anchors within anchors.

Here is an example from a project last year:

```
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}{{ title_suffix }}

    <a href="{{ path('entity.node.canonical', {'node': NODE_ID_VAR}) }}">

    {% if block_content.field_sidebar_image is not empty %}
      {{ content.field_sidebar_image }}
    {% endif %}

    <div class="c-sidebar-promo__content">
      <div class="c-sidebar-promo__header">
        {% if block_content.field_title_image is not empty %}
          {{ content.field_title_image }}
        {% endif %}

        <h4 class="c-sidebar-promo__title">{{ label }}</h4>
      </div>
      <div class="c-sidebar-promo__description">
        <p>{{ content.field_sidebar_description }}</p>
      </div>
    </div>

    </a>

  {{ content|without('field_sidebar_image', 'field_sidebar_description', 'field_sidebar_link', 'field_title_image') }}
</div>

```

This makes the entire block output clickable to the provided link destination.

Edit: Updated the example with how to generate a node link with Twig.
> 0 votes

# Answer
For a view with a fields show format :

* add the content id field
* override the templates for view fields in your theme, in my case views-view-fields--seminary--block-2.html.twig

\< a href="{{ path('entity.node.canonical', {'node': fields.nid.content|striptags|trim}) }}"\> //Some fields
> 0 votes

---
Tags: 8, views, blocks
---


# Question
Title: Better understanding of Drupal behaviors
I read about Drupal behaviors today, and I tried writing the following code.

```
(function ($) {

  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      $('#mymodule_id', context).change(function () {
        alert('Handler for .change() called.');
      });
    }
  };

}(jQuery));

```
* Is `Drupal.behaviors.mymodule` the namespace?
* What are the context and settings parameters passed to the Drupal behavior?
* Is this the equivalent of `document.ready()`?
* Can I attach any number of functions?
* Can I define JavaScript functions which will be called somewhere?

# Answer
In short, the advantage of Behaviors over `document.ready()` is that they are automatically re-applied to any content loaded through AJAX. `mymodule` is your namespace, which needs to be unique. `context` is the part of the page for which this applies, for example a part of a form that has been updated with AJAX. You can attach multiple behaviors, but I think you need to use a unique name (mymodule) for each of those.

Have a look at the following resources for more information:
> 60 votes

# Answer
In easy words, `Drupal.behaviors` is a better way to implement `jQuery.ready`

Unlike `jQuery.ready` which only runs once when the DOM is ready, `Drupal.behaviors` can be ran multiple times during page execution.

For example, in views infinite scroll, more elements will be loaded when user clicks load more button, hence , DOM will change after initial load.

What if we want to add classes to the newly added elements? Here Drupal Behaviors come handy.

> The behaviors will be executed on every request including AJAX requests.

Drupal will call attached behaviors when the DOM is loaded and also when it is changed by Ajax, passing in two arguments

**context** and **settings**

The first time Drupal.attachBehaviors() is called, the **context** variable contains the document object representing the DOM, but for the rest of the calls context will hold the affected piece of HTML.

**settings** contains information passed on to JavaScript via PHP, it is similar to accessing it via Drupal.settings.

Furthermore, modules may call Drupal.attachBehaviors() as well.
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: Leaving first-level tab selected when clicking on a subtab
I have a menu like the following defined in `mymodule.links.menu.yml`:

```
mymodule.page_memos:
  title: 'List of memos'
  description: 'View list of memos'
  route_name: view.document_list.page_1
  route_parameters: { doctype: 'memo'  }
  menu_name: main
  weight: 100

mymodule.page_letters:
  title: 'List of letters'
  description: 'View list of letters'
  route_name: view.document_list.page_1
  route_parameters: { doctype: 'letter'  }
  menu_name: main
  weight: 200

mymodule.page_notes:
  title: 'List of notes'
  description: 'View list of notes'
  route_name: view.document_list.page_1
  route_parameters: { doctype: 'note'  }
  menu_name: main
  weight: 300

```

and then a list of tasks defined in `mymodule.links.task.yml`:

```
mymodule.document_list:
  title: 'List of documents'
  description: "View full list of documents"
  route_name: view.document_list.page_1
  base_route: view.document_list.page_1
  weight: 10

mymodule.create_doc_by_type:
  title: 'New document'
  description: 'Insert new document'
  route_name: mymodule.create_doc_by_type
  base_route: view.document_list.page_1
  weight: 20

```

Everything work as expected, with three tabs in the main menu and two tabs in the task (they will soon become more). There is only a small visual glitch: when I click on tabs in the main menu, the last one clicked is correctly marked as active; when I click on tabs on the task menu, only the first one is ever marked as active. I am sure this has to be something really minor, but I really don't know how to search for a solution.

# Answer
I came back to study this problem further. If I am not mistaken, the active trail is not set from the local task to its parent menu link, even if the first local task is correctly set to the corresponding menu voice. I looked at a few modules and custom solution, and in the end I simply changed a bit my URLs and installed the module menu\_trail\_by\_path, and I got the desired behaviour.
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: Why doesn't "composer update drupal/drupal" work?
I installed a Drupal 8.2.0 site with `composer create-project drupal/drupal testsite`.

Now I would like to upgrade it to Drupal 8.2.1. However, running `composer update drupal/drupal` doesn't work. It prints the following error:

> Package "drupal/drupal" listed for update is not installed. Ignoring.

How do I do this? The support is clearly documented in example.gitignore.

```
# Ignore core when managing all of a project's dependencies with Composer
# including Drupal core.
# core

```

So there has to be some way to do this with composer, but how?

# Answer
Think I solved it. I figured that I would need a different root composer.json file that pulled in the drupal package instead of replacing it, but I didn't know how to do so.

Fortunately, someone has already done this and repackaged Drupal in a composer-friendly way: https://github.com/drupal-composer/drupal-project (No stable version yet, apparently.)

By using `composer create-project drupal-composer/drupal-project:8.x-dev --stability dev drupal-dir` I was able to get an install that can be updated with composer.
> 4 votes

# Answer
Edit: this is probably not helpful b/c I just re-read your statement and you didn't have the same case as mine where I was coming from an old Drupal 8 install but I will leave this up in case anyone else has this issue and try to see if I can find the specific issue you are having. Sorry.

I had this issue when dealing with a recent update and this was my issue but YMMV so if it doesn't work just let me know.

This may be a problem of that you composer file is set to the old repository listing on composer.org. Recently, Drupal setup their own composer endpoints, one for Drupal 7 and another for Drupal 8. You can read more about that change here: https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-packages-through-drupalorg

This is the command that needs to be ran to swap the repository over the Drupal.org's.

```
$ composer config repositories.0
$ composer https://packages.drupal.org/8

```
> 5 votes

# Answer
The command `composer create-project` clones the requested package, which in this case is https://git.drupal.org/project/drupal.git. At the end of the project creation process, you should be prompted whether you want to remove the existing VCS history. If you answered `n`, you will have a way to update from the upstream drupal repository. Navigate into testsite, and use git to fetch and check out the version of Drupal you want. Then run `composer install` to get the dependencies identified in composer.json and composer.lock of the updated version of Drupal.
> 3 votes

# Answer
On the command line, we had to require drupal core (replace with your version):

```
composer require drupal/core:8.6.3 --update-with-dependencies

```

In the composer.json file under replace we had to remove "drupal/core": "^8.6" so replace looks like:

```
"replace": {

},

```

in our composer.json file now. We then ran:

```
composer update

```

and drupal updated to the latest version.
> 3 votes

---
Tags: 8, composer
---


title: Trigger cron internally using PHP

text:
# Question
Title: Trigger cron internally using PHP
The server my site is on cannot use curl, wget or lynx to call the external cron address (eg http://example.com/cron/cron\_key)

Is it possible to use php to 'run' the cron from inside the server.

I'm was thinking something like php -f /home/docroot/core/Drupal/Cron.php with a query string for the cron key, but I notice there isn't a query string as in Drupal 7.

I cannot use Drush since it's not installed on the prod servers.

I also cannot use a third party external cron service.

Any ideas?

# Answer
> 1 votes
a way to do that :

create customcron.php in the drupal root with the content :

```
<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// Load cron service and run cron.
\Drupal::service('cron')->run();

$kernel->terminate($request, $response);

```

then run :

```
php customcron.php

```

i would not let the file customcron.php in the root because anybody could then execute it from the browser.

A simple way to avoid that is moving the file customcron.php to drupal root only for the time you execute it or maybe have an unguessable file name instead of customcron.php

# Answer
> -1 votes
In general, using Drush to run cron via `drush cron` or Drupal Console cron:execute `drupal cron:execute` would be a first suggestion.

If you are interested in command line, it's likely that Drush and Drupal Console will become valuable tools for you, so to not have them because they aren't on prod is a bummer.

There is also the concept of site aliases in drush that can work on remote servers.

---
Tags: 8, cron
---


# Question
Title: Adding an address to a node's address field programmatically
I am presenting a form to receive an address. I want to take the data and add it to a node that has an address field (from the address field module).

Can someone point me in the right direction on how to do that?

# Answer
> 1 votes
I provided a code example using entity\_metadata\_wrapper() in this issue. As soon as I finish cleaning up the issue queue, I'll make a regular documentation page out of that. You can follow this issue to see when the documentation page gets published.

# Answer
> 1 votes
Here's a PHP snippet that can be used to set an address field on a node.

# PHP

```
$lang = $node->language;
$node->field_address[$lang][0] = array(
  "country" => "US",
  "thoroughfare" => "123 Fake Street",
  "premise" => "",
  "locality" => "Beverly Hills",
  "administrative_area" => "CA",
  "postal_code" => "90210"
);

```

And for reference, here's the JSON that can be used with the Services module.

# JSON via Services Module

```
{
  "nid":123,
  "field_address":{"und":[{
    "country":"US",
    "thoroughfare":"123 Fake Street",
    "premise":"",
    "locality":"Beverly Hills",
    "administrative_area":"CA",
    "postal_code":"90210"
  }]}
}

```

This example works for the US only, see addressfield\_get\_address\_format() for the components that are required for your desired country(ies).

# Answer
> 1 votes
In drupal 8 the data insert will work only if 'country' is changed to 'country\_code' and 'thoroughfare' is changed to 'address\_line1'. Hence the code will be as follows

```
$lang = $node->language;
$node->field_address[$lang][0] = array(
  "country_code" => "US",
  "address_line1" => "123 Fake Street",
  "locality" => "Beverly Hills",
  "administrative_area" => "CA",
  "postal_code" => "90210"
);

```

---
Tags: 7, entities
---


# Question
Title: How do I use a different structure of a theme on different pages?
The picture shows the block region demonstration of a Drupal theme that I am using.

I am new to Drupal.

As the structure is given, I want to use different structure in different pages of my site. Say, at home page I want to use all the block regions Left Sidebar, Content and Right Sidebar. But for another page (one of the main navigation) I only want to use one of the sidebars with content and leave other sidebar. Also I want to add custom blocks at various regions on different pages.

Is this possible? If yes, how should I do it?

# Answer
Theme block regions are just empty placeholders that mark up certain points within your HTML. Regions don't affect your site on their own, it is only when you put Blocks inside them that they show up.

Most (if not all) themes first check that a region isn't empty before printing the region container into the HTML. So regions don't appear in your HTML if there are no Blocks inside them.

What you should be focused on instead is Block Visibility, not regions. It makes more sense to control where each piece of *content* should appear, instead of controlling the containers/regions.

And you can control for each Block on which pages it should appear, so that is how you achieve the different structure of the pages. Some Blocks you set to display for example in sidebars regions but only on the front page. Some Blocks you put in the sidebar but only on node pages.

If there is a page that doesn't have any blocks set to appear in sidebars, then this page will not show any "sidebar area". It will be up to your theme CSS to style what the page without sidebars looks like. Most likely it will just be a simple one column area for your content.

There are modules that allow you for more control over the Blocks placement (Context for example), that do something that could be described as turning regions on or off, but that is a slightly different approach and I think you should play with the original Blocks arrangement first if you're new to Drupal. It is much easier to understand and setup Blocks to be visible on only sections of your website.

In Drupal 8 you can place the same Block more than once, in another region, or even the same region. You can then adjust the Visibility to different conditions, so for example you can have your Main navigation displayed in Header region on the front page, but displayed in the sidebar on all other pages.

BTW the above example isn't the best one, navigation should be always in the same place for accessibility and other reasons. But I hope you understand the concept of placing Blocks in regions, but then using Visibility to make them appear on only certain pages, and not others.
> 0 votes

---
Tags: blocks
---


title: Related events block

text:
# Question
Title: Related events block
I have a content type, Venues and a content type Events. In the Events post type, I have 'field\_hosted\_by' - allowing me to select the relevant venue.

On each venue page (/venue/venue-name), i'd like to create a block listing the events they are hosting – what would be the best way to do this?

I had a solution using taxonomies but this seemed inefficient, i'd rather not have to create a term for each venue, as well as a node.

* Using Drupal 8.

# Answer
Taxonomy terms are still entity reference fields, just like the field you have connecting your events and venue nodes. So there is no need to duplicate the same functionality.

You can list the Events referencing the Venue with a Views Block:

1. Create Content Views with Block display listing Events
2. Add a Contextual filter for the `field_hosted_by` field and configure it:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Content**
**Venue**
3. Save the Views and place the Block in a region of your choice to be displayed on Venue pages

You cant test the views output by entering the node ID of a venue node into Preview field, before placing the Block to test it's working.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: Content type Text field as Geolocation source field in View
I have a text field(named as address) in my content type and I will store the address in that text field. Here I don't want to store the address in geolocation field so I have to use text field to store address.

I just created the View with page and have set Format as "Geolocation Google Maps API - CommonMap". In that Format settings I have to set Geolocation source field to display the Map. But I can't able to set Content type Text field as Geolocation source field.

Is there any way to set **Content type Text field as Geolocation source field**?

# Answer
> 0 votes
Map formatters usually only take geolocation data in order to display them (latitude and longitude for example). There is a way to "convert" a textual address into geolocation data with the help of a Geocoding service.

So you *do* have to create a geolocation field. You can set it to automatically take the address and convert it to points on a map, and you can hide this field from users. It's a problem though if the address someone enters isn't correct in some way.

With the geodata ready in that field you can set your views map to use that field as the source for geo points on a map.

Here's a comparison of modules that can help you with this: Comparison of Mapping modules.

It seems your best bet is Geofield Well Known Text and Geocoder.

---
Tags: views, 8, nodes
---


# Question
Title: My content type has a string of words, how do I make them tags?
I am very new to drupal. I currently have a content type called 'Issue', which has a plain text field containing something like "money, houses, pigs". How can I look at that string and turn each word into a tag?

The reason I have this is because I read data in from an older database, and they had their tags saved as a string. I read it in using the feeds module.

Is there a way to read in the tags differently? Or is there a way to parse that string and add each word as a tag in my content type?

Note, I read in the database as a CSV file.

My end goal here is to be able to 'query' for all Issues tagged with the word 'house' for example and display those.

Thanks in advance.

# Answer
> 0 votes
You can do it using the Feeds module, you probably could have done it when importing the data for the first time.

Create the Taxonomy you need with all the terms.

Export the relevant nodes information containing the text field, in the CSV copy the text field column and manipulate it so you can use it to import the terms into a multi-value Term reference field.

This requires a bit of Excel/Calc magic. It will probably be term IDs separated by semicolons IIRC.

Then use a Feeds importer to update the existing nodes (the same ones you exported), make sure to map the correct column to the Term reference field for the new Taxonomy.

---
Tags: 8, taxonomy-terms, feeds
---


# Question
Title: Logging URLs in the PHP-FPM Access Log - possible Clean URL Conflict
I have set up an access log in PHP-FPM under pool.d/www.conf, and I noticed that the log usually constructs the URL as "index.php" with all query parameters, EXCEPT for 'q,' which is the URL. I know that this is removed by the server for clean URLs, so would anyone know how to collect this?

Looking at the access log format instructions, it seems like there should be a header specifying location. I'll see if I can find one in Charles Web Proxy.

Here are the relevant config file sections:

### from NGINX site config:

```
location / {
    # try_files $uri @rewrite; # For Drupal <= 6
    try_files $uri /index.php?$query_string; # For Drupal >= 7
}

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

...

location ~ '\.php$|^/update.php' {
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    # Security note: If you're running a version of PHP older than t$
    # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
    # See http://serverfault.com/q/627903/94922 for details.
    include fastcgi_params;
    # Block httpoxy attacks. See https://httpoxy.org/.
    fastcgi_param HTTP_PROXY "";
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_intercept_errors on;
    # PHP 5 socket location.
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    # PHP 7 socket location.
    #fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

```

### from /path-to-php5/fpm/pool.d/www.conf

```
; The access log file
; Default: not set
access.log = /var/log/php5-fpm/$pool.access.log

; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request

...

;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some exemples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e

...

;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o

;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
access.format = "%R|%u|%t|%m|%r%Q%q|%s|%f|%{mili}d|%{kilo}M|%C%%"

```

# Answer
I am using

```
access.format = "[%t] %m %{REQUEST_SCHEME}e://%{HTTP_HOST}e%{REQUEST_URI}e %f pid:%p took:%ds mem:%{mega}Mmb cpu:%C%% status:%s {%{REMOTE_ADDR}e|%{HTTP_USER_AGENT}e}"

```

which logs lines like

```
[16/Nov/2018:23:54:13 +0100] GET https://realdomain.com/path?param /linux/path/file.php pid:1234 took:1.035s mem:2mb cpu:0.99% status:200 {192.168.1.10|Mozilla/5.0 (full User-Agent)}

```

More info: https://github.com/php/php-src/blob/master/sapi/fpm/www.conf.in#L257-L318
> 2 votes

# Answer
Here's the answer I've come up with so far: I am having Drupal generate an X-URI header, and am adding %{X-URI}o to the log format. So far this is producing the type of report we are looking for.
> 0 votes

---
Tags: nodes, uri
---


# Question
Title: Themeing custom form as table and getting updated field values on submit
In my attempt to create a table that shows all of the locales for a node and contains two editable fields, I've come up with the following functions:

```
function language_dashboard_overview_form($form, &$form_state, $entity) {
  $form = [];
  $options = [];

  $header = [
    'language_locale' => t('Language Locale'),
    'status' => t('Status'),
    'staging_url' => t('Staging URL'),
    'start_date' => t('Start Date'),
    'end_date' => t('End Date'),
    'display_title' => t('Display Title'),
  ];

  $translations = $entity->translations->data;

  foreach($translations as $locale => $locale_data) {
    // Add the CSS for the icons.
    drupal_add_css(drupal_get_path('module','language_dashboard') . '/css/language_dashboard.css');
    // Link to edit page for locale.
    $locale_link = "<a href='/$locale/node/$entity->nid/edit?destination=node/$entity->nid/languagepublishing'>". $locale ."</a>";
    // Locale status
    $status = $locale_data['status'] == 1 ? '<div class="check-wrapper"><span class="fluke-icon fluke-icon-checkmark"></span></div>'
      : '<div class="close-wrapper"><span class="fluke-icon fluke-icon-close"></span></div>';
    // Link to item on staging site
    $uri = entity_uri('node', $entity);
    $path_locale =  drupal_get_path_alias($uri['path'], $locale);
    $full_path = 'http://staging-igcommerce.flukedev.com/' . $locale . '/' . $path_locale;
    l('<div class="search-wrapper"><span class="fluke-icon fluke-icon-search"></span></div>', $full_path, array('html' => TRUE, 'attributes'=>array('target'=>'blank')));
    $stage_url = l('<div class="search-wrapper"><span class="fluke-icon fluke-icon-search"></span></div>', $full_path, array('html' => TRUE, 'attributes'=>array('target'=>'blank')));
    // Display title
    $title = fluke_solr_fallback($locale, $entity, 'field_content_title', "value", FALSE);
    // Define start and end date text fields.
    $start_date = isset($entity->field_locale_publishing_dates[$locale][0]['value']) ? $entity->field_locale_publishing_dates[$locale][0]['value'] : '2049-01-01T00:00:00';
    //$start_date_object = new DateTime($entity->field_locale_publishing_dates[$locale][0]['value']);
    $start_date_object = new DateTime($start_date);
    $new_start_date = $start_date_object->format('n-j-Y');

    $end_date = isset($entity->field_locale_publishing_dates[$locale][0]['value2']) ? $entity->field_locale_publishing_dates[$locale][0]['value2'] : '2050-01-01T00:00:00';
    //$end_date_object = new DateTime($entity->field_locale_publishing_dates[$locale][0]['value2']);
    $end_date_object = new DateTime($end_date);
    $new_end_date = $end_date_object->format('m-d-Y');

    $form['locales'][$locale]['checkbox_' . $locale] = [
      '#type' => 'checkbox'
    ];

    $form['locales'][$locale]['language_locale'] = [
      '#markup' => $locale_link
    ];

    $form['locales'][$locale]['status'] = [
      '#markup' => $status
    ];

    $form['locales'][$locale]['staging_url'] = [
      '#markup' => $stage_url
    ];

    $form['locales'][$locale]['start_date'] = [
      '#type' => 'textfield',
      '#size' => 10,
      '#maxlength' => 10,
      '#value' => $new_start_date
    ];

    $form['locales'][$locale]['end_date'] = [
      '#type' => 'textfield',
      '#size' => 10,
      '#maxlength' => 10,
      '#value' => $new_end_date
    ];

    $form['locales'][$locale]['display_title'] = [
      '#markup' => $title
    ];

  }

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit')
  ];

  return $form;
}

/**
 * Theme function for language_dashboard_overview_form
 */
function theme_language_dashboard_overview_form($vars) {
  $output = '';
  $rows = [];
  $form = $vars['form'];
  $locale_items = $form['locales'];

  $header = [
    t('Select'),
    t('Language Locale'),
    t('Status'),
    t('Staging URL'),
    t('Start Date'),
    t('End Date'),
    t('Display Title')
  ];

  $locales = array_filter(array_keys($locale_items), function($value) {
    return substr($value, 0, 1) != '#';
  });

  foreach($locales as $locale) {
    $test = 'a';
    $row = [
      drupal_render($form['locales'][$locale]['checkbox_' . $locale]),
      drupal_render($form['locales'][$locale]['language_locale']),
      drupal_render($form['locales'][$locale]['status']),
      drupal_render($form['locales'][$locale]['staging_url']),
      drupal_render($form['locales'][$locale]['start_date']),
      drupal_render($form['locales'][$locale]['end_date']),
      drupal_render($form['locales'][$locale]['display_title'])
    ];

    $rows[] = $row;
  }

  $table_vars = [
    'header' => $header,
    'rows' => $rows
  ];

  $output = theme('table', $table_vars);

  $output .= drupal_render($form['submit']);
  $output .= drupal_render_children($form);

  return $output;
}

/**
 * Implements hook_entity_update().
 */
function fluke_staging_entity_update($entity, $type) {
  // Index the entity to the staging environment.
  if (in_array($type, array('node', 'taxonomy_term'))) {
    fluke_staging_index_solr($entity, $type, 'staging');
  }
}

```

This builds the form ok, but I have two big problems when the form is submitted: 1) `$form_state['values']` doesn't contain multiple records; instead it just contains values for all of the checkboxes, the two text fields, and the form values (token, id , etc) 2) The date values don't contain the updated values input into the form.

What do I need to change to achieve my desired results of 1) getting all of the rows from the table and 2) getting the updated values from the text fields?

# Answer
> 0 votes
1) By default `$form_state['values']` holds a flattened array, it does not maintain the original form array structure and each locales keys will override the previous one. However, this should not affect `'checkbox_' . $localeUse` precisely because you build up this key from $localeUse variable.

You can change this default behavior by using the `#tree` property that defaults to `FALSE` : `$form['locales']['#tree'] = TRUE;`

---

2) Use `$form_state['values']` when available in your form builder. Values should be available when the form is rebuilt after it is submitted. You will have to override defaults explicitly, e.g. :

```
if (!empty($form_state['values'][$locale]['start_date'])) {
  $start_date = $form_state['values'][$locale]['start_date'];
}
else {
  // initial assignment
}

```

---
Tags: 7, forms
---


# Question
Title: how to create signup form with MailChimp module
I want to follow the tutorial at https://drupalize.me/videos/create-your-first-mailing-list-and-sign-form?p=2235 but I'm stumbling as soon as we get to create sign up forms in the `MailChimp` module configuration. I don't see a "SIGNUP FORMS" tab but instead I get 5 red error messages on top that say **Failed to load MailChimp PHP library. Please refer to the installation requirements.** and if I look under `/admin/reports/status`, I see **The MailChimp MCAPI library could not be found.** under the `MailChimp` module. How can I get these resolved?

# Answer
> 2 votes
I get it. You’ve just signed up for Mailchimp and set up your first list. You want to put a signup form on your Drupal 8 (probably works in D7 as well) website so visitors can start signing up for your newsletter or announcements. Here's how you place a signup block. I know this is a late answer, but hopefully it will help someone. To get through this process you have to clear cache a lot. Here's what worked for me.

Install and enable the mailchimp module and the Mailchimp\_signup module. Set up the API key with your mailchimp API clear cache (on the command line you can type ‘drush cr’ or you can do it in the admin menu | config page | performance link | clear all caches button).

Go to admin/config/services/mailchimp/signup and add a signup form. Give it a name and remember the name since that’s what you’ll search for when you’re ready to place the block. Check the ‘Block’ checkbox. Choose at least one list that you’ve set up on Mailchimp’s website or on the Lists tab. Save the form.

Refresh cache ‘drush cr’ again.

Go to the Structure | Block layout tab. Choose a region where you would like the signup tab and choose ‘Place block’. Search for the name you used when naming your signup form. Choose it and ‘Save block’.

Now go to your site and observe your work. Your form will appear in the area you specified.

# Answer
> 0 votes
The module isn't able to find the required library. You can follow the instructions on the project page or the follow the Drupalize video tutorial in the series you linked to. If you've already followed those steps, there's a good chance you've not set the correct ownership/permissions on the API libraries so that the Drupal can load/execute the API code.

---
Tags: 7, emails
---


# Question
Title: How to change the format that shows the autocompletion of reference entities?
I am trying to change the format that it shows by default in the text fields that have an associated reference entity.

I found an article where a format modification is made, I think it may be a good starting point, but this module changes the format of all the fields of the whole site, what I am trying to do is that I can define the format by type of content, that is, for Articles, it would have one format and another type of content, depending on what is most convenient.

For example, in the module mentioned, it changes the behavior of the autocomplete globally, is there a way to do it by type of content?

```
<?php
namespace Drupal\alter_entity_autocomplete\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;

use Symfony\Component\Routing\RouteCollection;

class AutocompleteRouteSubscriber extends RouteSubscriberBase {
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.entity_autocomplete')) {
      $route->setDefault('_controller', '\Drupal\alter_entity_autocomplete\Controller\EntityAutocompleteController::handleAutocomplete');
    }
  }
}

```

Is there any way to do it?

The github project of the module

# Answer
You can filter for the entity type & bundle in the getMatches() method.

It is also possible to add specific handlers to *your* forms: https://www.qed42.com/blog/autocomplete-drupal-8
> 0 votes

---
Tags: 8
---


# Question
Title: Programmatically set value of Boolean radio button field in form
I am using a custom field in the profile2 module for when a user registers. The field is a Boolean field using the radio button widget.

I want to programmatically set the value for the field using hook\_form\_alter().

I have managed to successfully set the #default\_value using:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['profile_company']['field_employees']['und'][0]['value']['#default_value'] = 0;
}

```

But this code does not actually check the No button, so it looks like nothing has been selected and when the form is submitted it throws an error saying that that field is required and nothing has been selected.

How can I get the code to actually check one of the buttons as well as setting the default value, based on values that I want to pre-fill the form with?

The code above would work fine with a text field, It just doesn't work with a Boolean field using radio buttons.

I have spent a while on this and can't seem to find an answer. I thought maybe I need to use the field #after\_build property or possibly JavaScript?

I'm attaching a screen grab of my field settings.

# Answer
> 1 votes
First, check you are setting the `#default_value` property at a correct level in the $form array. It seems quite weird to get multiple values in `$form['profile_company']['field_employees']['und']`, so I'm not sure about assigning defaults nested under `[0]['value']` (but I could be wrong).

A good rule is to ensure you set `#default_value` at the same level as the `#options` array. For example, if you would have these options under the lang code like :

```
print_r($form['profile_company']['field_employees']['und']);

# Output :
Array
(
    ['#options'] => Array (
        # ... => ...
    ),
    # ... => ...
);

```

... you would set the `#default_value` at the same level :

```
$form['profile_company']['field_employees']['und']['#default_value'] = $default_value;

```

---

Secondly, ensure the `#default_value` is mapped to an existing key in the form `#options` array :

```
# Let's say your options are defined as :
$form['profile_company']['field_employees']['und']['#options'] = array(
  0 => t('N/A'),
  1 => t('No'),
  2 => t('Yes')
);

# This would set 'N/A' as default :
$form['profile_company']['field_employees']['und']['#default_value'] = 0;

```

---
Tags: 7, forms
---