title: Can't login with varnish enabled

text:
# Question
Title: Can't login with varnish enabled
I can't login from the front-end with varnish installed. Here's what I think it is issue

```
sub vcl_recv {

 # Do not cache these paths.
 if (req.url ~ "^/status\.php$" ||
  req.url ~ "^/admin$" ||
  req.url ~ "^/admin/.*$" ||
  req.url ~ "^/admin/?" ||
  req.url ~ "^/user" ||
  req.url ~ "^/user/.*$" ||
  req.url ~ "^/users/.*$") {
  return (pass);
 }

```

and the session cookies

```
if (req.http.Cookie) {
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|NO_CACHE)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|SSESS[a-z0-9]+|NO_CACHE)=", "; \1=");

```

If I try to login directly from apache port:8000 it works as expected. Here's the whole default.vcl file: http://pastebin.com/qPRyFEjP

I don't get why it's not piping to the authenticated users. Why wouldn't it login in? Thanks.

# Answer
> 3 votes
The offending parts in your VCL are (line 53):

```
# Drop any cookies sent to Drupal.

 if (!(req.url ~ "install\.php|update\.php|cron\.php|admin\.php")) {
 unset req.http.cookie;
 }

```

and (line 81):

```
# Drop any cookies Drupal tries to send back to the client. This will make it unpossible to login, unless you filter it a bit better that it is made below
sub vcl_fetch {
 if (!(req.url ~ "install\.php|update\.php|cron\.php|admin\.php")) {
  unset beresp.http.set-cookie;
 }
}

```

Remove both of them.

# Answer
> 1 votes
I had the same issue and the solution was to explicitly set the cookie domain for the Drupal website in settings.php. For example:

```
 $cookie_domain = '.mydomain.com';

```

This way Drupal will store the session cookie correctly.

---
Tags: proxies
---


title: Fetch result of query twice

text:
# Question
Title: Fetch result of query twice
I faced with problem while fetching query results, my code:

```
$result = $query->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result->fetchAllKeyed(2, 0);

```

But the `$array2` is empty, so `fetchAllKeyed` cut all values from `$result`.

I'm already tried to use the following:

```
$query2 = clone $query;
$result = $query->execute();
$result2 = $query2->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result2->fetchAllKeyed(2, 0);

```

It's works, but I don't want do two queries instead of one.

So, how can I do two (or more) different "fetch" from one result?

# Answer
> 1 votes
Since fetchAllKeyed() internally uses foreach loop to sort the data, the answer given by Suranga Panagamuwa Gamage to use fetchAssoc() and then a loop seems the most efficient way.

---
Tags: 7, database
---


title: Subtheme for Subsite in Multisite

text:
# Question
Title: Subtheme for Subsite in Multisite
I have a Drupal 8 Multisite setup with the following Folder structure:

* themes
    + custom\_theme
        - main\_custom\_theme
* sites
    + site1
        - themes
            * subtheme1
    + site 2

So I want both sites to use main\_custom\_theme, but site1 needs to override one template (page.html.twig) with subtheme1. subtheme1 folder contains a subtheme1.info.yml as follows:

```
name: subtheme1
description: "Custom sub-theme"
core: 8.x
type: theme
base theme: main_custom_theme

```

I rebuilt all caches (Backend and drush cr, but drush cr might not clean caches of subsites?) but cannot select the new subtheme in Backend of site1. What am I missing?

---

This is the Twig Debug output after using leymannx answer, subsites path is "leistungen"

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * page--leistungen.html.twig
   * page--node--560.html.twig
   * page--node--%.html.twig
   * page--node--article.html.twig
   * page--node.html.twig
   x page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my_custom_theme/templates/main/page.html.twig' -->

```

---

I have a question that builds on this one... I published it appearently with a different user, without wanting to. Still new to not only reading stackexchange :)

If I try to do the same for the node of my content type, which is using a template named node--CONTENTTYPENAME.html.twig at the moment, I can insert a name suggestion node--NAMEOFSUBSITE.html.twig, which will then be used for ALL nodes. I'd like to insert a suggestion such as node--CONTENTYPENAME--NAMEOFSUBSITE.html.twig, for only this one nodetype.

How can I do that?

Thanx in advance!!

# Answer
In Drupal 8 you are supposed to organize your themes and multi-site instances like in the following structure. I only highlight the relevant folders.

```
__docroot
  |__modules
  |  |__contrib
  |  |  |__devel
  |  |  |__views
  |  |__custom
  |     |__my_module_abc
  |     |__my_module_xyz
  |__sites
  |  |__default
  |  |  |__settings.php
  |  |__site1
  |  |  |__settings.php
  |  |__site2
  |     |__settings.php
  |__themes
     |__contrib
     |  |__bootstrap
     |__custom
        |__my_bootstrap_subtheme

```

So, if you want to create a sub-theme of a custom theme, you also have to place it inside `docroot/themes/custom`. Then it will appear in your back-end where you can enable it.

---

But what I would recommend instead of adding another sub-theme, is to simply add a template suggestion based on the multi-site instance name via `hook_theme_suggestions_HOOK_alter`. By that you can move on with only one custom theme (which is much easier to maintain in the end), and inside its `MYTHEME.theme` file you'll switch the page template for your certain multi-site instance like following.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $site_path = \Drupal::service('site.path');
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $suggestions[] = 'page__' . $site_name;
}

```

Now you simply can place `page--site1.html.twig` in your theme's template folder and `site1` will take this page template instead the default `page.html.twig`. (Source)

---

Tried it on a fresh D8 with Twig debugging enabled and it works just fine.

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   x page--site1.html.twig
   * page--front.html.twig
   * page--node--1.html.twig
   * page--node--%.html.twig
   * page--node.html.twig
   * page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my-custom-subtheme/templates/page--site1.html.twig' -->

```
> 1 votes

---
Tags: theming, multi-sites
---


# Question
Title: INVALID_SERVICE Error Code on CAS forced login page
i have configured a forced login for the `/intranet` page

```
/fr/admin/config/people/cas

```

I have created a menu link to that page `/intranet`

when clicking on it , the cas creadential are asked and it returns an

> INVALID\_SERVICE error

```
http://mywebsitedomainfr/casservice?q=fr%2Fcasservice&returnto=http%3A%2F%mywebsitedomain%2Ffr%2Fintranet%3Fq%3Dfr%252Fintranet&ticket=ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserver||0||Validation response received from CAS server: #012#012#012#012#011#012#011#011Le ticket 'ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserver' ne correspond pas au service demandé. Le service original était 'http://mywebsitedomain/fr/casservice?returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet' et le service demandé était 'http://mywebsitedomain/fr/casservice?q=fr/casservice&returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet'.
Error when validating ticket: Error Code INVALID_SERVICE: Le ticket 'ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserveur ne correspond pas au service demandé. Le service original était 'http://mywebsitedomain/fr/casservice?returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet' et le service demandé était 'http://mywebsitedomain/fr/casservice?q=fr/casservice&returnto=http%3A//mywebsitedomain/fr/intranet%3Fq%3Dfr%252Fintranet'.
http://mywebsitedoamin/fr/casservice?q=fr%2Fcasservice&returnto=http%3A%2F%2Fmywebsitedomain %2Ffr%2Fintranet%3Fq%3Dfr%252Fintranet&ticket=ST-74551-ESB2kMRXfQ5UcMbqajPd-mycasserverdomain||0||Converting query parameter 'returnto' to 'destination'.
http://mywebsite domain/fr/intranet?q=fr%2Fintranet&q=fr%2Fintranet||0||Temp disable flag set, skipping CAS subscriber.

```

# Answer
> 0 votes
this happened to be a nginx misconfiguration

---
Tags: 8
---


# Question
Title: How to use stye attribute in custom block markup?
I'm developing a custom block in Drupal 8. In my `build()` method I've got:

```
$progress_markup = array(
  '#theme' => 'progress_bar',
  '#percentage' => $registration_percentage,
  '#message' => array('#markup' => $registration_node_count . ' of ' . $this->configuration['capacity']),
);
$markup = \Drupal::theme()->render('progress_bar', $progress_markup);

```

This generates the following HTML:

```
<div class="progress" data-drupal-progress>
  <div class="progress__track"><div class="progress__bar" style="width: %"></div></div>
  <div class="progress__percentage">%</div>
  <div class="progress__description">30 of 120</div>
</div>

```

However, when the block renders on the page, the `style` attribute has been removed. Here's the relevant D8 issue.

What I don't understand is: if I create a custom block and use Full HTML, and paste in the generated markup that contains the `style` attribute, Drupal 8 will happily render it. But when I generate this markup in the `build()` method, it gets removed.

Is there a way to specify, in the block plugin definition, that the `build()` method should not filter out any HTML? Any other thoughts on how ot get around this issue?

# Answer
This is a working example of adding the style attribute to the render array of a block via the build() method.

```
<?php
/**
 * @file
 * Contains Drupal\foo\Plugin\Block\FooBlock
 */

namespace Drupal\foo\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * @block(
 *   id = "foo",
 *   admin_label = @Translation("Foo block")
 * )
 */
class FooBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * If a block should not be rendered because it has no content, then this
   * method must also ensure to return no content: it must then only return an
   * empty array, or an empty array with #cache set (with cacheability metadata
   * indicating the circumstances for it being empty).
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    return [
      'inside' => [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => 'Hello world',
        '#attributes' => [
          'class' => ['some-class'],
          'style' => ['color:red']
        ]
      ]
    ];
  }
}

```
> 5 votes

# Answer
You need to put a `#attributes` property in your render array, but at the **root** of the render array. Here we add `block-class` class to the block :

```
class FooBlock extends BlockBase {

  public function build() {
    return [
      'inside' => [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => 'Hello world',
        '#attributes' => [
          'class' => ['inside-class'],
        ]
      ],
      '#attributes' => [
        'class' => ['block-class']
      ]
    ];
  }
}

```
> 0 votes

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


# Question
Title: Schedule Migrate to import XML data regularly
Is it possible to schedule Migrate to import/update my XML regularly, say, once an hour? Maybe in Rules?

**EDIT:** I have a skeleton of a module written for this now, to hook into Rules.

*Event:* If there are unimported nodes, or if it has been more than 15 minutes since the last import

*Condition:* Just the machine name of the Migration, and its enddate timestamp

*Actions:* I want two, one to do an import and rollback, and another to update and import.

I am having trouble trying to find what functions to call to initiate the actions, and which ones to get my arguments. Is there any good documentation on the core Migrate functions (not field handlers or anything) so that I can see which ones I need?

**EDIT 2** I ended up with this cron function. Is this how it's written? And I can put it into my module where the rest of my migration is? I also need to specify that it should update any nodes already imported. How do I do that?

```
    function mymodule_cron() {
            $last_run = variable_get('mymodule_last_cron', 0);
            $interval = variable_get('mymodule_interval', 60);
            if(time() - $last_run > $interval){
                 variable_set('mymodule_last_cron', time());
                 $migration = Migration::getInstance('ImportNodes');
                 $result = $migration->processImport();
            }
     }

```

# Answer
> 3 votes
I think the best way to achieve your goal is to use Drupal's cron, not Rules.

Cron is a service that will trigger the execution of a function, depending on the frequency you want it to.

You just have to implement hook\_cron in your custom module to execute your migration. You will have to take care of the frequency you need for your script. I found this example useful.

How to run migration programmatically? As stated here, it's very simple:

```
<?php
  $migration = Migration::getInstance($machine_name);
  $result = $migration->processImport();
?>

```

# Answer
> 1 votes
For Drupal 8, you can use the Migrate Scheduler module for it. It uses the Cron API internally.

> The Migrate Scheduler module provides the functionality of executing the migrations on a particular schedule.

P.S - I am the author and maintainer of the module. Any feedback is welcomed in the issue queue.

# Answer
> 0 votes
Have you had a look at the Feeds module? That could maybe help you with whatever you're trying to do. Also the Feeds XPath Parser will help you with any specific XML.

---
Tags: importing-exporting, migrations, rules
---


# Question
Title: Why is my custom parameter converter class not used?
I start banging my head on the table, the wall or anything else... please help me.

Here is my my\_module.routing.yml:

```
my_module.api.validate_coupon:
  path: '/api/v1/{coupon_code}/validate'
  defaults:
    _controller: '\Drupal\my_module\API\ValidateCouponController::validate'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      coupon_code:
        type: coupon_code_converter

```

This is my services.yml

```
services:
  paramconverter.coupon_code_converter:
    class: Drupal\my_module\Routing\CouponCodeConverter
    tags:
      - { name: paramconverter }

```

This is my converter class - it is taken from Drupal\language\LanguageConverter and I added some breakpoints which should make the script stop in my IDE:

```
namespace Drupal\my_module\Routing;
use Drupal\Core\ParamConverter\ParamConverterInterface;
use Symfony\Component\Routing\Route;

/**
 * Converts a coupon code to a fully loaded coupon
 */
class CouponCodeConverter implements ParamConverterInterface {

  /**
   * {@inheritdoc}
   */
  public function convert($value, $definition, $name, array $defaults) {
    if (!empty($value)) {
      return $this->languageManager->getLanguage($value);
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'language');
  }
}

```

And this is my controller class:

```
namespace Drupal\my_module\API;

use Drupal\Core\Controller\ControllerBase;

class ValidateCouponController extends ControllerBase  {

  public function validate($coupon_code) {
    $container = \Drupal::getContainer();
    $kernel = $container->get('kernel');
    $services = $kernel->getCachedContainerDefinition()['services'];
    ksort($services);
    return array(
      '#markup' => 'hallo'
    );
  }
}

```

I can enter http://mypath.com/api/v1/1/validate and the controller gets the value '1' for $coupon\_code. But I want my CouponCodeConverter class to do some magic before the parameter gets sent to the Controller... but the converter gets not called... what do I wrong?

# Answer
> 2 votes
I think the condition in applies() doesn't match with the route parameters, try this:

```
  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'coupon_code_converter');
  }

```

---
Tags: 8, routes
---


# Question
Title: Responsive background image in Twig template
I would like to render an image as background image in my Twig template. To optimize my resources I'd like to use a responsive image but I cannot find a way to use it for background images.

For a standard image I would use something like

```
img src="{{ file_url(node.field_with_image.entity.uri.value) }}" alt="my_alt" class="my_class">

```

How can I achieve that with a background image?

# Answer
> 0 votes
You should definitely have a look at Background Images Formatter.

> It contains a submodule to handle responsive images as well.

Either use that or check how they are doing it.

---
Tags: 8, theming, media
---


# Question
Title: Dynamic local tasks to the same route with slug
I have a route set up with a slug accepting taxonomy terms (`routing.yml`):

```
example.column:
  path: '/column/{taxonomy_term}'

```

I would like to add (secondary, although that's not important) local task tabs on a page, one for each possible term of the vocabulary used (`links.task.yml`):

```
example.column_list:
  deriver: 'Drupal\example\Plugin\Derivative\ColumnTasks'
  parent_id: example.parent

```

The deriver is pretty straightforward and simple and mentioned in a few docs on drupal.org, the relevant part is:

```
foreach ($columns as $column) {
  $route_name = 'example.column';
  $this->derivatives[$route_name] = [
    'title' => $column->getName(),
    'route_name' => $route_name,
    'route_parameters' => ['taxonomy_term' => $column->id()],
    'parent_id' => 'example.parent',
  ] + $base_plugin_definition;
}

```

The problem is that this code, obviously, doesn't generate more than one tab because all go to the same `$route_name`. But I'm not allowed to use any other route name (suffixing it with the term, for instance) because it complains about a non-existent route then.

Do I have any other solution than to generate all the routes separately, using a `_route_callback`? This would somehow feel wrong, going against the reason for the existence of slugs in the first place.

# Answer
> 1 votes
The array key is *not* the route name, it's the machine name of the local task. It's pretty common to use the same string but that's in no way a requirement.

Just use a different array key and this should work.

---
Tags: 8, routes
---


# Question
Title: How to display content where author matches connected user?
is it possible to modify admin/content view to display only the content the connected user has created ?

If not , how to achieved that?

# Answer
> 1 votes
thanks to kevin

with contextual filters , selecting fixed value:

author == id of connected user

---
Tags: views, 8, users
---


# Question
Title: What is the difference between core.entity_form_mode and core.entity_form_display?
I'm trying to learn how to configure content types and form modes programmatically in Drupal 8. I've created the following using the UI:

* A content type named `book`
* A form mode for content, named `foo`
* A view mode for content, named `bar`

When I run `drush cget`, I get this list:

```
...
[36] core.entity_form_display.node.book.default
[37] core.entity_form_mode.node.foo
[38] core.entity_form_mode.user.register
[39] core.entity_view_display.node.book.default
[40] core.entity_view_display.node.book.teaser
[41] core.entity_view_mode.node.bar
[42] core.entity_view_mode.node.full
[43] core.entity_view_mode.node.rss
[44] core.entity_view_mode.node.search_index
[45] core.entity_view_mode.node.search_result
[46] core.entity_view_mode.node.teaser
[47] core.entity_view_mode.user.compact
[48] core.entity_view_mode.user.full
...

```

What is the difference between the `entity_form_display` configuration (36) and the `entity_form_mode` configurations (37, 38)?

# Answer
`entity_form_mode` would be the *form mode* (/admin/structure/display-modes/form)

* 37 - Form mode `foo` available for use on `node` entities (shows as content on the link above)
* 38 - Form mode `register` available on `user` entities.

`entity_form_display` is the configuration for that mode on a specific bundle - how the fields are arranged (/admin/structure/types/manage/book/form-display/{form\_mode}) - in your case `form_mode` would be foo.

* 36 - Form display settings for the `default` display on the `book` bundle (content type) of the `node` entity.

The reason `36` is `default` is because you have arranged your form display (/admin/structure/types/manage/book/form-display) but you haven't enabled your `foo` mode.

At the bottom of that page is a fieldset called "Custom display settings". Expand that and you can enable your `foo` display for that content type.

In the picture, I have a created a `form mode` called `Inline Entity Form`, yours should say `foo`
> 4 votes

---
Tags: 8, configuration
---


title: Referencing nodes reciprocally

text:
# Question
Title: Referencing nodes reciprocally
I have a content type called *Project* which can relate to n projects of the same content type. This is done with a field called *related projects* using the D8 core Entity References. A possible relationship could look like that:

```
            Project B
          /
Project A
          \
            Project C

```

Project templates should show all linked projects in both directions. Also would be great to edit the relations in both ways, when editing *Project A* but also when edition *Project B*.

This works fine for projects which have projects defined in the *Related Projects* field, like *Project A* in the example. But it doesn't work out for referenced projects like *Project B* and *Project C*. This is because of the directed nature of Entity References.

I try to use Corresponding Entity References module which *"syncs the node reference between two node types which have a nodereference to each other"* configuring it like that on */admin/config/content/cer*:

1. First field: *related\_projects*
2. Second field: *related\_projects*
3. Package: *Node: Project*

But *Project B* and *Project C* don't get updated when saving *Project A*. What am I doing wrong? Or is there another possible solution for syncing node references?

# Answer
> 1 votes
You can display both directions in Parent-Child Entity references with Views. You don't need to edit the reference to note direction in any special way.

The Entity reference field is already showing Children information on Parent nodes (your Project A is showing Project B and Project C).

## List Parent links on Child nodes using Views

To show Parent links on nodes that are referenced from that Parent (backwards relationship) create a block and display it on the Child nodes:

1. Create Views of type Content Project. You'll probably have the Title field already there, leave it for now just for testing.
2. Add a Contextual filter `ID` from Content Category 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
Validator **Content**
**Project**

Now if you enter the node ID (either Project will do: A, B or C) into the Preview argument field, it will only show that node Title in the Views results. This is just to test that our contextual filter is working correctly, when we place it on Project pages.
3. Add a new Relationship **Content using field\_project\_reference** (Relate each Content with a field\_project\_reference set to the content.) This is the backwards Relationship! Be careful *not* to include the forwards one that is called "Content referenced from field\_project\_reference"!

**Require this relationship** because it makes sense, we want only the results if the node we're on actually has a Parent, but it won't matter much if you don't tick this.
4. Edit the existing **Title** field and set it to use the Relationship from the previous step. The field using that Relationship will show the title of the Parent node, and not the one you're currently viewing, like it did up until now.

Edit the label to say "Other Projects referencing this Project" or similar.

Under **No results behavior** choose
**Hide if empty**

This will ensure that if the node you're currently viewing doesn't have any other nodes referencing it, nothing will be displayed. Otherwise, you'd get the Label and No results text (if you have it configured which you always should), or just the Label "Other Projects referencing this Project" with nothing listed there. With "Hide if empty" the block will not display anything which is more inline with displaying Fields on node pages.
5. Now place this Block on Project nodes in Content region if you want it show close to the orignal Entity reference field, set the Block settings **Content ID: Node from URL** and restrict to show it on Project types only.

You can use these Views to display other information from references nodes, not only Titles.

---

In Drupal 7 the module Relation provided two-way references, but it seems in Drupal 8 you can recreate that without that module. If you need fields on your Relation/Entity reference or other features read the comments at the bottom: Relation for Drupal 8 Development.

---
Tags: 8, nodes, entities
---


# Question
Title: Redirect links to nodes of past events to the up-to-date version
On a event-centered site we have a lot of recurring events, but there's no pattern like every first monday etc. So the editors just clone the event with node-clone and with pathauto we generate a date-token that is appended to the url.

After the date is gone, these events are deprecated and get unpublished (by Rules). But still people find links to these events via search engines and the like.

How can we automatically redirect links of past events to a up-to-date one?

Right now the url looks like this: www.mydomain.com/events/eventname-300518 (which would be today the 30th of May)

I could add a "basic" event without the date token if that would help. So if a event gets unpublished a redirect to the basic node could take place.

Can you point me in the right direction?

# Answer
> 1 votes
## Rules and Redirect

Since you're already using Rules to automatically Unpublish past events, you could try adding an Action that creates a Redirect from the unpublished node path to the latest one. You'll need a Redirect module that provides Redirect actions. I haven't tried this but I expect Redirect module to have that.

## Match Redirect

Or you could use the standalone solution Match Redirect.

## Server side Redirect

Redirects don't have to be handled within Drupal. You could create Rewrite rules in your server configuration too.

But this all might be the solution for the wrong problem.

## Better structure within Drupal

If the original event information doesn't change, and you only change the times, maybe you should structure it with 2 different content types, Event and Event instance or something that makes more sense.

The Event would hold everything except the times, and the Instances would only hold times. Then use Entity references to connect Instances to their Events.

Use Views to display Instances information on Events (Block or Attachment), you can use Views to filter out only future dates to display on Event nodes. And when marketing your event only ever share link to the Event node, that will always be showing correct relevant dates through the power of Views.

You can set your robots.txt to not index Instance content nodes on search engines, and in general don't link to them or show them to the users, only use the Instance information on Event nodes.

Or if you have per-date relevant information for the event (comments or similar), store it on the Instance node, and then again with the power of Views you can list past event info on the Event node itself, if anyone wants to read, look at past image gallery or similar.

That way you'd have both the future and past info available to be displayed how you want them, and only one Event link for marketing that would probably even be beneficial for SEO ranking.

---
Tags: 7, rules, redirection
---


# Question
Title: Drupal 8, make comment subject a required field
I am pretty new to Drupal and simply cant figure it out. I've set up a comment type for a content type. I want to use the default subject field as comment title and want to make it required.

I know, I could simply create a text field named "title" and make it required. But if I manage the comments in backend, there will always be (no subject) in the comments overview list. Is there any way to set it to required?

Thanks in advance!

# Answer
> 5 votes
Here is how, you will need to create a custom module , and add this ... to yourmodule.module file ...

```
/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
  if ($form_id === 'comment_comment_form') {

    $form['subject']['widget'][0]['value']['#required'] = TRUE;

  }
}

```

---
Tags: comments
---


# Question
Title: How to get submitted values on $formstate['values'] instead of $formstate['input']?
I was generating a simple form with below fields, but i am wandering why my field values are not storing in the $formstate\['values'\], but its in the $formstate\['input'\].. please have look into below code and correct me if i am doing something wrong.

```
function create_entry_form($form, &$form_state){
    $form['entry']['password'] = array(
      '#type' => 'password',
      '#required' => TRUE,
      '#default_value' => '',
      '#maxlength' => 15,
    );

    $form['entry']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('OK'),
      '#weight' => 100,
    );
    $form['entry']['emailid'] = array(
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' => '',
      '#maxlength' => 25,
    );

    $form['entry']['reqbtn'] = array(
      '#type' => 'button',
      '#value' => t('Request'),
      '#weight' => 106,
      '#executes_submit_callback' => TRUE,
      '#submit' => array('request_site_password'),
      '#limit_validation_errors' => array(),
    );

  return $form;
}
function request_site_password($form, &$form_state) {
    echo '<pre>';print_r($form_state);exit;
  }

```

# Answer
If you want to get $formstate\['values'\] or $form\_state\['input'\] values .You have to write like below.

```
    function create_entry_form($form, &$form_state){
        $form['entry']['password'] = array(
          '#type' => 'password',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 15,
        );

        $form['entry']['submit'] = array(
          '#type' => 'submit',
          '#value' => t('OK'),
          '#weight' => 100,
        );
        $form['entry']['emailid'] = array(
          '#type' => 'textfield',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 25,
        );

        $form['entry']['reqbtn'] = array(
          '#type' => 'submit',
          '#value' => t('Request'),
          '#weight' => 106,
          '#submit' => array('request_site_password'),
          );

      return $form;
    }
   function request_site_password(&$form, &$form_state) {
    drupal_set_message('<pre>' . print_r($form_state['input'], TRUE) . '</pre>');
  }

```

You missed '&$form' in this function request\_site\_password(&$form, &$form\_state)
> 1 votes

---
Tags: 7, forms
---


title: How to debug an empty cache_page table

text:
# Question
Title: How to debug an empty cache_page table
I have a bunch of sites built off the same profile, and recently noticed the pages aren't being cached. I spent some time doing the usual: looking for `drupal_set_message` calls, disabling all the modules that might disable page cache, as defined here. I've also dug into `drupal_page_get_cache`. This lead me to the database, where it turns out the `cache_page` table is empty.

This is clearly the source of the issue, I'm just not sure how/what is preventing the page cache. What I'd like to do is to figure out where page cache is writing to the database, and do a debug\_backtrace, or just `dpm` from that point backward.

A) Is there a point in drupal core where cache\_page is written to? B) Any other ideas for debuggings this? (please don't say disable all modules, then re-enable, we have upwards of 200 modules in place with a dozen custom module with interdependencies)

After posting this I opened my IDE and realized I had found the `DrupalDatabaseCache->set` method, and that the `cache_page` `$cid` is never called into that function.

# Answer
Whether or not a page is cacheable is determined by drupal\_page\_is\_cacheable().

Set a breakpoint there and dig into call stack / step through the conditions to determine the reason why nothing is saved to the `cache_page` bin.

Also take a look at drupal\_page\_footer() which calls into drupal\_page\_set\_cache() in order to store the built page in the page cache.
> 1 votes

---
Tags: 7, caching, debugging
---


# Question
Title: Translate a JS string from interface translations doesn't work
I've a problem about string translations.

I've built a multi-language site and in a custom module, in a JS file, I've used the function `t()` to make translatable some strings. These strings appear in `/admin/config/regional/translate` and I'm able to edit their value, but then, after cleared cache when I visit the site I see the strings not translated.

The strangest things is that for other elements the system works. I'm not able to debug this, my apache error and access logs are clear, nothing also in the message log of Drupal.

Anyone can help me? Thank u in advance

# Answer
Which string you want to translate before that you can use **Drupal.t**

like

```
var optionsList = '<option value="" selected>' + Drupal.t('Navigate...') + '</option>';

```
> 3 votes

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


# Question
Title: urol executed via bash throws exception error if role has a space in it
Role name "teaching assistant"

command executed is:

```
drush @comply-all urol "teaching assistant" sdf --y

```

if I copy and paste this it works fine. if the following command is called from a bash script it bricks every time when encapsulating the role name (which is needed otherwise it's evaluated by drush as two different arguments). Anyone experience anything similar?

```
[ulmusdrush@localhost ~]$ exception 'Drush\Role\RoleException' with message 'Could not find the role: "teaching' in          [error]
/home/ulmusdrush/.composer/vendor/drush/drush/lib/Drush/Role/RoleBase.php:46
Stack trace:
#0 [internal function]: Drush\Role\RoleBase->__construct('"teaching')
#1 /home/ulmusdrush/.composer/vendor/drush/drush/includes/drush.inc(113):
ReflectionClass->newInstanceArgs(Array)
#2 /home/ulmusdrush/.composer/vendor/drush/drush/commands/core/role.drush.inc(273):
drush_get_class('Drush\\Role\\Role', Array)
#3 /home/ulmusdrush/.composer/vendor/drush/drush/commands/user/user.drush.inc(281):
drush_role_get_class('"teaching')
#4 [internal function]: drush_user_add_role('"teaching', 'assistant"', 'qwe')
#5 /home/ulmusdrush/.composer/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_user_add_...', Array)
#6 /home/ulmusdrush/.composer/vendor/drush/drush/includes/command.inc(210):
_drush_invoke_hooks(Array, Array)
#7 [internal function]: drush_command('"teaching', 'assistant"', 'qwe')
#8 /home/ulmusdrush/.composer/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#9 /home/ulmusdrush/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62):
drush_dispatch(Array)
#10 /home/ulmusdrush/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#11 /home/ulmusdrush/.composer/vendor/drush/drush/drush.php(11): drush_main()
#12 {main}

```

# Answer
> 0 votes
Use

```
drush @comply-all urol "teaching\ assistant" sdf --y

```

Might be helpful to you.

---
Tags: drush, console
---


# Question
Title: How to always run hook_update_N automatically, regardless of the 'N' value?
I need to run a specific command after each update of a certain module. Is there any way to use `hook_update_N` without having to update the `N` for each version? A `hook_update_always` solution?

The use case is that I have Features with Rules. These Rules are not always reverted to the new version when the Feature is updated. If I can have a revert/delete function to run after every update of this Feature/module it would save me some headache.

# Answer
> 1 votes
Basically, all you have to do is to provide a custom module that implements `hook_update_N`, and everytime you want your features to be reverted, you add a new `hook_update_N` to your module time by time.

Starting with `hook_update_7001`, then `hook_update_7002`, then `hook_update_7003` etc. (presuming you are using D7).

On your live server then you have to run `drush updatedb`, it will check for the **newest** update functions and run the code that's put inside them.

And then there's this question which already has a lot of answers to show you what to put inside your update function to revert a feature programmatically (skip the Drush answer).

---

How you set up your deploy routine then, that's totally up to you. Normally you would have a webhook or some continuous integration SaaS like CircleCi setup to run a predefined deployment script **on every code release automatically**. This (Bash-)script then would run let's say `git pull`, `drush cc all`, `drush updb -y`, `drush fra -y` always automatically.

---
Tags: updating
---


# Question
Title: Drupal incorrectly reporting that permissions need to be set on settings.php
I've updated a site to v8.5.3. Checking the status report I have various messages. One says:

> Not protected Protection disabled
>
> * The file sites/default/settings.php is not protected from modifications and poses a security risk. You must change the file's permissions to be non- writable.
> * The file sites/default/settings.local.php is not protected from modifications and poses a security risk. You must change the file's permissions to be non-writable.

I've checked these files and they are set to `444`, there are no write permissions set. Drupal seems to be reporting this incorrectly.

Is there anything else I need to do or am I missing anything?

# Answer
They keyline here is `Protection disabled`.

Which means you have to check your `settings.php` or `setting.local.php` for

```
$settings['skip_permissions_hardening'] = TRUE;

```

which must be

```
$settings['skip_permissions_hardening'] = FALSE;

```

instead.

If it's not there already, add it.

Flush cache, done.
> 4 votes

---
Tags: 8, updating
---


# Question
Title: How do I delete a vocabulary programmatically?
In Drupal 7 there was `taxonomy_vocabulary_delete($vid)`, but this doesn't seem to be there in Drupal 8.

What's the equivalent code for Drupal 8?

# Answer
I believe I have figured this out. You have to load the vocabulary using the `Vocabulary` entity class, then call the delete method on it. So something like this:

`Vocabulary::load($vid)->delete();`
> 6 votes

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

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

```

Or

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

```
> 1 votes

# Answer
Here is how I did it

```
$vocabularies = [
'test',
'second_test'
];
foreach ($vocabularies as $vocabulary) {
    $vocab = Drupal\taxonomy\Entity\Vocabulary::load($vocabulary);
    if ($vocab) {
        $vocab->delete();
    }
}

```
> 0 votes

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


# Question
Title: How to make CKeditor format code indenting elements and adding line breaks?
Using CKEditor in Drupal 7, I could configure CKEditor to format the code adding line breaks and indenting the HTML code automatically.

For example, pasting this in the source code:

```
<div class="row"><div class="col-md-12">Test</div></div>

```

CKEditor could be configured to turn it into:

```
<div class="row">
    <div class="col-md-12">
        Test
    </div>
</div>

```

To achieve that, I just had to select the right configuration for CKEditor (Indent the element contents, Break line before the opening tag, Break line after the closing tag), and include the Javascript configuration:

```
config.allowedContent = true;

```

But in Drupal 8, I can't see those options and CKEditor removes all the whitespace from the source code.

How can I make CKEditor work like with that configuration in Drupal 8?

# Answer
> 1 votes
Finally I found a solution, thanks to the post CKEditor with well-formatted html source code.

I just added to a custom module the following code:

```
function mymodule_editor_js_settings_alter(array &$settings) {
  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
      $settings['editor']['formats'][$text_format_id]['editorSettings']['customConfig'] = base_path() . drupal_get_path('module', 'mymodule') . '/ckeditor_config.js';
    }
  }
}

```

to include a configuration a file called ckeditor\_config.js that contains the code:

```
CKEDITOR.on('instanceReady', function(ev) {
    // Sets indentation of source code
    ev.editor.dataProcessor.writer.setRules( 'div', {
                indent: true,
                breakBeforeOpen: true,
                breakAfterOpen: true,
                breakBeforeClose: true,
                breakAfterClose: true
            });
});

```

Doing this, CKEditor will keep the indentations in the source code, and a well formatted code easy to read.

# Answer
> 0 votes
Let's assume you're using CKeditor in your body field.

Ideally, you shouldn't be adding classes/wrappers in CKeditor. You should use the node template file of your content type and add them there.

Go to your theme's template folder and create a copy of **node.html.twig** and rename the copy to **node--\[content-type-name\].html.twig**. Ex: node--article.html.twig, if it's the article content type.

Inside this twig file, find where it says `{{ content }}` and delete that. Instead, you put `<div class="row"><div class="col-md-12">{{ content.body }}</div></div>`

and print other fields `{{ content.field_name }}` that you need.

Clear/Flush the cache to see changes.

---
Tags: 8, wysiwyg
---


# Question
Title: Custom submit handler on form loaded via entity.form_builder
Using Drupal 8.5.3. Currently working within a custom controller to load and alter a form for menu links. To load the form I am using the following:

```
// Load the menu link field.
  $menu_link_content = MenuLinkContent::create([
    'title' => 'Example link',
    'link' => ['uri' => 'internal:/node'],
    'menu_name' => 'main',
  ]);

  $form = \Drupal::service('entity.form_builder')->getForm($menu_link_content, 'default', $form_state_params);

```

Simple enough right? From there I go onwards to alter $form inside the same method in the controller. I can change the $form values from there to adjust which menu items are available.

**The problem is that I can't seem to add a submit handler.**

I've tried both of these to add a submit handler, to no avail.

```
$form['#submit'][] = 'group_content_submenu_group_link_add_submit';
$form['actions']['submit']['#submit'][] = 'group_content_submenu_group_link_add_submit';

```

Any ideas on what I could be missing? I'm open to other approaches as well, but I specifically need to be able to set the parent item that this form should be using to present available parent menu link choices.

# Answer
As per a comment from another user, the form is already processed after being returned by the form builder. That said, you can still alter values, but not add form elements or alter actions.

The solution for me was to do a form alter on the form before hand, and give it a submission handler, along with a hidden field. Then when I get the form in the code above, I now set the hidden field to contain a relevant value (Group ID). In my submission handler, I only proceed if that hidden value != NULL. This prevents me from doing anything on the core entity form which I do not want to affect.

Thanks for the hint 4k4!
> 1 votes

---
Tags: forms, navigation
---


# Question
Title: Best way to integrate "customization" to the front page
**#First question**

We are making a Drupal 7 theme for one of our customers. The company wants to be able to edit the frontpage easily, without any coding skills.

Atm we got this:

**Image 1**

**Image 2**

But this is totally not user friendly. We made a block, and put block content in it, for this one it was just html. But what we want is more like a wordpress "customizer" or something?

*Maybe this is something that is totally basic in Drupal 7 but we just missed it?*

**#Second Question**

The people (Employes of our client) that will manage the website when launched. Will they have to work in de basic Drupal 7 dashboard, or is there a way to make your own dashboard in the style of your website?

# Answer
> 0 votes
As a possible starting point, you might use the Panels and Panelizer modules.

When you define a custom CTools page (using the Page Manager module included with the CTools module), you can define its layout and content.

Concerning your second question, it is also possible to edit the page without moving to the administrative interface, by using the IPE (In Place Editor) provided by Panels.

You should be able to find many tutorials about Panels, in drupal.org too: https://www.drupal.org/node/1857644

# Answer
> 0 votes
I think there is no out of the box solution like you want to have on drupal7.

the question is what they want to customize.

Only the text and Images? Just Install an Html editor and use Panels.

If you have some fancy Sliders or things like this I would use "paragraphs" but its alot work cause you have to write the templates for every element.

Or you just keep it userunfriendy and hope they pay you for changing the content:)

# Answer
> 0 votes
I agree with kerim, it would help to have a scope of what the client needs to be able to customize.

Drupal does offer a lot of themes and modules that have "customizable UIs" built into them, but I personally feel they all still assume a great deal of skill and can put you in a position to offer endless support.

My suggestion is scope out what they want to customize, and build those items into custom content types. Then just assign the regions to different blocks throughout the page, i.e. "header photos," "sidebar links," "main content" - then they can fill one form, and it will dynamically flesh out the site for them.

I used this approach for a major real estate company to build property templates - they completed one node form, and it snaps everything right into place. It may not work exactly how you want, but it may set you in the right direction.

Personally I would advise you against exposing blocks to your client directly - they're difficult to parse off with permissions and assume a lot of base knowledge.

---

For your second question, there are plenty of ways to provide multiple themes throughout your site - you can even set your client's UI pages to a custom URL path, and then use something like https://www.drupal.org/project/page\_theme to set a theme to only those pages, i.e. site.com/client/front-page, site.com/client/editor, etc

Best of luck!

---
Tags: 7, views, theming, nodes, blocks
---


title: Session API Security Advisory

text:
# Question
Title: Session API Security Advisory
I'm working on a website that is interested in adding chat features. I did some research, and ended up installing the DrupalChat module, and its dependencies. After configuring the module, I realized it would not work for anonymous users unless I also installed the Session API module.

My concern is that on the Session API module information page, it displays a banner stating that

> This project is not covered by Drupal’s security advisory policy.

I have not run into this issue before, so I'm not sure how leery I should be to use the Session API module?

Does this mean it's likely to receive a future update to address pending security issues? Should I use some other method of adding chat to the web site? If so, any recommendations?

# Answer
Basically all this means is that the module maintainers haven't opted into Security Advisory Coverage yet. Seems they haven't even opened an application in the review queue.

I asked them to do so in a new issue. As also Acquia does not recommend implementing modules not covered under the Security Advisory Policy (article). Pantheon takes that as a red flag (article), too.

But I wouldn't be worried too much. Just remember to always update this module first. But yeah, I'm not a security expert :)
> 1 votes

# Answer
The Drupal Security Advisory is a program of the Drupal community (Drupal Security Team) that is dedicated to review reported security flaws, contributed code, and to manage fixing identified security issues and releasing scheduled security updates (in the case of contributed modules together with its maintainers).

For contributed modules, opting into security advisory means, that stable releases of the module may be reviewed for obvious security flaws by the security team. (Note, only stable releases are covered by security advisory, not development versions, or alpha/beta/rc pre-release versions.) Also, available security updates/fixes will be announced within the Security announcements that conveniently are available as RSS feeds and can be subscribed to on Twitter.

New module maintainers can optionally opt-in their module(s) to that program, after they have proven a basic understanding of Drupal Coding Standards and best practices by applying with one of their modules within the Security Advisory Applications queue. The process can sometimes take several months to complete, as it is based on voluntarily conducted reviews by the Drupal developer community and a final approval by a dedicated team of Drupal webmasters that have to take that time for reviewing the source code as well.

A module that still has the banner stating there is no security advisory coverage means that the maintainers are new to the Drupal eco system and therefore do not automatically have the right to opt in as they did not undergo the above mentioned review. (Or they just did not opt into security advisory because there is no stable release of their module yet, or they just forgot about it.)

Now to the security concerns:

A module without security advisory coverage is not automatically bad or has security issues. It may receive bug fixes and further features by its maintainers and/or contributions (patches) from the Drupal community, as all other modules on drupal.org do.

Good indicators always are the module's usage statistics, the activity within its issue queue, and the maintenance status stated on the module page.

A module with high usage is likely to not having many (unidentified) bugs or other issues left. With modules having a low usage (that exist for very special use cases), I'd always go for manual own code reviews to check the code quality and what the module actually does.

As security updates will not be announced within the security announcements, you will want to shortlist/follow the issue queues of any such modules you use within your projects, in order to keep a close eye on important issues/fixes coming up.
> 0 votes

---
Tags: security
---


title: How to Logout user with Basic auth?

text:
# Question
Title: How to Logout user with Basic auth?
I can log in, perfectly fine, but can't get logout to give me a JSON response. Currently, I can only do POST to

```
d8.com/user/logout?csrf_token=123&?_format=json

```

and that would log out, even though the token 123 is not the same as the given csrf-token at login or the logout token. This doesn't work without the token query, even though cookie/session isn't enabled anywhere

> ("message": "'csrf\_token' URL query argument is missing.").

The logout happens when hitting a 403 forbidden on that URL.

Other info: csrf\_token=123 is the actual query, doesn't need to be csrf-token or the log out token is given at login Version: 8.5.3 The only basic\_auth turned ON, at all endpoints.

# Answer
The mistake is in the url parameters, it should be :

```
d8.com/user/logout?token=123

```

The *\_format* is not needed for logout. I found the parameter name for the token on this page https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Access%21CsrfAccessCheck.php/function/CsrfAccessCheck%3A%3Aaccess/8.3.x
> 0 votes

---
Tags: 8, authentication-authorization
---


title: After submit form open a view

text:
# Question
Title: After submit form open a view
I am using the custom module to create a block wich contains a form. I added this form in a node of a custom content type. When I click to submit, I want to open a view wich contains another form and I will create it in the same module.

this is my code

```
function my_module_block_info() {
$blocks['visit'] = array(
    'info' => t('Visit'),
    'cache' => DRUPAL_CACHE_GLOBAL
);
return $blocks;
}
function my_module_block_view($delta = '') {
$block = array();
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
    $nid = arg(1);
}
switch ($delta) {
    case 'visit':
        $block['content'] = drupal_get_form('visit_project', $nid);
        break;
}
return $block;
}
function visit_project($form, &$form_state, $nid) {
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
);
$form['actions'] = array('#type' => 'actions');
$form['actions'] = array(
    '#type' => 'submit',
    '#value' => t('Visit'),
    '#attributes' => array('class' => array('general_button')),
    '#submit' => array('_visit_project_details')
);
return $form;
}
function my_module_menu() {
$items['my-page'] = array(
    'title' => 'Title of my page',
    'page callback' => 'project_details',
    'access callback' => TRUE,
);
return $items;
}
function _visit_project_details($form_state)
{
   $form_state['redirect'] = 'my-page';
}
function project_details() {
    return '<p>ok in details of '.$_POST['id'].'</p>';
}

```

Can you help to go to **my-page** after submit form and still reading the $\_POST?

Thank you

# Answer
Below code is redirecting to my-page

```
<?php

function my_module_block_info() {
$blocks['visit'] = array(
    'info' => t('Visit'),
    'cache' => DRUPAL_CACHE_GLOBAL
);
return $blocks;
}
function my_module_block_view($delta = '') {
$block = array();
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
    $nid = arg(1);
}
switch ($delta) {
    case 'visit':
        $block['content'] = drupal_get_form('visit_project', $nid);
        break;
}
return $block;
}
function visit_project($form, &$form_state, $nid) {
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
);
$form['actions'] = array('#type' => 'actions');
$form['actions'] = array(
    '#type' => 'submit',
    '#value' => t('Visit'),
    '#attributes' => array('class' => array('general_button')),
    //'#submit' => array('_visit_project_details')
    '#submit' => $form['actions']['submit']['#submit'],
);
$form['actions']['#submit'][] = '_visit_project_details';
return $form;
}

function my_module_menu() {
$items['my-page'] = array(
    'title' => 'Title of my page',
    'page callback' => 'project_details',
    'access callback' => TRUE,
);
return $items;
}
function _visit_project_details($form, $form_state)
{
   //$form_state['redirect'] = 'my-page';
   drupal_goto('my-page');
}
function project_details() {
    return '<p>ok in details of '.$_POST['id'].'</p>';
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Using theme hook, how do I get block contents into the $comm line?
```
if ( isset($vars['content']['#block_content']) ) { // check for custom content
    if ($vars['content']['#block_content']->type[0]->getValue()['target_id'] == 'js_file_block') { // only run on js_file_block types
      $storage = \Drupal::entityTypeManager()->getStorage('block-content');
      $comm = current($storage->loadByProperties(['type' => 'block']));
      $route_match = \Drupal::routeMatch();
      $vars['inlinejs2'] = array();
      if ($comm !== false) {
        foreach ($comm->get('field_js_url') as $script_block) {
          $vars['inlinejs2'][] = $script_block->value;
        }
      }
    }
  }

```

I dont know what I am doing wrong, but it will not make the array.

# Answer
> 0 votes
If you try to access the entity in a template preprocess hook, there is a much simpler way:

```
function MYTHEME_preprocess_block(array &$variables) {
  // check for custom content block
  if ($variables['base_plugin_id'] == 'block_content') {
    // the entity is alreary availale in the preprocess hook, no need for another query
    $blockContentEntity = $variables['elements']['content']['#block_content'];
    // my advice: pass the entire entity to the template, so you can access all the block fields
    // in Twig without further preprocessing, similar to node templates, e.g.
    // {{ block_content.field_whatever.0.value }}
    $vars['block_content'] = $blockContentEntity;
    // further processsing only for custom content blocks of type 'js_file_block'
    if ($blockContentEntity && $blockContentEntity->bundle() == 'js_file_block') {
        //...whatever you need in here...
    }
  }
}

```

# Answer
> 0 votes
THis code works for me.

```
function MYTHEME_preprocess_block(&$variables) {
    if ($content['#block_content']->bundle() == 'megamenu_image_video_block') {
      if(isset($content['#block_content']->get('field_select_campaign')->target_id) && !empty($content['#block_content']->get('field_select_campaign')->target_id)) {
        $selectedCampaign = node_load($content['#block_content']->get('field_select_campaign')->target_id);
        $variables['headerMegamenuCampaignTitle'] = $selectedCampaign->get('title')->value;
      }
    }
}

```

---
Tags: blocks, hooks
---


# Question
Title: How to solve my Field mapping problem during import of Registration codes?
I'm using the RegCode Module and I need to have 64 different registration codes and I want each of them to be used an infinite number of times. So the only solution is to import them.

I created an Excel spreadsheet with two columns:

* "code", which contains the 64 codes.
* "maxuses", which contains "999999".

I exported it as a CSV file but when I try to import it, I get this message:

> File successfully saved
>
> Successfully inserted 0 rows out of 64
>
> Warning: array\_combine(): Both parameters should have an equal number of elements in regcode\_ie\_admin\_import\_submit() (line 167 of /sites/all/modules/regcode/regcode\_ie/regcode\_ie.module).

Am I doing something wrong ?

# Answer
> 0 votes
## Preparing your cvs file

First remove all the column names from the first row, otherwise they will be added and will throw an error, as they won’t be in the correct format.

## Drupal Regcode import tab

You can map to the following six fields:

* begins: When code should be active from in date format
* expires: When code should expire in date format
* code: The registration code text format (for numbers and letters) and should be unique
* is\_active: Whether the code is active text format ‘Yes’ or ‘No’ Default is Yes
* maxuses: Maximum times the code can be used number format default is 1
* uses: Number of times the code has been used number format default is 0

If your cvs file codes are in the first i.e column one (A) then you would map it as code and if the next column is maximum times the code can be used then you would map as code, maxuses separated by a comma. Note: no colons.

---
Tags: 7
---


title: Hide user's blog link on blog entries

text:
# Question
Title: Hide user's blog link on blog entries
I want to hide the *user's blog* link that appears on blog entries e.g *Anonymous's blog*

How can I do this in *node--blog.tpl.php*?

I tried `hide($content['author']);` but that doesn't seem to work.

# Answer
Try following code in your template.php file.

```
<?php
function phptemplate_links($links, $attributes = array()) {
    unset($links['blog_usernames_blog']);
    return theme_links($links, $attributes);
}
?>

```

To get the more information about all the links use following code:

```
<?php
function phptemplate_links($links, $attributes = array()) {
    print_r($links);
    return "Hello World";
}
?>

```
> 1 votes

# Answer
In your node--blog.tpl.php add `unset ($content['links']['blog']['#links']);` instead of `hide($content['author']);`
> 4 votes

# Answer
For remove user blog link you have to just comment or remove bellow line from your node--blog.tpl.php

``<?php print render($content['links']); ?>``

remove above line from your tpl file its remove user blog link perfectly
> 1 votes

# Answer
If you want to remove the link you can try this. Taken from here:

```
function your_module_user_view_alter(&$build, $account, $display) {
  unset($build['summary']['blog']);
}

```
> 0 votes

# Answer
First create a node tpl file for your blog content (reference: https://drupal.stackexchange.com/a/42653/1254). Then inside that file, you can use the below code:

```
unset ($content['links']['blog']['#links']); // Unset the blog links
print render($content['links']); // Print the links

```
> 0 votes

---
Tags: 7, nodes
---


title: blocking access to admin content view

text:
# Question
Title: blocking access to admin content view
When blocking access for a editor role to the view admin/content, all sub-items of the toolbar content item are not visible to this role. How to solve this ?

# Answer
> 1 votes
You can add a new menu link to act as the parent of all the items, a menu link that the users will have access to, then move the Content sub items underneath it. Or you could just move them out from underneath the Content menu item, but that'll probably make a messy toolbar. The toolbar just shows part of the Administration menu, all items under the Administration menu link.

---
Tags: views, 8
---


# Question
Title: Get all available permission after NodeType delete - Drupal 8
I know that to get all available permissions you can do

```
var_dump(array_keys(\Drupal::service('user.permissions')->getPermissions()));

```

which give you a list of all permissions' name.

I also know that when you create a NodeType, it refresh this list.

So what I want to do here, is to fill a table of my database with a list of all available permissions, that update when permission is add or removed.

When I create a NodeType :

```
function inside_entity_insert(\Drupal\Core\Entity\EntityInterface $entity) : void
{
    if (get_class($entity) === 'Drupal\node\Entity\NodeType') {
        $permissions = array_keys(\Drupal::service('user.permissions')->getPermissions());

        foreach ($permissions as $permission) {
        // somestuff -> updating database permission table
        }
     }
}

```

So that means when NodeType is created the Drupal permissions list is updated and I must update my database too.

What I want to do here is the same thing but when a NodeType is deleted.

I tried :

1. hook\_entity\_delete
2. hook\_entity\_predelete

But in both hook the ***user.permission*** list didn't change, I still get the same permissions, and what I though is that the permissions of my actual nodetype dissapeared, because of the deletion.

I do not know where to look..

Is getting the name of the nodeType and delete matchings rules' name of the database, a good alternative ?

I also wanted where can I initialize these database, because actually it's created & updated only when someone create a NodeType. But that's not urgent at the moment.

Thanks to all

# Answer
You are using the wrong hooks. I am not sure what your objective is, but you want `hook_ENTITY_BUNDLE_delete` I believe:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_entity\_bundle\_delete/8.6.x

```
function mymodule_entity_bundle_delete($entity_type_id, $entity) : void
{
    if ($entity_type_id == 'node' && $bundle == 'node type to check') {
        $permissions = array_keys(\Drupal::service('user.permissions')->getPermissions());

        foreach ($permissions as $permission) {
        // somestuff -> updating database permission table
        }
     }
}

```

I don't know if you care to check `$bundle` or not, but if you delete any node type, this code should fire.
> 0 votes

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


# Question
Title: Simplenews + Mime Mail + SMTP = occasional blank email
I have a client site that uses the Simplenews module with the Mime Mail and SMTP Authentication modules. The subscriber list has a little over 300 email addresses, and when newsletters go out the cron sends out batches of 100 messages per hour. Things usually go off without a hitch, but with the last newsletter one of the batches sent contained blank messages. I have been unable to reproduce the problem. Someone else reported the same problem here:

https://www.drupal.org/node/2378147

. . . but has of yet there has been no response, and I'm not convinced the problem lies with the Simplenews module itself. Has anyone else seen anything like this problem?

# Answer
> 0 votes
First step. Have you combed your logs in Drupal for errors? And have your also looked at your web server PHP error logs?

With this random problem you are having I would expect to see something going on in the logs.

I have never used the Simplenews module or reviewed it's code so I cannot say how well the authors of the module addressed error handling the module.

Clearly you have a problem and it's been reported by other people. If you find no error in the logs then I would say that potentially the module does not have enough error handling written into it to diagnose the problem.

For what it's worth (purely for your own information), I will say that attempting to do an email newsletter from a a web server is not the preferred method. An email service provider should be used for that functionality if you have any concern for deliver-ability of your newsletter.

# Answer
> 0 votes
@JOakland just switch cron to be called only from special URL, not at any URL call I killed 5 days investigating "empty emails" trouble - crap begins observed in theme\_render\_template($template\_file, $variables) at include point

---
Tags: emails
---


# Question
Title: How to combine multiple view result sets, limiting the combined result set
I want to create a 'suggested content' display that, by default, displays 4 nodes that share terms on a term reference field belonging to the currently node. So, if the current node is tagged with "baking" and "family", it should display nodes that have those terms in common. I have this working — all is good here.

Also, on the reference node I've added an entity reference field that allows editors to curate their own suggested content. My intention is to put this curated content at the beginning of the suggested results, so that if an editor specifies 2 nodes, the other view will populate the other 2 nodes.

Basically, what I think I need to do (correct me if I'm wrong), is to combine the results from two views (one displaying the curated nodes, the other displaying the term-related nodes), and limit them to the top 4 entries, ensuring that the curated nodes are displayed first.

If this was confusing, this image should make it clearer;

How can I combine the results from two views and limit the combined result set? Also, note that each view only uses a single field for each row (a rendered node).

# Answer
Here's what I ended up doing (not using views). I'm using Panels on this site, and my default view for this content-type is controlled via Panelizer. Since I couldn't find a way to do this with Views, I created a custom panels pane (code below).

Basically, this pane accepts one setting: the number of related events to display. The render callback counts the editor-defined related nodes, and grabs more (if needed) based on shared terms.

```
<?php

$plugin = array(
'single' => TRUE,
'title' => t('Suggested Events'),
'description' => t('Combines curated suggested events with those related by category.'),
'category' => t('Custom Panes'),
'edit form' => 'MYMODULE_suggested_events_edit_form',
'render callback' => 'MYMODULE_suggested_events_render',
'admin info' => 'MYMODULE_suggested_events_info',
'defaults' => array(
  'events_to_show' => 4
),
'all contexts' => TRUE,
);

/**
 * Edit Form.
 */
function MYMODULE_suggested_events_edit_form($form, &$form_state) {
$conf = $form_state['conf'];

$form['events_to_show'] = array(
  '#title' => t('Number of events to show'),
  '#description' => t('Used to control the number of suggested events shown. Defaults to 4.'),
  '#type' => 'select',
  '#options' => drupal_map_assoc(range(3, 6)),
  '#default_value' => $conf['events_to_show'],
  '#required' => TRUE,
);

return $form;
}

/**
 * Submit callback for settings form.
 */
function MYMODULE_suggested_events_edit_form_submit($form, &$form_state) {

foreach (array_keys($form_state['plugin']['defaults']) as $key) {
  if (isset($form_state['values'][$key])) {
    $form_state['conf'][$key] = $form_state['values'][$key];
  }
}
}

/**
 * Run-time rendering of the content
 */
function MYMODULE_suggested_events_render($subtype, $conf, $args, $contexts) {

  if (isset($contexts['panelizer'])) {
    $nid = $contexts['panelizer']->data->nid;
  } else {
    return false;
  }

  // Grab the Category Term IDs from referenced node.
  $node = node_load($nid);
  $categoryField = field_get_items('node', $node, 'field_category');
  $categoryTIDs = array_column($categoryField, 'tid');

  // suggestedEvents are the events which are selected by the editor.
  $suggestedEventsField = field_get_items('node', $node, 'field_event_suggested');

  if (empty($suggestedEventsField)) {
    $suggestedEvents = array();
  } else {
    $suggestedEventsNIDs = array_column($suggestedEventsField, 'target_id');
    $suggestedEvents = entity_load('node', $suggestedEventsNIDs ); // @returns array of entities
  }

  // determine how many events we need to find
  // based upon the total to display and how many are site-editor-defined
  $relatedEvents = array();
  $relatedEventsCount = 0;
  if (count($suggestedEvents) < $conf['events_to_show']) {
    $relatedEventsCount = $conf['events_to_show'] - count($suggestedEvents);
  }

  if ($relatedEventsCount > 0) {
    // Query for other events that share the referenced categories.
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'event')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->propertyCondition('nid', $nid, '<>')
      ->fieldCondition('field_category', 'tid', $categoryTIDs, 'IN')
      ->fieldCondition('field_datetime', 'value', date('Y-m-d').'00:00:00', '>=', 0)
      ->range(0, $relatedEventsCount)
      // Run the query as user 1.
      ->addMetaData('account', user_load(1));

    $result = $query->execute();
    if (isset($result['node'])) {
      $relatedEventsNIDs = array_keys($result['node']);
      $relatedEvents = entity_load('node', $relatedEventsNIDs);
    }
  }

  $events = array_merge($suggestedEvents, $relatedEvents);

  $block = new stdClass();
  $block->title = 'You may also enjoy...';
  $block->content = '';
  if (!empty($events)) {
    $block->content .= '<div class="block__content">';
    $eventsRenderArray = entity_view('node', $events, 'showcase_card');
    $block->content .= render( $eventsRenderArray );
    $block->content .= '</div>';

    return $block;
  } else {
    return false;
  }

}

/**
 * Admin info.
 */
function MYMODULE_suggested_events_info($subtype, $conf, $contexts) {
if (!empty($conf)) {
  $block = new stdClass;
  $block->title = $conf['override_title'] ? $conf['override_title_text'] : '';
  $block->content = t('Show @events_to_show suggested events.', array(
    '@events_to_show' => $conf['events_to_show']
  ));

  return $block;
}
}

```
> 0 votes

---
Tags: 7, views
---


title: How to get Node Url in RSS view?

text:
# Question
Title: How to get Node Url in RSS view?
We are using the default RSS feed view found at `/admin/structure/views/view/frontpage`. We want to change the Show to be Fields so we can setup up which field should be used for the title, link, description, creator, and publication date.

When we attempt to add the node url field we cannot find it. How to add the absolute URL of the node?

We have tried searching for, but cannot find it:

1. Content: Path
2. Node URL

# Answer
> 0 votes
It's called `Link to Content`.

Path field could also be used in older 8 versions (you could construct the full URL with replacement patterns while overwriting the field output).

But the Path field is deprecated in 8.5 and you can use **Link to Content** instead, with **Output the URL as text** option.

Read more here, you can also see screenshots: Path field deprecation and backwards compatibility for existing views.

There is still work being done related to this, and if you get the wrong link in 8.5.1 there is a patch that seems to help: RSS view with fields give wrong URL from path field.

---
Tags: views, 8, entities, feeds
---


# Question
Title: How to programmatically submit a form that has a file-field using drupal_form_submit()?
I'm working to allow the submission of an existing form via REST using the Services module and `drupal_form_submit()`. Though this is reasonably routine, the form in question takes a file-upload which is a required field.

To avoid embedding extra logic in the form itself to handle files differently under programmatic submission than under manual submission, is there a trick for getting Drupal to accept a file submitted "headlessly" via REST?

Most of this is not relevant to the answer, but for completeness, here's how I'm set up:

```
function mymodule_my_resource_create($data) {
    $form_state = array();
    $form_state['values'] = $data + form_state_defaults();
    drupal_form_submit('mymodule_form',$form_state);

    $errors = form_get_errors();
    $status = '200 OK';
    if (!empty($errors)) {
        $status = '400 Bad Request - submission caused errors';
    }
    drupal_add_http_header('status',$status);

    return (object)array(
        'message' => $status,
        'errors' => $errors,
    );
}

function mymodule_form($form,&$form_state) {
    return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#title' => 'Spreadsheet file',
            // '#required' => 1,
            // ^ there have been issues with this since 4.x...
            // https://www.drupal.org/node/59750
            // so this is done manually in the '#validate' function
        ),
        'reason' => array(
            '#type' => 'textfield',
            '#title' => 'Why file is being submitted',
            '#required' => 1,
        ),
        'submit' => array(
            '#value' => 'Submit',
            '#type' => 'submit',
            '#validate' => array('mymodule_form_validate_upload'),
        ),
    );
}

function mymodule_form_validate_upload($form,&$form_state) {
    if (!isset($_FILES['files']['name'] || !isset($_FILES['files']['name']['spreadsheet'])) {
        form_set_error('spreadsheet','File must be provided');
    }
}

function mymodule_services_resources() {
    return array(
        'my_resource' => array(
            'create' => array(
                'callback' => 'mymodule_my_resource_create'
                'args' => array(
                    'name' => 'post_data',
                    'type' => 'struct',
                    'description' => "Should match contents of $form_state['values'] when submitting through the UI.",
                    'source' => 'data',
                    'optional' => FALSE,
                ),
            ),
        ),
    );
}

function mymodule_actools_plugin_api($owner,$api) {
    if ($owner=='services' && $api=='services') {
        return array(
            'version' => 3,
            'file' => 'mymodule_services.inc',
            'path' => drupal_get_path('module','wos2'),
        );
    }
}

function mymodule_default_services_endpoint() {
    $endpoint = new stdClass();
    $endpoint->disabled = FALSE;
    $endpoint->api_version = 3;
    $endpoint->name = 'my_rest';
    $endpoint->server = 'rest_server';
    $endpoint->path = 'my_rest';
    $endpoint->authentication = array();
    $endpoint->server_settings = array();
    $endpoint->resources = array(
        'my_resource' => array(
            'operations' => array(
                'create' => array(
                    'enabled' => '1',
                ),
            ),
        ),
    );
    $endpoint->debug = 0;
    return array($endpoint);
}

```

# Answer
> 0 votes
This wasn't as hard as I expected; Drupal has different handling for fields with `'#type' => 'file'` as opposed to other types. There are two ways of solving the problem. One is simply adjusting the request-payload, expressed here as a `curl` command:

```
curl -i \
    'https://example.com/drupal/my_rest/my_resource' \
    -H 'Accept: application/json' \
    -H 'Content-Type: multipart/form-data' \
    -F "files[spreadsheet]=@my_spreadsheet.xlsx" # note the weird field-name
# This automatically uses the POST method, so Drupal reads it as a 'create'

```

Drupal munges file-field-names by default apparently apparently to match the file.inc code. This is stated expressly in comments:

```
if (!isset($element['#name'])) {
    $name = array_shift($element['#parents']);
    $element['#name'] = $name;
    if ($element['#type'] == 'file') {
        // To make it easier to handle $_FILES in file.inc, we place all
        // file fields in the 'files' array. Also, we do not support
        // nested file names.
        $element['#name'] = 'files[' . $element['#name'] . ']';
    }

```

If you want to API-endpoint users from the implementation shown above, the other solution is to *explicitly provide a `'#name'` value* for the file-field in question, as should be obvious:

```
return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#name' => 'spreadsheet_file', // <-- adding this prevents name-munging
            '#title' => 'Spreadsheet file',
            // ...

```

Note of course that the above might have consequences for other sections of code if the file used to be expected under the old name.

---
Tags: services
---


# Question
Title: How to use preprocess function for custom templates defined in hook_theme?
I have a custom module that i've created and I have set the theme template like this:

```
/**
 * Implemtnation of hook_theme()
 */
function custom_slider_theme($existing, $type, $theme, $path) {
    return array(
        'custom_slider' => array(
            'variables' => array('nodes' => NULL),
            'template' => 'custom_slider',
        ),
    );
}

```

This is all working fine.

What I can't find is how to load a css file for that template so when `custom_slider.tpl.php` is loaded the relevent css file is loaded. I don't need that css loaded on every page. I would rather call `drupal_add_css()` only when it's needed.

I used below approach, but it's not working.

```
function ModuleName_preprocess_TemplateName(&$vars) {
      drupal_add_css(drupal_get_path('module', 'custom_slider') . '/file.css');
    }

```

Also I added

```
'preprocess functions' =>array('ModuleName_preprocess_TemplateName'),

```

in hook\_theme, where I defined my templates, kindly suggest the right way to do it.

Any help with this is very much appreciated.

# Answer
> 3 votes
Drupal will automatically call `hook_preprocess_[template]` for each template defined in `hook_theme`.

e.g:

```
MODULE_preprocess_custom_slider(&$variables){}

```

Should be called by default. If not, then clear your cache to be sure the preprocess function is registered.

Fun fact is preprocess functions are called for theme functions as well, e.g `theme_item_list` calls `hook_preprocess_item_list` prior to rendering.

# Answer
> 0 votes
```
function ModuleName_preprocess_TemplateName(&$vars) {
      drupal_add_css(drupal_get_path('module', 'custom_slider') . '/file.css');
    }

```

This function works perfectly, just ensure that the css file is in the same folder as the .tpl.php and .module files

---
Tags: theming
---


# Question
Title: Can I use I18N or another module to house regional variations of a site in a single installation?
I have a large build coming up and am planning to attack it in Drupal 8.

The client will have three regional variations of their site, a .com, a .co.uk, and a .es. The goal is for them to look like one site. The sitemap will be 98% symmetrical between the three sites, only a handful of pages may exist in one menu and not in another. The .es will be in spanish, the .co.uk will be in UK English, .com in US English.

Is there any better way to approach the three sites that would make it easier to manage? For instance, using I18N? Having translations of each region is not a requirement, and almost every page will be shared between all three, with language variations (in .co.uk probably changes for SEO sake so we don't look like duplicate content).

Thank you for any input!

# Answer
> 1 votes
Af far as building and configuring such a project relying on Drupal multilingual features is a no-brainer, you should definitely go that way. Entering content in different languages has to be done either way, but with the multilingual setup, you don't have to repeat the work you do around the structure.

There probably is a very small number of special cases where not using multi-lingual features would be faster. Cases where you build one site, polish it, then just clone and do tiny adjustments for the other two languages. But the reality of web projects doesn't make it very probable that your project specs and necessary ongoing work will be so clearly defined to justify avoiding the multilingual setup.

`Detection and Selection` of `Languages` will allow you to choose `URL` as the detection method, and further in that configuration, you choose `Domain` (instead of the `Path prefix`) as the `Part of the URL that determines language`.

You'll have to do some planning around the menus, which ones you can share and translate, and whether you'll need to create some language-specific menus.

You'll be able to have language-specific paths, dates, other configuration... I found multilingual projects always take a lot more time to build than it seems, so don't underestimate it. It's not simply entering all the translated expressions into some interface and you're done. You have to learn about different places where to setup the structure for different languages etc. But in the end, it is faster to setup and maintain one site with multilingual features and translate it, than it is to build and maintain 3 separate ones.

Definitely learn about Hreflang for multilingual SEO, there's a link to Google support page explaining it there.

---
Tags: i18n-l10n
---


title: Clustered Google Map

text:
# Question
Title: Clustered Google Map
I'm new in drupal(2 days), never used it before. I have taken over this site knowing nothing about it and right away got new assigment to create clustered looking map and markers should be put from already data in drupal site. So there is a page on the site https://esc.gsfc.nasa.gov/view-all-saves that shows all information needed to place markers on the map. How do I connect to that table, loop through records to call google API to place markers. Do I have to create my own php file and put inside the root? I looked in database and couldn't find any tables that stores that data.

# Answer
> 0 votes
The best way (the Drupal way) is to build on top of available Drupal features, rather than creating a custom solution that may do the narrow task at hand, but bypasses a lot of the built-in structure that carries a lot of value when using Drupal.

Views module is used to build the page you linked to, and Views is also the best module to use to list the geo-data to be displayed on a map.

Each node from that table has Longitude and Latitude coordinates (visible when you visit a node page, not directly in the table). These coordinates fields can be used to feed a Views map display.

You'll need to install a module that provides a special Views Format that renders a map. Then add that Display type to the same Views where the page you linked is built. Adjust the fields (override) to provide for the map display.

Are your Longitude/Latitude fields from Geolocation Field? Check under Structure \> Content types \> SAR Saves \> Manage fields. Also check under Extend which geo-modules you have available.

With Geolocation Field you already have everything you need, you just need to configure a new map display in Views configuration, no coding required ;)

---
Tags: google-maps
---


title: Conditionally display a field

text:
# Question
Title: Conditionally display a field
On my "teaser" view mode I want to display my Image field but if the Image field is empty I want to display my Title field instead.

I have tried using hook\_preprocess\_node but it appears that this is not called when rendering the node in the "teaser" display mode when using Display Suite.

Another thought I had was to create a custom DsField plugin... but in that case I do not have the context of the other fields (unless I do?) so I cannot say "if img is empty display title, else display img" Using the suggestion below I came up with:

```
class ImageElseTitle extends DsFieldBase {

  public function build() {
    /** @var /Drupal/node/Entity/node $node */
    $node = $this->entity();

    if ($node->get('field_event_image')->isEmpty()) {
      return $node->get('title')->view('teaser');
    }
    else {
      return $node->get('field_event_image')->view('teaser');
    }
  }

}

```

But in this case the settings for the title field are not obeyed. For example, it is wrapped in a span instead of an h2 as specified in the display settings. Similarly it is not a link even though "link" is checked in the display settings...

I tried adding a preprocess to the title field that checks if the image field is empty, but I think the preprocess function is too late to say "the image field is not empty, so never mind, dont display the title"

Thoughts?

-- Continued --

I also tried this, but the fields are not hidden as I'd expect them to be:

```
function mymodule_ds_pre_render_alter(&$layout_render_array, $context, &$vars) {
  if ($context['entity_type'] == 'node' && $context['bundle'] == 'event' && $context['view_mode'] == 'teaser') {
    if ($context['entity']->get('field_event_image')->isEmpty()) {
      $layout_render_array['field_event_image']['#access'] == FALSE;
    }
    else {
      $layout_render_array['node_title']['#access'] = FALSE;
      $layout_render_array['title']['#access'] = FALSE;
    }
  }
}

```

# Answer
I've done this a couple ways.

First, you can you hook\_ds\_pre\_render\_alter (I can't find a better link to ds.api.php!) like hook\_preprocess\_node and just hide your title field if the image field is set. If you're using this option be sure to dig into the layout render array to the correct spot. For example if you have the ds node\_title field within the ds\_content region, hide it like

```
$layout_render_array['ds_content']['node_title']['#access'] = FALSE;

```

of if you have the same field within a title\_wrapper field group, hide it like

```
$layout_render_array['ds_content']['group_title_wrapper']['node_title']['#access'] = FALSE;

```

Or you can create a custom ds field (yes, you have access to the whole entity). I usually enable the `hidden` region at `/admin/structure/ds/settings`, then I add both my title field and image field to the hidden region on my view mode and then just render whichever one I need in my ds field's `build()` method via the field's view method, in this case it would be like

```
$this->entity()->field_MY_IMAGE_FIELD->view('teaser');

```

or

```
$this->entity()->title->view('teaser');

```

Instead of passing a view mode's name, you can pass a display configuration array straight to the field's view method.
> 3 votes

---
Tags: 8, entities, display-suite
---


# Question
Title: How can I pass the filter parameters of one view to a different view on the same page?
# Summary

I have two seperate views on the same page - one Page and one Block that show two seperate content types respectively, but have a filter exposed for a field that they share.

On the page of the first view, I have attached a block display of the second into a new region. I want the filter values of the exposed filter of the first view to also feed into the filter values of the second block view, if possible.

# How it's currently set up

I have two views.

The first view, "Local branches", is a **Page display** that surfaces content of type *Local branch*. This content type has a **Location** field, powered by the **Location** module. On the view page, there is an exposed filter criteria:

**Location: Distance / Proximity**

which is exposed to the user as a text field and the origin in the filter settings set to **Postal Code**.

The code is then sorted by Distance / Proximity.

On the view page therefore, there is a text field where users can enter in a post code and it will return results closest to that Postal code.

---

The second view, "Shops", is a **Block display** that surfaces content of type "Shops". This content type is almost identical to the "Local branch" content type, in that it also has a Location field.

In this view, I have again an exposed filter:

**Location: Distance / Proximity**

that is set up the exact same way - but note that this is a Block display. It's again sorted by Distance / Proximity.

---

Finally, on the Page of the first view, "Local branches", I have placed the second view's Block, "Shops" in a seperate region.

My hope is that the Shops block will somehow pick up the exposed filter settings from the URL built by the "Local branches" view, which looks like this:

http://www.example.com/local-support?distance\[postal\_code\]=EN11+8RX&distance\[search\_distance\]=100&distance\[search\_units\]=mile

As you can see there are three parameters that power the exposed Postal code search form. Here's a crude diagram:

# Problem

The Block view, "Shops", doesn't respond to the filter values in the URL, but just outputs all results sorted arbitrarily (there is no other sort atm). *I would like it to respond with results as if it were using the exposed filter values from the "Local branches" view as its own exposed filter.*

# Potential solutions and queries

One thing I did try was to programatically create the "Shops" block, and render it on the view page `/local-support` and see if I could use the `$_GET` parameters and feed it directly in to the view. Code to generate the output looks something like this:

```
function _mymodule_shop_block_view() {
  $view = views_get_view('shops');
  $view->set_display("block_1");
  $view->set_arguments($args);
  $view->pre_execute();
  $view->execute();
  $content = $view->render();

  return $content;
}

```

The problem is I'm not sure what the value of `$args` would actually be in this case. I want to exectue and render the view, but pass the `$_GET` params in somehow, but they're exposed filter params so I don't know if `$view->set_arguments` is actually appropriate in this case?

---

My other thought that was because the "Shops" view is a Block display, the exposed filter won't work as it should. Could I try building it as a page display, expose it the Location filter as a block, and then rendering it in a block? I could hide the exposed filter in CSS (bad I know but if you haven't guessed by now I kinda wanna get this working).

---

Could attaching the block to the Page view integrate it - is it possible to do view attachements across separate views?

---

Thanks for taking the time to read this - I hope there's enough info about what I am trying to achieve!

# Answer
> 3 votes
Yes, it's possible to have 2 different views on the same page sharing the same exposed filter query parameters.

The trouble you're having is, by default, a block display doesn't show any exposed filters. The only way to enable this is by enabling the **Use AJAX** setting on the block view under the **Advanced** section in the admin UI. Once set, both the block & page Views will pick up on the same `location[postal_code]`/`location[distance]`/`location[search_units]` query parameters.

Of course this means, you'll have 2 different form filters on the same page but you can kludge your way around it with a style rule to hide it (e.g. `#block-views-my_block_machine_name-block div.view-filters { display: none; }`) or some other means of hiding the form.

# Answer
> 0 votes
This module works great for exactly this issue:

https://www.drupal.org/project/views\_contextual\_filter\_query

The exposed filter of one view (probably the page view) turns into a query parameter. Just use the key of the query parameter as contextual filter value under "provide default argument" \>\> "parameter name". Done and done.

---
Tags: 7, views, location
---


# Question
Title: List Drush specific add ons, plug ins, extensions, or modules to use drush dl in automated script
I'm writing a really basic bash script and want use drush dl to download the Drush extras add on.

`drush dl drush_extras`

But I need to check whether drush extras is installed before I try to install it (and then use it) because it prompts the following text.

> Install location C:\cygwin64\home\USER/.drush/drush\_extras already exists. Do you want to overwrite it? (y/n):

How do I determine whether a drush add on/plug in/module (not sure what you call it) exists? So I handle that use case?

I'm trying to automate configuration, starting with assigning blocks to regions, and I have to make it work on Windows (first) and Linux. So I'm using Cygwin and Drush on Windows. There's probably different approaches, but this seems OK.

# Answer
> 1 votes
I would personally lean towards simply installing with `-y`. Adding `-y` onto the command you've listed will return Y accepting the default on any prompt that comes up (like the one you mention).

`drush dl drush_extras -y`

If you still want to check if it’s installed, you can check if the directory exists,

```
if [ -e $HOME/.drush/drush_extras ]; then
  # some logic here
fi

```

This won’t help you if the directory is empty though.

Another option is checking the output of

```
drush someCommand -h

```

Where `someCommand` is a command provided by `drush_extras`. You can compare the output of a valid one to an invalid one. If they match, it’s not installed.

---
Tags: drush
---


title: Drupal 8 multi fields in one fields

text:
# Question
Title: Drupal 8 multi fields in one fields
can Someone explain how can i make one field in Drupal 8 that can contain multiple fields in it... I am not allowed to use Paragraph module. I want to make it full programmatically, By the way i know how to make simple field in Drupal 8 but don't know how to set schema or form form dynamic field that can have multiple fields in it. For Example when we want to add some field in user or in node, we go to ~/fields/add-field and then select the field type, after in the field setting i want to have one form element that says add filed and the type of the field. and after saving setting, i will generate the field widget and formater depending on the field type selection that i made before.

Is there a solution for this problem (only programmatically)?

# Answer
> 0 votes
If you prefer another approach, a little more clean and following the Drupal structure, you can use Inline Entity Form to do that.

I don't like Paragraphs and Field Collection for just one reason. They don't follow the way that Drupal storages data in DB. If you open your database and search for the tables that this modules create, you will be able to see some strange patterns.

https://www.drupal.org/project/inline\_entity\_form

# Answer
> 0 votes
Content Entity Builder module: https://www.drupal.org/project/content\_entity\_builder

Allow you add multiple base field to entity by config. it store all base fields in one table.

If you don't like the way : one field 2 tables. You can have a try with this module.

---
Tags: 8, entities
---


title: Can't load font woff

text:
# Question
Title: Can't load font woff
I have relatively simple issue but I can't fix it myself.

My log is full warning with same message:

```
page not found
http://mywebsite.com/sites/all/themes/bigwig/font/entypo-icon-font.woff

```

I have looked around and most of suggestion is about .htaccess and I tried to add such block (but no luck).

```
<FilesMatch "\.(ttf|otf|eot|woff)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

```

I have tried to access other files in folder via browser and everything worked except the one with \*.woff

```
http://mywebsite.com/sites/all/themes/bigwig/font/*

```

What else can I try?

# Answer
It seems somewhere you have something referencing that file. First place I’d look is on the theme folder.

If you have access to a Linux or Mac machine, you can `cd` into the folder and run,

```
grep -rn ‘entypo-icon-font.woff’ . 2>/dev/null

```

This will tell you if there’s a file that has a mention to that file.

To fix, you can either remove the reference to that file or see if you’re able to find the file and add it to the path on the url.
> 0 votes

---
Tags: debugging, .htaccess
---