# Question
Title: How do I invalidate cache of an embedded view?
I have a node type "Article" that contains a repeating Paragraphs field. One of the paragraph types let's the user embed a view using a entity reference field. When rendering an Article node containing a views reference I embed the selected view in `hook_preprocess_paragraph` like this:

```
$view_id = $paragraph->field_view->target_id;
$view = \Drupal\views\Views::getView($view_id);
$view->setDisplay('embed_1');
$vars['content'] = $view->preview();

```

This is working fine except when I enable caching. For example one of my views lists nodes of the type "Event". When I add a new Event it does not show up in the listing until I clean the cache. I could force clean the cache when inserting / updating / deleting an "Event" but I would much rather use Drupal 8's cache tag system and only invalidate the cached content that contains event lists. The problem is I cannot get it to work.

So far I have tried adding cache tags to the node, the view, and the paragraph in `hook_preprocess_paragraph` and `hook_preprocess_node` like this:

```
$vars['paragraph']->addCacheTags(['node_list']);
...
$view->storage->addCacheTags(['node_list']);
...
$vars['node']->addCacheTags(['node_list']);

```

According to this page `node_list` can be used for node listings to invalidate the cache whenever a node is updated. But it has no effect. Maybe the preprocess hooks are to late to add cache tags?

What am I missing?

**Edit:**

After some more testing I found that if I edit an event, the changes can be seen in the listing and if I remove an event it disappears from the listing. The problem only occurs when adding new events.

# Answer
Try to use `buildRenderable()`, that should ensure that the necessary cacheability metadata is added automatically.

```
$vars['content'] = $view->buildRenderable();

```

Hint: You might be interested in my Views Custom Cache Tag project. The node\_list cache tag is invalidated every time any type of node is saved, even though your view only changes when an event changes. Using that module and a bit of custom code as shown on the project page, you have fewer cache invalidations and better performance.
> 11 votes

# Answer
Add the cache tag to the render array, not the object:

```
$vars['#cache']['tags'][] = 'node_list';

```

In preprocess you are working with render arrays, not objects. Look at this page of the documentation: https://www.drupal.org/developing/api/8/render/arrays/cacheability
> 3 votes

# Answer
I solved a similar issue using the module Views Custom Cache Tag:

In the view editor, under Advanced, click on Cache, then select "Custom tag based". To have the view rerendered each time a node is changed, enter 'node\_list' in the custom tag settings.
> 0 votes

---
Tags: views, 8, caching
---


# Question
Title: Stop from going to node on content creation
I would like for when I add of piece of content for it to stay on the admin back-end.. right now it forwards the user to the created node with a message saying it's been created, but the rest of the admin interface disappears so it's difficult to get back to adding more, and certain content types look very strange in that view.

I looked at actions/triggers, but I don't see a way to distinguish between content types, and I wouldn't want comments and user posts to forward to the admin interface so I don't see that as a solution.

# Answer
The Add another module might come in handy for that:

> Add another is designed to save time during repetitive content creation. It allows the content creator to add another node of the same type much faster.

It provides a 'Save and add another' button in addition to the standard 'Save' button on node forms.
> 1 votes

# Answer
## The programming answer:

You can use hook\_form\_alter to alter redirect behavior.

Like so: (from linked thread)

```
<?php
function jeff_form_alter(&$form, &$form_state, $form_id)
{
     $form['#submit'][] = 'jeff_form_submit';
}

function jeff_form_submit($form, &$form_state)
{
     $form_state['redirect'] = 'process-your-donation';
}
?>

```

## The contrib module answer:

Clive's recommendation of Add Another (compatible with D6 and D7) is a good one if you simply want to add another of the same type of node upon content submission.
> 0 votes

# Answer
A possible solution to answer this question is to enable the Rules module, and create a custom rule that looks like so:

```
{ "rules_show_new_article_link" : {
    "LABEL" : "Show New Article link",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Click \u003Ca href=\u0022[site:url]node\/add\/article\u0022\u003Ethis link\u003C\/a\u003E to add another article ..." } }
    ]
  }
}

```

Some details about this rule:

* **Rules Events**: After saving new content.
* **Rules Condition**: Content is of type `article`.
* **Rules Action**: Show a message on the site, whereas the actual message content that will be shown is "Click this link to add another article ..." and with 'this link' being rendered as an hyperlink to relative path `node/add/article`.

If you have the Rules UI enabled, you can just import the above rule in your own site. Adapt content type `article` to `custom_content` (or whatever fits your needs).

With that, each time you edit or create a node of article, you'll get such message (with appropriate link) in the Drupal message area. Obviously, you could add any applicable rules logic to further improve this prototype (e.g. to only show this for selected user roles). And should you want to do so, you could also add an extra Rules Action to perform a redirect to relative path `node/add/article`.

PS: this rule is my favorite sample to get started with the Rules module.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Is it better for performance to disable unused default core views?
I'm seeing 5 views on my site that I'm not using and want to disable to keep things clean and performant, but I worry it could cause a problem somewhere down the road.

The views are:

* Frontpage (frontpage)
* Recent content (content\_recent)
* Taxonomy Term (taxonomy\_term)
* Who's New (who\_s\_new)
* Who's Online (who\_s\_online)

I have disabled these views and haven't seen any issues. I am not using any of them. Is core expecting these to be enabled? Does disabling these actually improve performance in any way?

# Answer
> 2 votes
> I am not using any of them. Is core expecting these to be enabled?

They are just examples and can be disabled if you don't need them.

The taxonomy term view is a bit different because that is the one that provides list of content when clicking on a term, if you disable that then those pages become practically meaningless as all they do is show the term with its fields.

> Does disabling these actually improve performance in any way?

Most likely not a in a measurable way. There are a handful of routes less due to that that don't need to be regenerated on a cache clear but that's a tiny amount of the total routes and it should have no impact on runtime performance.

---
Tags: views, 8, performance
---


# Question
Title: Remove "<em> edit Article </em>" and [current-page:pager]
I'm working on a Drupal 7 site in which I'm using Meta tag module for SEO purpose. I have configured the meta-tags global and content settings.

When I try to edit a node for a content type, for example, edit an Article, inside the meta tag section in the page title field, it always displays *`<em> Edit title </em>`*, even I have removed all the tokens for this field but it still displays these tokens.

These are the global and content configurations.

>

>

This is how it displays the page title field inside the meta tags section in the content node edit page.

>

I want to remove *`<em> edit Article </em>`* and *\[current-page:pager\]*.

# Answer
> 1 votes
If you indeed removed tags in global and content settings, then they should not appear when creating new nodes. What you are looking at is probably a node that existed before you changed the meta tag settings.

---
Tags: meta-tags
---


# Question
Title: Billing and shipping mismatch on some orders
I just recently getting billing and shipping mismatch on some orders which in turn affects shipping rates. On below transaction shipping rates get billed for Afghanistan, but address details are for USA. Payments go through to Paypal which then need to be refunded due to the mismatch in Countries.

Having a look in the database I get 4 entries for this order, 2 shipping and two billing.

At Home » Administration » Store » Orders \>\> order number I see this:

Billing information: A. Customer Afghanistan

Shipping information: A. Customer 1234 Wild Trail Chocolate, OH 44233 United States

Any advise on how to trouble shoot this? Thanks for your input.

# Answer
> 0 votes
Afghanistan is the default country in country select lists since it's first alphabetically. It appears to me that perhaps some part of your checkout form is causing a previously saved address to be overwritten. This is an infrequent but common issue when combining a variety of Ajax related features on a single checkout form. I'd begin debugging there to see if you can isolate the point at which stale address data is saved to the active billing profile accidentally.

---
Tags: commerce
---


title: Formatting variation as table

text:
# Question
Title: Formatting variation as table
Very new to Drupal and Commerce 2.x. I'm use to working with WooCommerce on Wordpress.

I have a list of equipment products and product attributes created. Each equipment category has different specification so I created different product variation type so I can add in the different attributes.

Under product types \> manage display, the variation format is set to "add to cart form".

My question is how do I style the variation so that it displays as a table? display:table and display:flex doesn't seem to work with the fieldgroups.

**Here is what it looks like now:**

**I want the above information to look like this:**

Eventually I will be changing out the add to cart button to a request a quote so I wasn't sure if i needed to keep the variation format as an add to cart form or not. Unless there is a way for me to add the button in the template itself?

# Answer
What you're needing really is a general overview of Drupal 8 theming using Twig. The parts you're asking about theming here are just Drupal fields like any other, and you can format / render them into the page's HTML however you'd like from the appropriate template file. What that file is called and how you'll reference the fields you've added is dependent on your theme and the names you've set for those fields.

The "Add to Cart form" display formatter doesn't control the inclusion of these fields. It's solely used to render the actual Add to Cart form. The rest of the variation fields are injected into the product display from whatever the currently selected variation on the Add to Cart form is.
> 0 votes

---
Tags: commerce
---


# Question
Title: Prevent view to urlencode contextual filters
I have 2 views.

View 1 is a small exposed form which collects some data and has some contextual filters.

View 1 is linked to View 2, so when the form is submitted the form redirects to View 2 and inserts the collected data as contextual filters in the url.

The fields in the url are in the form of `module[module_field]` but they are printed as `module%5Bmodule_field%5D` in the addressbar in the browser when View 1 redirects to View 2.

But opening manually the same page with the decoded version `module[module_field]` works. How can I prevent View 1 to urlencode the parameters for the contextual filters?

# Answer
> 0 votes
You need to use theme\_links() function in template.php file of your theme. The original theme\_links() function has this:

```
if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

You should replace it with this to undo the encoding:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}

```

---
Tags: 7, views
---


# Question
Title: Create a Json view of the user, with the format of the user/login response
I'm in Drupal 8. After activating the module rest, and try and receive a response from the route /user/login?\_format=json I get this:

```
{
    "current_user": {
        "uid": "4",
        "name": "cravushedal"
    },
    "csrf_token": "49TlM-VLnQcErR1W5vW7losJPLHXPpqE2UpLh9_bZzg",
    "logout_token": "fkBNWh8iLoTbXPO4Elha86PVe_0I8L1JKIxXQ2KemMo"
}

```

Now I want to craete a view with all the users, but something like this:

```
{
    "current_user": {
        "uid": "3",
        "name": "blablabla"
    }
}
{
    "current_user": {
        "uid": "4",
        "name": "cravushedal"
    }
}

```

In my rest view, I have the name, uid, and a Global custom text. The name and the uid are hidden, and I am calling both fields in the global custom text. This is my result:

```
[{"current_user":"1josue"},{"current_user":"2slucuthivili"}]

```

It doesnt recognize the label, so I had try to include them manually, but the json add `\n` or `\what ever` and that destroy my json.

Any idea about how can I achieve this?? thanks!

# Answer
When you query `/user/login` it defaults to currently logged-in user.

I suppose you need to create a view with a "REST export" display. The view defaults to "Entity" row style, change it to "Fields".

In "Fields" settings, you can rename the labels that are output in "Alias" fields:

In this "REST Export" view you will have set a path. i.e. `/rest/people`

Querying `/rest/people?_format=json` should output something like this:

```
[
  {
    "user_name": "admin",
    "user_id": "1",
    "user_customtext": "Custom text"
  },
  ...
]

```

You can use the Global - Custom text field to concat multiple fields as tokens, then hide those fields from being displayed:
> 2 votes

---
Tags: views, 8
---


# Question
Title: Migrate users from a table with non-unique email column
I'm using the Migrate module to migrate users from a non-Drupal PHP/MySQL site to Drupal 7. The users are spread across two tables, the second of which has a non-unique email column, many values of which are present in the first table.

Generally, how do I import the second table, inserting users with new email addresses, and updating a couple fields whenever the email address is already present among the users created from the first table and avoiding duplication errors from the second?

The users from the first table are administrators. The users in the second table are clients. There are other tables that references administrators and clients by ID. ~~The ID columns for the two types of users are unique only within its respective table.~~

I made all the client uid's globally unique by adding 10,000 to all their uid's and updating their references in the other tables accordingly.

# Answer
It depends on what kind of method, modules, tools you'd like to use to migrate the data as each of them might have their own settings for the kind of situation you had described.

If it's just a custom script migrating data between databases, then I would treat all users the same and import any of the tables first and then import the second one ignoring the error message - Drupal won't be importing users with the existing e-mail twice. After the migration you could go over each admin to assign appropriate role.
> 1 votes

---
Tags: migrations
---


# Question
Title: "Page not found" or "Forbidden" when submitting form Is it a problem with Apache?
I have some reseller hosting and I am running Drupal 7 sites on several different accounts there.

I recently noticed a problem when updating one of them. It happens when I am editing content or changing admin settings.

* I go to an admin page - e.g. my.site/admin/people/permissions.
* I make a change and hit "Save".
* The page submits and reloads. The address bar still says my.site/admin/people/permissions, but the page content is:

> Page not found
> The requested page "/admin/people/permissions" could not be found.

I tried changing .htaccess files, disabling modules, etc, but nothing worked. In the end I did the following:

* Created a new hosting account on my reseller hosting
* Installed a fresh copy of drupal-7.58
* Created a new database

When I repeated the actions above, I got the same results, except this time the error message was the following.

> Forbidden
> You don't have permission to access /drupal-7.58/admin/people/permissions on this server.
>
> Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

I then checked another account on the same reseller hosting. It's running Drupal 7.54 and showing *Page not found*.

I didn't have the problem a few weeks ago, so I am wondering if my hosting company has changed something in Apache which is causing this problem (really clutching at straws here).

I am using:

* Apache 2.2.32
* PHP 5.6.30
* MySQL 10.0.34-MariaDB

Can anyone help?

# Answer
Based on the given error message, the issue is definitely about file and/or directory permissions or ownership. Make sure all the files and directories belong to the username under which your website runs. Also fix the permissions per https://www.drupal.org/node/244924.
> 0 votes

---
Tags: 7
---


# Question
Title: Can we update Drush compatibility chart to show Drush 8.1.15 is compatible with Drupal 8.4+
I have a hard time convincing my staff that they can use Drush version 8.1.15 to work on D8 sites on 8.4.6 and later, because the Drush compatibility chart likely needs a new row between D8 and D9 for Drush 8.1.15+ to indicate it can work on D6, D7, D8, D8.4+

The compatibility chart at this location looks like its controlled by git, and I'm just not catching on how to "edit on GitHub". Can someone edit that chart please? I had a colleague update to Drush 9, and now he can't issue commands for Drupal 7 sites.

# Answer
The compatibility table is given on http://docs.drush.org/en/master/install and if you believe something is incorrect on the table, then you must submit issue on https://github.com/drush-ops/drush/issues/new, so authorized users could edit the page.

However, I doubt anything is wrong on that table. And please also note if you install the Drush Launcher as suggested on http://docs.drush.org/en/master/install, then it will automatically load local environment for each Drupal website: Drush 9 for Drupal 8 websites and Drush 8 for Drupal 7 websites.

You might also be interested in reading How to get Drush to work with Composer
> 1 votes

---
Tags: 8, drush
---


title: Trying to get files from the old site

text:
# Question
Title: Trying to get files from the old site
So I am currently trying to access our old website which was set up using Drupal. I re-downloaded all of the databases as well as the site files and set it up on a localhost.

The problem I am having is the only page shown is basically a white version of the old site with just the text of what was on it (without any of the CSS styles). When I try to click on a page it directs me to an "Access denied\* page, unless I use the search box which just redirects me to a white page.

Does anyone know why I cannot get this site to work? I am just trying to access the articles that were published (which are located in the databases).

(I am running this on a local host version thru MAMP)

This is how the site appears.

>

# Answer
> 0 votes
Assuming your site is a Drupal 7 site

1. Make sure you have `.htaccess` in your project root. You can get it here \- this should fix the access denied errors
2. If you have drush, run: `drush cc all` \- this should fix the missing CSS (Drupal doesn't really serve pages directly, it makes cached versions of them. I'd say you caches are empty to they need to be rebuilt.

(If you aren't able to clear / rebuild the cache with drush, please try some of the alternative steps outlined here)

---
Tags: migrations
---


title: Can I manually migrate comments?

text:
# Question
Title: Can I manually migrate comments?
I have a Drupal 7 site and I'm thinking about upgrading it to Drupal 8. I want to refactor the site, so I just need to export the content.

So far, I've tested exporting content types using feeds module and a csv file, as I don't quite understand how to do the export using .yaml files. It did work: I exported the stuff I wanted using views in my current site, and then imported it back using Feeds.

I would like to know if there's a way of manually importing into Drupal 8 all the comments (where I already have imported the content).

I will appreciate any suggestion! Thank you!

# Answer
> 1 votes
Give a try to Migrate module that is for Drupal 7 and comes as part of Drupal 8. It can import comments. You might also be interested in reviewing all migrate tools listed on https://www.drupal.org/docs/8/upgrade/drupal-8-migrate-modules

---
Tags: comments, importing-exporting
---


# Question
Title: Can I set a serial number for each columns or row in a sequential manner?
Can I set a serial number for each column or row, in a sequential manner, from left to right, without doing it manually?

I am using *Content* format, not *Field*. There is no option to add a result counter field.

>

# Answer
> 1 votes
## When format is content

You can override `views-view-unformatted.html.twig` and perhaps create a twig file for just this particular view.

If your view name is **test** you can copy from `core/modules/views/templates/views-view-unformatted.html.twig` to your `THEMENAME/templates` folder and rename to `views-view-unformatted--test.html.twig`. In this twig file you can use `{{loop.index}}` inside the for loop to give you the row index/count sort of like this:

```
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    <span>row count: {{loop.index}}</span>
    {{ row.content }}
  </div>
{% endfor %}

```

## When format is fields

Yes you can add *view results counter* when the format is *fields*

# Answer
> 0 votes
> Can we give serial numbers in views to each columns or row in a sequential manner?

In FIELDS, Add, **Views result counter**.

> How to could i get row counter value in views twig template?

Assuming you're using **views-view-fields--\[viewname\].html.twig** you can print it with

`{{ fields.counter.content }}`

---
Tags: views, 8
---


title: EventSubscriber endless redirect

text:
# Question
Title: EventSubscriber endless redirect
I have Drupal 8.5.1 and I am trying to force a redirect for anonymous users to the CAS login page. First I thought that the issue was related with the firing of the `checkAuthStatus` function below, however, the issue seems related to an **endless redirect**:

```
namespace Drupal\my_custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    \Drupal::logger('my_custom_module')->error('THIS IS A TEST');
    if ($this->account->isAnonymous()
        && \Drupal::routeMatch()->getRouteName() != 'cas.legacy_login'
        && \Drupal::routeMatch()->getRouteName() != 'cas.service') {
      $response = new RedirectResponse('/cas', 301);
      $response->send();
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus', 27];
    return $events;
  }

}

```

What could be the issue?

# Answer
Finally I have solved the issue thanks to the comments I received on my question. Here is the solution I found:

```
namespace Drupal\my_custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    if ($this->account->isAnonymous()
      && \Drupal::service('path.current')->getPath() != '/cas'
      && \Drupal::service('path.current')->getPath() != '/casservice') {
      $response = new RedirectResponse('/cas', 301);
      $event->setResponse($response);
    }
    return;
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus', 100];
    return $events;
  }

}

```

In short, the issue was related with the path checking and the `RedirectResponse` object management.
> 7 votes

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


# Question
Title: Sign out not working properly in OpenID Connect
I have integrated OpenID Connect(Generic), where my Signin was successful(Redirects to destination server, provided credentials, redirect to drupal & authenticated).

While i make Sign out, it was successful. But what i found is, log out happens only at drupal side whereas my destined server session still exists(I have checked it by relogin in drupal, it was authenticated without providing credentials).

Is there is any option to log out from both Drupal & destined server?

# Answer
> 2 votes
The openid\_connect module is great for authenticating/adding users via external identity providers. However, it does not provide single sign out capabilities.

You will have to implement them yourself.

A viable way of doing so is to implement `hook_openid_connect_post_authorize()` to add information about the used identity provider/tokens to the user session/database, and e.g. hook\_user\_logout() to invoking the sign-out endpoint of your identity provider, if the above saved information is present when the user logs off your Drupal.

---
Tags: 7, users, authentication-authorization
---


# Question
Title: Display all dates for a multi-day "event"
I have an "event" content type that can have multiple dates or repeating dates. Up until last week the node view of a repeating event would display all the dates for the event.

> Repeats every week every Friday until Fri Apr 27 2018.
> Friday, April 6, 2018 - 10:00am to 11:00am
> Friday, April 13, 2018 - 10:00am to 11:00am
> Friday, April 20, 2018 - 10:00am to 11:00am
> Friday, April 27, 2018 - 10:00am to 11:00am

Now it only displays the first date.

> Repeats every week every Friday until Fri Apr 27 2018.
> Friday, April 6, 2018 - 10:00am to 11:00am

I don't know what change I made that caused this. I checked the date field settings and the field display settings against a recent backup, and everything is the same.

Do you have any idea?

EDIT: It's not a display issue, it's a data issue. Via `node_load()` I can see that only the first data is written to the database:

```
'field_reserved_time' => array(
    'und' => array(
      array(
        'value' => '2018-04-05 19:30:00',
        'value2' => '2018-04-05 20:30:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=TH;UNTIL=20180427T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
    ),
  ),

```

While previously it would write all dates to the db:

```
'field_reserved_time' => array(
    'und' => array(
      array(
        'value' => '2018-04-06 17:00:00',
        'value2' => '2018-04-06 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
      array(
        'value' => '2018-04-13 17:00:00',
        'value2' => '2018-04-13 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
      array(
        'value' => '2018-04-20 17:00:00',
        'value2' => '2018-04-20 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
      array(
        'value' => '2018-04-27 17:00:00',
        'value2' => '2018-04-27 18:00:00',
        'rrule' => 'RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;UNTIL=20180428T065959Z;WKST=SU',
        'timezone' => 'America/Los_Angeles',
        'timezone_db' => 'UTC',
        'date_type' => 'datetime',
      ),
    ),
  ),

```

# Answer
You have removed the repeat date option for date field. Please check your content type, for repeat date you must have to enable repeat option of date field.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Node select list + dropdown + view of entity references
In a content type, and a field is an entity reference to another content type (the professionals companies).

I created a view, to display: first: the professionals flagged as favorite; then all the others.

Then comes my problem:

How can I create a selection of professionals like this:

1. If user click on the "empty" field (empty before selecting): the list of favorites appears (this can be the first 10 of my view)
2. the user can type and like autocomplete, the results are shown.
3. if no favorite found, then comes a text (with link) to add node (create a new professional).

In the widget type of the entity reference:

* I tried "autocomplete" but the 1. doesn't work (user is obliged to type before something shows)
* I tried "view" but it's even worse (and the search is difficult)
* I tried "select list" but it doesn't allow to search.

I forgot to specify: The 3 options should be on the same field. So, when user click on the field to select (the company), the behavior of the field to select the garage should be like this:

* User clicks on it: user's favorites companies appears (through view)
* If the company he wants was not flagged as favorite, he can start to type in the field and the results appears (classic behavior in Drupal).
* If the name of the company he types doesn't exist, the field shows "no result" and show a link to create a company.

# Answer
maybe you should try these modules (at least for a part of your question):

Inline Entity Form can help you with #3 (embed a node form within another node form with option on existing nodes)

Entity Browser could help you with #1/#2 (build your own widget, based on a View, here with a contextual filter on logged in user and relationship to favorites) - really nice tutorial here.

and Flag for favorites.

I hope this could give you some fresh ideas.
> 0 votes

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


# Question
Title: Custom form, input with ajax autocomplete not working
I have developed a module with a custom form but I don't know why ajax autocomplete doesn't work. The form works good, but in one of the input field I'd like to have a autocomplete function. The next is part of my code:

`src\Form\Mycustomform.php`

```
...
public function buildForm(array $form, FormStateInterface $form_state, $parameter = NULL) {
...
    $form['customer'] = array(
      '#type' => 'textfield',
      '#title' => t('Customer'),
      '#id' => 'inpCustomer',
      '#autocomplete_route_name' => 'mymodule.autocomplete',
    );
....

```

`mymodule.routing.yml`

```
mymodule:
  path: 'mycustompath'
  defaults:
    _form: '\Drupal\mymodule\Form\Mycustomform'
    _title: 'Records'
  requirements:
    _permission: mycustompermission

mymodule.autocomplete:
  path: 'autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::autocomplete'
    _format: json
  requirements:
    _permission: 'access content'

```

`\src\Controller\MyModuleController.php`

```
...
class MyModuleController extends ControllerBase {

    public function autocomplete(Request $request)
    {
        $string = $request->query->get('q');
        $matches = array();
        \Drupal:logger('autocomplete')->notice($string);
        $query = \Drupal::entityQuery('node');
        $query->condition('type','customers');
        $query->condition('title', '%'.$string.'%', 'like');
        $query->sort('title');
        $query->range(0,20);
        $entity = $query->execute();
        $nodos = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity);
        foreach ($nodos as $row) {
            $matches[] = array('value' => $row->getTitle(), 'label' => $row->getTitle());
        }

        return new JsonResponse($matches);
    }
}

```

If I see drupal log, I never get a register as expected. But if I see conosole log, I don't see ajax request. How could I find where is the problem? I think there isn't an ajax call when I write some letters on the input field. I don't see the circle on the right of the input that is shown when autocomplete is working.

# Answer
> 2 votes
After some tests I have found the problem. My code is right and it works good. The problem was the template file `input--textfield.html.twig`. Input textfield needs some automplete classes to work and this template deleted them to add some other classes. The required classes are: `form-autocomplete form-text ui-autocomplete-input`. I have changed this template file to add a new class I need but without deleting the other, and then, autocomplete works.

# Answer
> 0 votes
I do not tested your code but I see that your custom form doing completely the same like entity\_autocomplete form element https://www.drupal.org/node/2418529

```
$form['customer'] = array(
      '#type' => 'entity_autocomplete',
      '#title' => t('Customer'),
      '#id' => 'inpCustomer',
      '#target_type' => 'node',
      '#selection_settings' => array(
        'target_bundles' => array('customers'),
        ),
    );

```

---
Tags: 8, forms, ajax
---


# Question
Title: How to resolve the error "Base table or view not found"?
When I connect my custom module with database external

```
$database = array(
  'host' => 'localhost',
  'database' => 'DATABASE1',
  'username' => 'root',
  'password' => 'root',
  'driver' => 'mysql',
);
Database::addConnectionInfo('mykey', 'default', $database);
   db_set_active('mykey');

```

it gives error on running the module

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'DATABASE1.filter\_format' doesn't exist: SELECT ff.\* FROM {filter\_format} ff WHERE (status = :db\_condition\_placeholder\_0) ORDER BY weight ASC; Array ( \[:db\_condition\_placeholder\_0\] =\> 1 ) in filter\_formats() (line 434 of /var/www/html/drupalprac/modules/filter/filter.module).
>
> Uncaught exception thrown in shutdown function.
>
> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'DATABASE1.semaphore' doesn't exist: DELETE FROM {semaphore} WHERE (value = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 1595456215ac3545f2ff1c3.60338979 ) in lock\_release\_all() (line 269 of /var/www/html/drupalprac/includes/lock.inc). Uncaught exception thrown in session handler.
>
> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'DATABASE1.sessions' doesn't exist: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db\_condition\_placeholder\_0) AND (ssid = :db\_condition\_placeholder\_1) ); Array ( \[:db\_condition\_placeholder\_0\] =\> gSAxKMpfVXzf2EVP4EWBtuF2klcg0RZie30ztTTUjKc \[:db\_condition\_placeholder\_1\] =\> ) in \_drupal\_session\_write() (line 209 of /var/www/html/drupalprac/includes/session.inc).

# Answer
You need to switch the database back before it carries out any operation that requires the Drupal database.

```
// Switch to your custom database.
db_set_active('mykey');

// Work with that database (select/insert/update).
...

// Switch back, before you use the Drupal API again
db_set_active();

```
> 2 votes

---
Tags: 8, database
---


# Question
Title: How to bypass HTML mail for specific Webform
I have configuration Mailsystem to send all webform emails as HTML, I thought I could use the "key" in mailsystem's configuration to specify which webforms' submissions get sent as HTML or plain text. Unchecking the checkbox on the webform's email handler to say "Send email as HTML" only strips HTML from mail, but the wrapper is still HTML.

While keeping HTML emails for most webform generated emails, how do I configure one to be sent as plain text?

# Answer
There are two parts to this answer 1) Mailsystem configuration and 2) Mailsystem template suggestions.

**1) Mailsystem configuration**

This solved the issue for me and I was perhaps being silly: Go to /admin/config/system/mailsystem and set Mime Mailer as your default config, well I want that as default.

Then below I had webform config for all webforms, but this was overkill as the settings above already made webforms use Mime Mailer, what I needed to do was add an override for this one email handler:

The specific email handler machine name was email so you can see its key is "email\_email".

**2) Mailsystem template suggestions**

Something I learnt while investigating this is that there are template suggestions added by mimemail.module of the following pattern:

```
$suggestions[] = "mimemail_messages__" . $variables['key'];

```

So the above webform email, if using mimemail would use a template named `mimemail-messages--email-email.html.twig`
> 2 votes

---
Tags: 8, webforms, emails
---


# Question
Title: Updating packages with composer and knowing what to update
I'm just starting to work with Drupal 8 and composer and I'm trying to figure out how the updating workflow should work. I know the basics from administering a Drupal 7 server for years, but the Composer part is tripping me up.

Right now I run, from the root folder of my Drupal install, (with maintenance mode enabled) `composer outdated` and I get a list of a bunch of packages in need of an update.
As far as I can tell from the documentation, I should only be updating the packages that start with "drupal/". Assuming just the console and core come up as outdated, I run `composer update drupal/console drupal/core --with-dependencies` and that pulls down the updates, and does its thing. After this is done, if I run `composer outdated` again, I still see a bunch of packages that are outdated according to composer. Is that intended? Or should these packages be updated?

I'm guessing Drupal is built using specific versions of packages, so updating all of them would probably break some stuff, right? How is someone supposed to know what packages should be updated and which ones should stay at a specific version?

This is what I get when I run `composer outdated`.

```
alchemy/zippy                         0.4.3       0.4.8       Zippy, the archive manager companion
composer/installers                   v1.4.0      v1.5.0      A multi-framework Composer library installer
consolidation/annotated-command       2.8.1       2.8.2       Initialize Symfony Console commands from annotated command class methods.
consolidation/output-formatters       3.1.12      3.1.13      Format text by applying transformations provided by plug-in formatters.
cweagans/composer-patches             1.6.2       1.6.4       Provides a way to patch Composer packages.
dflydev/dot-access-data               v1.1.0      v2.0.0      Given a deep data structure, access data by dot notation.
drupal/php                            1.0.0-beta1 1.0.0-beta2 Allows embedded PHP code/snippets to be evaluated. Enabling this can cause security and performance issues as it allows users to execute PHP code on your site.
egulias/email-validator               1.2.14      2.1.3       A library for validating emails
fabpot/goutte                         v3.2.1      v3.2.2      A simple PHP Web Scraper
gabordemooij/redbean                  v4.3.4      v5.0        RedBeanPHP ORM
jcalderonzumba/gastonjs               v1.0.3      v1.2.0      PhantomJS API based server for webpage automation
phpdocumentor/reflection-docblock     2.0.5       4.2.0
phpspec/prophecy                      v1.7.2      1.7.3       Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage             2.2.4       5.3.0       Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator             1.4.2       1.4.5       FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-token-stream              1.4.11      2.0.2       Wrapper around PHP's tokenizer extension.
phpunit/phpunit                       4.8.36      6.5.5       The PHP Unit Testing framework.
phpunit/phpunit-mock-objects          2.3.8       5.0.6       Mock Object library for PHPUnit
sebastian/comparator                  1.2.4       2.1.1       Provides the functionality to compare PHP values for equality
sebastian/diff                        1.4.3       2.0.1       Diff implementation
sebastian/environment                 1.3.8       3.1.0       Provides functionality to handle HHVM/PHP environments
sebastian/exporter                    1.2.2       3.1.0       Provides the functionality to export PHP variables for visualization
sebastian/global-state                1.1.1       2.0.0       Snapshotting of global state
sebastian/recursion-context           1.0.5       3.0.0       Provides functionality to recursively process PHP variables
sebastian/version                     1.0.6       2.0.1       Library that helps with managing the version number of Git-hosted PHP projects
symfony-cmf/routing                   1.4.1       2.0.3       Extends the Symfony2 routing component for dynamic routes and chaining several routers
symfony/browser-kit                   v3.3.10     v4.0.3      Symfony BrowserKit Component
symfony/class-loader                  v3.2.14     v3.4.3      Symfony ClassLoader Component
symfony/config                        v3.2.14     v4.0.3      Symfony Config Component
symfony/console                       v3.2.14     v4.0.3      Symfony Console Component
symfony/css-selector                  v3.3.10     v4.0.3      Symfony CssSelector Component
symfony/debug                         v3.4.3      v4.0.3      Symfony Debug Component
symfony/dependency-injection          v3.2.14     v4.0.3      Symfony DependencyInjection Component
symfony/dom-crawler                   v3.4.3      v4.0.3      Symfony DomCrawler Component
symfony/event-dispatcher              v3.2.14     v4.0.3      Symfony EventDispatcher Component
symfony/expression-language           v3.4.3      v4.0.3      Symfony ExpressionLanguage Component
symfony/filesystem                    v3.4.3      v4.0.3      Symfony Filesystem Component
symfony/finder                        v3.4.3      v4.0.3      Symfony Finder Component
symfony/http-foundation               v3.2.14     v4.0.3      Symfony HttpFoundation Component
symfony/http-kernel                   v3.2.14     v4.0.3      Symfony HttpKernel Component
symfony/process                       v3.2.14     v4.0.3      Symfony Process Component
symfony/routing                       v3.2.14     v4.0.3      Symfony Routing Component
symfony/serializer                    v3.2.14     v4.0.3      Symfony Serializer Component
symfony/translation                   v3.2.14     v4.0.3      Symfony Translation Component
symfony/validator                     v3.2.14     v4.0.3      Symfony Validator Component
symfony/var-dumper                    v3.4.3      v4.0.3      Symfony mechanism for exploring and dumping PHP variables
symfony/yaml                          v3.2.14     v4.0.3      Symfony Yaml Component
twig/twig                             v1.35.0     v2.4.4      Twig, the flexible, fast, and secure template language for PHP
webflo/drupal-finder                  1.0.0       1.1.0       Helper class to locate a Drupal installation from a given path.

```

This is a fairly vanilla Drupal install. I only have a few modules added and one theme. I should probably also mention that this site was build using the drupal-composer template mentioned in the official docs (https://github.com/drupal-composer/drupal-project).

# Answer
Honestly, for a codebase like your typical Drupal site, this is a hard problem to solve. Take, for instance, my Drupal VM Prod codebase, which I just upgraded from Drupal core 8.4.5 to 8.5.0 yesterday:

* My drupal/core version constraint in composer.json is `~8.4`
* Running `composer update drupal/core --with-dependencies` didn't update Drupal core; it was stuck at 8.4.5
* Running `composer update` (more of the nuclear option—it will update everything, including contrib modules and any other dependencies, which could cause issues and make it way harder to test individual updates on a complex site!) worked to upgrade Drupal core... but that's not ideal.

So I asked about it in the issue composer fail to upgrade from 8.4.4 to 8.5.0-alpha1, and even tried to figure out which dependency was blocking my Drupal core upgrade using the Composer command:

```
composer prohibits drupal/core:8.5.0

```

This listed off a ton of different symfony components... so I could've sat there and copy-pasted each of the 14 components into my `composer update` command, but that is not fun to do, so I kept poking around (to no avail).

Later in the comment thread, @eiriksm mentioned that since my project has `symfony/config` (a dependency of drush and drupal console), I needed to run `composer update drupal/core symfony/config --with-dependencies`.

I still have no idea how I could've figured out I just needed to add `symfony/config` in the update command (vs adding all the other symfony components)... but if I do, I'll try to update this answer with that information so others can benefit in the future!
> 4 votes

# Answer
Updating minor versions (8.3 \> 8.4, 8.4 \> 8.5) with composer is a nightmare.

I am coming to the conclusion that maybe `composer update` should be "embraced" and that one should manage module versions carefully in `composer.json` perhaps locking them all to the currently installed versions, then changing the version only when you want to update the module. That is really not that big a deal to do.

That is really how we did it before composer. We decided what module to update one by one, not all at once, with `drush up modulename` or whatever.

This could mean installing modules with specific version numbers is a good idea:

```
composer require "drupal/address:1.0"

```

not this

```
composer require "drupal/address:~1.0"

```

You can always change `"~1.0"` to `"1.0"` later in `composer.json`, but if you install a specific version number, you won't need to.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: How to debug 404 on user/login user/register user/logout?
I have a Drupal 8 site on 8.4.2. When I upgrade it to 8.5.1, after running the database updates, the paths `/user/register`, `/user/login`, and `/user/logout` return a 404.

* I can log in with Drush (`drush uli myuser`), so it is possible to actually log in, but the log in page is not displayed.
* I tried uninstalling my custom modules, but the problem persists.
* I looked at `/admin/reports/dblog`, but it just says "page not found" as the error for `/user/login`.

This question about a similar problem was closed as off topic because it was too specific; my question is about "how can I debug this?" not "what is the cause of my problem?"

# Answer
> 3 votes
@AndrewKillen:

> Checked with Devel and it says "Unable to load route for url '/user/login'" when checking the user.login route.

How this could be debugged (on an working example, because I don't have a broken site):

Enable Xdebug and go to the url: /devel/routes/item?path=/user/login

*Drupal\devel\Controller\RouteInfoController::routeDetail:*

```
  public function routeDetail(Request $request, RouteMatchInterface $route_match) {
    $route = NULL;

    // Get the route object from the path query string if available.
    if ($path = $request->query->get('path')) {
      try {
        $route = $this->router->match($path);

```

Set a breakpoint for the last line and step into `match($path)`. Then after a new request with the path info is created you get to:

*Router::matchRequest:*

```
  public function matchRequest(Request $request) {
    $collection = $this->getInitialRouteCollection($request);
    if ($collection->count() === 0) {
      throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $this->currentPath->getPath()));
    }
    $collection = $this->applyRouteFilters($collection, $request);

    if ($ret = $this->matchCollection(rawurldecode($this->currentPath->getPath($request)), $collection)) {
      return $this->applyRouteEnhancers($ret, $request);
    }

```

`getInitialRouteCollection()` results in three possible matches:

* user.login
* user.login.http
* entity.user.canonical

The second one is filtered in `applyRouteFilters()` because this is POST only and for JSON. The entity route is removed after the compiled routes are matched in `matchCollection()` because "login" is not a valid user.

And so the route user.login is the last one remaining and returned. If not you have to check where on this way the route is not collected or filtered out.

---
Tags: 8, debugging, uri
---


# Question
Title: How do I change the original language in PHP files and Twig files?
I have installed a Drupal 8.5 site in French (monolingual). Then, I added content.

Of course, there are many strings in the PHP files of my custom theme/module I pass to `t()`. There are also many strings in the Twig files I translated with `{{ 'a string'|trans }}`.

After a while, I added English.

Unfortunately, I discovered that all the strings (interface) I just mentioned are seen by Drupal as English string.

For example, using the Translation template extractor module, I don't have the choice to extract the strings in English. I have only 2 options for the extraction: *Language independent template* and *Template file for French translations*.
When I use the Translation Management Tool module, all the locale sources strings have *Original language* under the English column and *Not translated* under the French column.

How do I tell Drupal that all my strings (PHP and Twig) are French strings? Alternatively, what is the process to be able to export/translate in English, and import files (PO or XLIFF) into my site?

# Answer
> How do I tell Drupal that all my strings (PHP and Twig) are French strings?

You can not. There is no setting for that, the source code *must* be english.

Drupal *does* allow to translate the code/system-english to the actual english if you enable the checkbox when editing the english language. I don't know what that does exactly to potx and I don't think TMGMT supports it either.
> 1 votes

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


title: Redirect not obeying front page URL

text:
# Question
Title: Redirect not obeying front page URL
We are using this module for our redirection for 404's and manually created redirects.
The site has a number of pages translated for the American audience. We added a redirect today for a page and simply pointed the redirect url to `<front>`. The referring URL is http://www.example.com/when-to-go/october. In the *General site* settings, the front page is set to /homepage. (A Basic page for this exists.)

Now when going to http://www.example.com/when-to-go/october, the users are redirected to http://www.example.com/en-us which gives a *The page isn't redirecting properly* error.

There are two issues:

* It should simply send users to /homepage, which is what is set to
* If we wanted the American version, then it should use *en-US* not *en-us*; Drupal seems to be treating this as case sensitive

# Answer
A circular redirect was been caused which stopped the redirect to front working. Checking the redirects already created and removing the offending ones fixed the issue.
> 0 votes

---
Tags: redirection
---


# Question
Title: What is the difference between "content type" and "custom content type"?
Can anyone explain to me the difference between *content type* and *custom content type*?

# Answer
> 2 votes
*Custom content type* can be used with two different meanings:

* Any node type (bundle, or entity bundle, in Drupal 8 terminology) created from the user interface (admin/structure/types/add in Drupal 7 and Drupal 8) from users with the right permissions
* Any node type implemented from third-party modules

What is not a custom content type is a content type created from a Drupal core module, or a Drupal core profile. For example, the *Forum topic* content type is created from the Forum module, while the *Article* content type is created from the Standard profile.

For the rest, there isn't much difference between a custom content type and a content type: Both can be extended with fields.
There could be a difference between a content type created from a module (core module or third-party module) and a content type created through the user interface: the content type fields that aren't created from the user interface made available from the *Field UI* module. For example, the Forum module adds to the *Forum topic* content type a reference field for a vocabulary the module created. Similarly, the Standard profile adds a field to attach an image to nodes of the *Article* content type.

# Answer
> 3 votes
A content type is a type of node. Node types (aka content types) are generally created through the browser UI. However, they can also be created through code, which people refer generally refer to as a custom content type.

---
Tags: nodes
---


# Question
Title: How to remove all attributes displayed for a field?
We are looking for a way to remove all the attributes for one or more fields (if not all) when they are displayed. There is a way to do this using Twig template by removing `{{ attributes.addClass }}` in any twig template that has `<article {{ attributes.addClass }}>`, but that requires for us to do this with all fields and any twig templates.

The goal would be to have a settings globally to remove the attributes, but we have been unable to find a module that does this.

How would we without modifying twig templates, accomplish this situation?

We have a way to add custom attributes on a as needed basis.

# Answer
> 0 votes
We ended up creating a `field.html.twig` in our custom sub theme where all the attributes were removed and only added them on an as needed basis.

---
Tags: 8, theming, entities
---


# Question
Title: In views, add class depending on the user input in a checkbox.
I need to add a class to a field of views depending if the user wants to have an overlay on the image or no. We need to use a checkbox for the user to input if it needs the class or no.

# Answer
1. Create your boolean field (my case the name is field\_no\_overlay), The checkbox should have the values for the classes you want to use and apply to your field.

2. In the views, rewrite your value .
3. Create the style for each class.
> 1 votes

---
Tags: 7, views
---


# Question
Title: correct way to load JS library for custom module
I am trying to use d3.js in my module, but I am facing some issues.

I have the D3 module installed in sites/all/modules/d3/ and d3.min.js installed in sites/all/libraries/d3/, and I can see the d3/examples fine.

Now I have a js script in my custom module that is supposed to use D3, but I fail to load it. Here's my attempt to load the library:

```
drupal_add_library('d3','d3');
# retrieve some data as JSON
$setting = mymodule_load_data($param);
# create the render array
$content = array(
  '#attached' => array(
    # attach JS
    'js' => array(
      array(
        'type' => 'setting',
        'data' => array('mymodule' => array('json_data' => $setting)),
      ),
      array(
        'type' => 'file',
        'data' => drupal_get_path('module', 'mymodule') .'/js/myscript.js',
      ),
    ),
    'css' => array(
      drupal_get_path('module', 'mymodule') . '/css/mystyle.css',
    ),
  )
);
# return result
return $content;

```

but I don't see d3 included in the source code of my page and myscript.js of course doesn't work.

I have checked the return value of drupal\_add\_library as suggested in the comments and it's FALSE.

Any hints?

# Answer
> 3 votes
`drupal_add_library()` works only with libraries defined from `hook_library()` implementations. Since the d3.js module implements hooks used from the *Libraries API* module, you need to use the functions this module make available.

See Using Libraries API 2.x (as a module-developer) or Using Libraries API 1.x (as a module-developer), basing on which version of the *Libraries API* module you are using.

Normally, with the 2.x branch of the *Libraries API* module, you just call `libraries_load('d3')` which will call `drupal_add_js()`, or `drupal_add_css()`, or both, depending on what the library contains. Otherwise, if you need to check when a library has not been loaded, you use code similar to the following one.

```
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // The library has been loaded.
}

```

Even better, using a render array, you just need to use code similar to the following one, which is for the case the library needs to be attached to a form element.

```
$form['myelement']['#attached']['libraries_load'][] = array('d3');

```

For an `hook_page_build()` implementation, adding the library at the page bottom requires code similar to the following one.

```
function mymodule_page_build(&$page) {
    $page['page_bottom']['d3_library']['#attached']['libraries_load'][] = array('d3');
  }
}

```

---
Tags: 7, javascript
---


title: Get drupal breadcrumb by providing nid?

text:
# Question
Title: Get drupal breadcrumb by providing nid?
How can I get a breadcrumb path by providing `$nid`?

Example

```
$nid = 116;
$breadcrumb = breadcrumb_get_crumb($nid);

```

I have a node type that is always associated with another node, and I want to use that node's breadcrumb trail for this node too.

# Answer
> 2 votes
You could use Crumbs module. Now, if you say these nodes are "associated", I wonder how exactly? With an Entity reference field? Or just that you know the parent? Is this for all nodes of this type, or just for this specific one? Are these nodes somewhere in a menu?

If you can arrange either of the criteria above, you can use existing Crumbs plugins. Otherwise, you could do a custom module..

# Answer
> 0 votes
sounds to me that you could use the Custom Breadcrumbs module, just set those node types custom breadcrumbs to what you want.

# Answer
> 0 votes
I just wrote a function to retrieve this information. It loops through the menu structure several times and builds a array with the needed info.

```
function getBreadcrumbs($menu)
{

    $menu = @menu_load_links($menu);
    $breadcrumbs = array();
    $parentSearch = -1;

    // check 10 levels back from the current page, back to the highest page
    for ($i = 0; $i <= 10; $i++) {
        // stop when the item with no parent is found
        if ($parentSearch === 0) {
            continue;
        }
        // loop the menu for this level check
        foreach($menu as $item) {
            $link = url($item['link_path']);
            if ($link === url(current_path()) && $parentSearch === -1) {
                $breadcrumbs[] = array('title' => $item['link_title'], 'url' => $link, 'current' => true, 'mlid' => $item['mlid']);
                $parentSearch = (int) $item['plid'];
            } else if ($parentSearch !== -1 && (int) $item['mlid'] === $parentSearch) {
                $breadcrumbs[] = array('title' => $item['link_title'], 'url' => $link, 'current' => false, 'mlid' => $item['mlid']);
                $parentSearch = (int) $item['plid'];
            }
        }
    }

    return array_reverse($breadcrumbs);
}

```

---
Tags: 7
---


title: Which PHP/MySQL version should I use?

text:
# Question
Title: Which PHP/MySQL version should I use?
We plan on updating our Drupal 6 (with MySQL 5.5x and PHP 5.x) site to Drupal 7.

Which version of PHP and MySQL should I choose?

# Answer
You will get the best speed performance using PHP 7.x. I've been running a few Drupal sites on PHP 7 with no issues, and definite performance improvements over PHP 5.x.

MySQL 5.5 or 5.6 is good.
> 1 votes

# Answer
The minimum PHP version supported by Drupal 7 is 5.2.5. The minimum recommended PHP version for Drupal 7 is PHP 7.1.x, until December 1, 2019. After that date,PHP 7.1 will only receive security fixes, and it should not be anymore used for new sites.

* Drupal 7.50's automated test suite is now fully passing on PHP 5.4, 5.5, 5.6, and 7; third-party modules could still have issues when running on PHP 7.1
* Drupal 7.63 or higher is recommended for using PHP 7.1 and PHP 7.2
* For Drupal 7.62 or higher, the minimum required is PHP 5.3.3

Drupal 7 supports MySQL 5.0.15/MySQL 5.1.30/MariaDB 5.1.44/Percona Server 5.1.70 or higher.

This is all for Drupal core. The compatibility with third-party modules can vary, and there could be modules having troubles with the newest PHP version, especially because backward incompatible changes.

Before upgrading PHP, you should make a test on a development site, and see if any of the modules you are using cause problems with the newer PHP/MySQL versions.

### References
> 1 votes

# Answer
Before upgrading to Drupal 7, consider to directly upgrade to Drupal 8, as the upgrade path is smoother and D8 is the new version, so you won't have to migrate from D7 to D8 in a relatively short period.

Note this for Drupal 7, taken from Drupal PHP requirements:

> Because PHP 7 is the newest release, extra care should still be taken with it. See the Drupal 7.50 release notes and the PHP 7 discussion for more details. However anecdotal evidence from a variety of users suggests that Drupal 7 can be successfully used on PHP 7, both before and after the 7.50 release.

Regarding MySQL, taken from Drupal database server requirements:

> Drupal 7 supports MySQL 5.0.15/MySQL 5.1.30/MariaDB 5.1.44/Percona Server 5.1.70 or higher, and requires the PDO database extension for PHP

Anyway I invite you to read the two linked pages, as they contain useful information that goes beyond your question.
> 1 votes

# Answer
MySQL 5.5 will work just fine (according to the docs).

But as @user1527576 suggested, consider going from D6 directly to D8. Drupal's upgrade path usually skips (bunny hops?) major versions, unlike most software.

And with any Drupal upgrade, testing it is HIGHLY recommended - in a staging environment that resembles your production environment as closely as possible.
> 0 votes

# Answer
I think dont need to upgrade Mysql version. Drupal7 has support of Mysql5.0 and higher, but first you have to upgrade major version of Drupal6 and then can update to drupal7.
> 0 votes

---
Tags: 7
---


# Question
Title: Custom template files for multiple blocks provided by a custom module?
The custom module is called, "epic\_module". It defines several blocks, say "awesome\_block" and "epic\_block".

```
function epic_module_block_info() {
  $blocks['awesome_block'] = array(
    'info' => t('Awesome block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['epic_block'] = array(
    'info' => t('Epic Block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function epic_module_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'awesome_block':
      // TO-DO: Set $block['content'], etc...
      break;
    case 'epic_block':
      // TO-DO: Set $block['content'], etc...
      break;
  }
  return $block;
}

```

I have also created a templates directory under my module's directory.

I'm confused by the naming conventions. I want to link the template files for the specified blocks.

# Answer
If you want to use a different template file for your blocks, by default Drupal uses the following template files.

* block--epic-module.tpl.php for all the blocks implemented by the module you are showing
* block--epic-module--awesome-block.tpl.php and block--epic-module--epic-block.tpl.php for the blocks implemented by that code

Keep in mind that each underscore in the module name or in the block name (i.e. what the documentation calls *delta*) is replaced with a hyphen.

### Reference
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Specify default sort header for a sortable table (tablesort) in D8?
I am trying the table sort example module and noticed that I am unable to specify the default sort col once the page load. Meaning, when the page load for the first time it's always sorting by the first column in the table. In this case the number column (see screenshot). I tried `'sort'=> 'DESC'` and `'sort'=> 'ASC'` on the second and third col but it did not pick any as a default sort col. Here is the code generating the tablesort:

```
<?php

namespace Drupal\tablesort_example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller routines for tablesort example routes.
 */
class TableSortExampleController extends ControllerBase {

  /**
   * The Database Connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }

  /**
   * TableSortExampleController constructor.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * A simple controller method to explain what the tablesort example is about.
   */
  public function description() {
    // We are going to output the results in a table with a nice header.
    $header = [
      // The header gives the table the information it needs in order to make
      // the query calls for ordering. TableSort uses the field information
      // to know what database column to sort by.
      ['data' => t('Numbers'), 'field' => 't.numbers'],
      ['data' => t('Letters'), 'field' => 't.alpha'],
      ['data' => t('Mixture'), 'field' => 't.random'],
    ];

    // Using the TableSort Extender is what tells  the query object that we
    // are sorting.
    $query = $this->database->select('tablesort_example', 't')
      ->extend('Drupal\Core\Database\Query\TableSortExtender');
    $query->fields('t');

    // Don't forget to tell the query object how to find the header information.
    $result = $query
      ->orderByHeader($header)
      ->execute();

    $rows = [];
    foreach ($result as $row) {
      // Normally we would add some nice formatting to our rows
      // but for our purpose we are simply going to add our row
      // to the array.
      $rows[] = ['data' => (array) $row];
    }

    // Build the table for the nice output.
    $build = [
      '#markup' => '<p>' . t('The layout here is a themed as a table
           that is sortable by clicking the header name.') . '</p>',
    ];
    $build['tablesort_table'] = [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];

    return $build;
  }

}

```

# Answer
> 3 votes
I was trying `$header= [ .... ['data' => .... 'sort'=> 'DESC' ,` and that was not working. After debugging, I found out the sort value is case sensitive. In function tablesort\_get\_order we have

```
  if (empty($default) && isset($header['sort']) && ($header['sort'] == 'asc' || $header['sort'] == 'desc')) {
    $default = $header;
  }

```

So it must be lower case to work. The following code achieves the desired behaviour:

```
$header = [
      // The header gives the table the information it needs in order to make
      // the query calls for ordering. TableSort uses the field information
      // to know what database column to sort by.
      ['data' => t('Numbers'), 'field' => 't.numbers'],
      ['data' => t('Letters'), 'field' => 't.alpha'],
      ['data' => t('Mixture'), 'field' => 't.random', 'sort' => 'desc'],
    ];

```

I hope this helps others.

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


title: Get contextual filter ID in views row

text:
# Question
Title: Get contextual filter ID in views row
I've got a view with a contextual filter for an entity reference field. The contextual filter fetches the current node id from URL as filter criteria. The individual rows of the view are rendered as content in teaser view mode (not using fields), so basically it uses `node--nodetype--teaser.html.twig` to render the results. The view is attached to nodes using the EVA module

I now need the value of a field from the host/contextual node in `node--nodetype--teaser.html.twig` (the template used by the views row). I know how to query entities and fields, but I don't know which hook to use and how to get the node ID of the contextual filter.

How can I get the contextual filter ID and which hook should I use to pass the contextual filter down to the node teaser template?

# Answer
> 3 votes
Implement template\_preprocess\_node in your .theme file and get the page's node with the following code.

```
/**
 * Implements template_preprocess_node().
 */
my_theme_preprocess_node(&$vars) {
  // This will fire for any node type with the teaser view mode
  if ($vars['view_mode'] == 'teaser')
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // You have the full node object and can access fields as needed.
      // You can even check the $node type in the above if statement to only add
      // this value to the teaser for nodes when you're on the type with your EVA
      // Make sure to add them to the $vars array to see them in your template.
    }
  }
}

```

See this post re: how to access fields from a node object.

Note: This doesn't do exactly what you're asking, but will work if you're viewing the full page of the node with the EVA.

---
Tags: views, 8
---


# Question
Title: if function getValue() on null return nothing
I looked around, but am not exactly sure how to ask this question.

Is there a means of not erroring out on "function getValue() on null". Basically I'd like to return nothing and move on if getValue is being called on something that doesn't exist.

# Answer
> 3 votes
You can check if a field is empty or not before asking for `getValue()` with:

```
if (!$entity->get('field_name')->isEmpty()) {
  $value = $entity->get('field_name')->getValue();
}

```

---
Tags: 8, entities
---


title: Fuzzy image display on new content type

text:
# Question
Title: Fuzzy image display on new content type
I'm having issues on our Drupal 7 site. We have created a new content type that includes a hero image. The problem is that full sized images that we upload aren't displayed on the page (despite calling for "Original image" in the manage display settings.

Instead, the page is displaying the image in Drupal's "large" image style, then scaling up on the page and creating a blurry image.

Here's a test page: https://claremontmckdev.prod.acquia-sites.com/content/history-0

# Answer
Based on the markup on your test page reflecting an html5 element and the code snippet calling for a "picture\_sizes\_formatter", I suspect your site has the Picture and Breakpoints module) installed which automatically serve images based on predefined/configured breakpoints.

Go to the Picture Mappings configuration page *Config \> Media \> Picture Mappings* (/admin/config/media/picture) to examine existing mappings and add new ones.

You should be able to add a new picture mapping for a wider breakpoint to serve the original image, thus limiting serving the large image to a narrower desktop viewport.

Once you've added an additional mapping (and possibly a wide breakpoint), don't forget to clear the caches before reloading your test page.
> 0 votes

# Answer
In the off chance that anyone else is struggling with this issue, we were able to solve the conundrum. The pages were created via panels and the formatter settings for the image within the panel settings were set to "picture." Changed that to "Image" and all was copacetic.
> 0 votes

---
Tags: media
---


# Question
Title: Creating content with content type: only Title is displaying on first click not the other fields
I have a content type to submit events/workshops etc for a conference.

The fields I have are like this:

Label; Machine name; Field type; Widget; Event Title; title; Node module element;

Fields: Panel Image; field\_panel\_image; Image; Image;

Room; field\_room; Entity Reference; Drag & Drop;

Timeslot; field\_timeslot; Entity Reference; Drag & Drop;

Speaker First and Middle Name; field\_speaker\_first\_and\_middle\_n; Text; Text field;

Speaker Last Name; field\_speaker\_last\_name; Text; Text field;

Speaker Email(s); field\_speaker1\_email; Text; Text field;

Speaker Affiliation(s); field\_speaker1\_affiliation; Text; Text field;

Speaker Biography; field\_speaker1\_biography; Text; Text field;

Problem is that when the authorized user clicks on the link which leads to the add content type form it does just display the "Event Title" field. When I am logged in as admin I see the whole form.

But the "normal" authorized user needs first to hit save after typing in the event title and then the site displays the title of that just created node and an edit button. When the authorized user clicks on "edit" s/he sees the whole form.

Is there a way where the authorized user sees the whole form immediately when s/he calls up that content type form?

(Some of the fields mentioned above (room and time slot) have the permissions set so that just admins should be able to see it. But the other permissions are set for authorized users as well.

Thank you.

Marcus

**../admin/reports/status:** Drupal 7.58 Web server Apache/2.4.10 (Debian)

CKEditor 4.5.4 Code per Node CodeMirror v5.36.1 is installed. CodeMirror is installed and it is a compatible version. Excellent! Configuration file Protected CSS Injector directory writable CSS Injector Directory public://css\_injector is writable

CTools CSS Cache Database system version Database updates Date iCal iCalcreator library is installed, version: 2.20.2 found Drupal core update status File system Writable (public download method) GD library PNG support 2.1.1-dev GD library rotate and desaturate effects 2.1.1-dev

jQuery Update jQuery 1.7.2 (configure) and jQuery UI 1.10.2 Warning Module and theme update status There are updates available for one or more of your modules or themes. To ensure the proper functioning of your site, you should update as soon as possible. See the available updates page for more information and to install your missing updates.

Node Access Permissions 540 permissions in use If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions. Rebuild permissions

OpenSSL Enabled (OpenSSL 1.0.1t 3 May 2016) PHP 5.6.33-0+deb8u1 (more information) PHP extensions Enabled

PHP memory limit 256M PHP register globals Disabled

Plupload library 1.5.8 SOAP Enabled

Unicode library PHP Mbstring Extension Update notifications Enabled

Upload progress Not enabled Your server is capable of displaying file upload progress through APC, but it is not enabled. Add apc.rfc1867 = 1 to your php.ini configuration. Alternatively, it is recommended to use PECL uploadprogress, which supports more than one simultaneous upload.

Views Data Export temporary directory Exists

---

**MODULES ENABLED** Name Administration menu Adminimal Theme (adminimal\_admin\_menu)

Auto Assign Role (autoassignrole)

Automatic Entity Labels(auto\_entitylabel)

Backup and Migrate(backup\_migrate)

Better Exposed Filters(better\_exposed\_filters)

Block Class (block\_class)

Bootstrap Login Modal(bootstrap\_login\_modal)

Calendar (calendar)

CKEditor Link (ckeditor\_link)

CKEditor (ckeditor)

COD Email (cod\_email)

COD Session (cod\_session)

Code per Node (cpn)

Coffee (coffee)

Commerce Billy Mail(commerce\_billy\_mail)

Commerce Coupon(commerce\_coupon)

Commerce Event Ticket(commerce\_event\_ticket)

Commerce Features(commerce\_features)

Commerce iATS (commerce\_iats)

Composer Autoloader(composer\_autoloader)

Conditional Fields(conditional\_fields)

Contact (contact)

Content Access (content\_access)

Content Type Clone(content\_type\_clone)

Contextual links (contextual)

CSS Injector (css\_injector)

Database logging (dblog)

Date All Day (date\_all\_day)

Date iCal (date\_ical)

Date Tools (date\_tools)

Devel generate (devel\_generate)

Devel (devel)

Display Suite Extras (ds\_extras)

Display Suite Format (ds\_format)

Display Suite Forms (ds\_forms)

Display Suite UI (ds\_ui)

Distribution Update Status Manager (distro\_update)

Draggableviews (draggableviews)

Empty Front Page(empty\_front\_page)

Enabled modules (enabled\_modules)

Entity Reference Autocreate(entityreference\_autocreate)

Entity reference autofill addressfield(entityreference\_autofill\_addressfield)

Entity reference autofill OG(entityreference\_autofill\_og)

Entity Reference Drag & Drop(entityreference\_dragdrop)

Exclude node title(exclude\_node\_title)

Features Diff (features\_diff)

Field group multiple(field\_group\_multiple)

Field reference (field\_reference)

Field tools taxonomy(field\_tools\_taxonomy)

Field tools (field\_tools)

Fieldable Panels Panes(fieldable\_panels\_panes)

FileField Sources Plupload(filefield\_sources\_plupload)

Google Analytics (googleanalytics)

Hidden CAPTCHA (hidden\_captcha)

Image CAPTCHA (image\_captcha)

Image URL Formatter(image\_url\_formatter)

IMCE plupload (imce\_plupload)

jQuery Countdown Timer(jquery\_countdown\_timer)

Media WYSIWYG (media\_wysiwyg)

Media: oEmbed (media\_oembed)

Menu Block (menu\_block)

Mime Mail (mimemail)

Module filter (module\_filter)

Multifield table (multifield\_table)

Organic groups access control(og\_access)

Organic groups field access(og\_field\_access)

Organic groups register(og\_register)

Panels In-Place Editor (panels\_ipe)

Payment UI (commerce\_payment\_ui)

PHP filter (php)

Rules Scheduler (rules\_scheduler)

Session Room - Schedule validation (validate\_session\_booking)

Statistics (statistics)

Stylizer (stylizer)

ThemeKey UI (themekey\_ui)

# Answer
Make sure you rebuilt the permissions first.

If the issue still exists, first check the permissions at `/admin/people/permissions` page. If the desired roles don't have required permissions for those fields.

For what you ask, create/edit/delete permissions must be given to desired roles.

Also check "Organic Group" settings. Field permissions might be misconfigured. This is more likely the issue.
> 0 votes

# Answer
*If the previous two answers don't apply;*

Third possible solution might be related with Conditional Fields.

Make sure to check all fields for their settings. Check if any of them has conditions defined making them available only on edit page, but not on create page as well.
> 0 votes

---
Tags: 7, organic-groups
---


# Question
Title: Migrating data from a CSV source: Where should the source go?
I'm trying to do a migration of an old (and full of nodes and comments) D7 site, to a Drupal 8 brand new one.

In order to import only the contents, I'm trying to do the migration from a csv file (with the stuff that I've exported using views).

My question is, how to set the source? Full path? I'm using a test csv file and I put it at the root folder, at the same place where the index.php file is.

I tried this:

```
source:
  plugin: csv
  path: 'http://www.example.com/myfile.csv'
...

```

And this:

```
source:
  plugin: csv
  path: '/myfile.csv'
...

```

(with and without the slash)

I keep receiving this error when I try to run the migration script:

> ```
> An AJAX HTTP error occurred.
> HTTP Result Code: 500
> Debugging information follows.
> Path: /batch?id=20&op=do_nojs&op=do
> StatusText: Internal Server Error
> ResponseText: The website encountered an unexpected error. Please try again later.
>
> ```

What should I do?

# Answer
Please add the file as :

```
source:
  plugin: csv
  path: 'public://csv/test.csv'

```

And under sites/default make a folder named as csv and place the file inside that. It will work.
> 4 votes

---
Tags: migrations
---


# Question
Title: D7 - Rules System Page Redirect not working at all?
I've been trying to add action Page Redirect to my rule (after a coupon code is applied to an order), and it doesn't work in any scenario? I did a bit of digging and it seems this is common - anyone know why it's happening/what the fix is?

# Answer
First things first: a page redirect from "current page" to "current page" is what seems to be your very last Rules Action, is that what you actually want? If that's not your issue, then read on about a possible approach to find out what else might be wrong.

# Basic debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my **K**eep-**I**t-**Super**-**S**imple technique I often use is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Also, since you have 2 Rules Conditions in a single rule (both must be satisfied for your Rules Actions to execute), you should try to see what happens (if you get a "bingo") for each of the individual Rules Conditions. This by simply (temporary) removing 1 out of the 2 Rules Conditions you are using, and verify if they each result in the Rules Action you'd expect (also just a simple Bingo-message should be sufficient).

# Advanced debugging

Something else that will help you find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your `node:comments`).

For way more details about these 2 variations, refer to **Rules debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".
> 1 votes

---
Tags: 7
---


title: Block view contextual filters

text:
# Question
Title: Block view contextual filters
**What I want to achieve**

I need to create a single view to display latest content of each content type. And I have content type: Article, Basic page.

**What I do**

I have create a View with a display Block called *Latest content by Bundle*. In this view, I add Contextual filters Content: *Content type*. I set *When the filter value is not avaiable* to *Provide default value: Content ID from URL*.

I try the view preview, type the value `article` and it display the articles content. I then go to Block layout, place the block view that I created to a region.

**My problem**

When I configure the Block view, there are option to select content type, but the dropdown item is empty.

I'm expecting list of content type displayed. Is this correct? Or there are something that I miss?

# Answer
> 0 votes
I don't think you can pass an argument into a block like that.

However, you can do it with page manager.

* Skip the next screen (click next)
* Set up a context like this

* Skip the next two screens (click next)
* Add your view block like this

* Now go to `<your_url>/latest/article` and the page should list your articles
* You can add other pages/contexts for other content types

---
Tags: views, 8
---


title: Image block module translate

text:
# Question
Title: Image block module translate
I have created block using image block module. I want to translate block content in other languages. I have used i18n module for translation. currently I only translate the title of the block. But I also want translate body content. So,please anyone help me. Thanks in advance

# Answer
I believe the image block module is not yet fully compatible with i18n module and you will need to apply the patch in this issue which according to the posters is reviewed and ready to be committed.

**Alternatively** you can install nodeblock and create a content type (i.e. *block*) and use it as a nodeblock and you will get all the benefits of *nodes* and *blocks*. Therefore you can add image fields or any other fields that you need and after creating a node of that content type you will be able to add it in a region of your theme like a normal block. Nodeblock supports translatable content (Contrent translation with i18n and Entity Translation).
> 1 votes

---
Tags: 7, blocks, i18n-l10n
---


# Question
Title: Remove default language prefix from URL in Drupal 7
I have started to create a website using Drupal 7. I have website to use multi-language functionality. How do I remove default language prefix from URL.

# Answer
You can modify the language prefix for an enabled language by going to *Configuration \> Regional and language \> language* and then pressing *edit* on the desired lanaguage. On edit form you can edit *Path prefix language code* and *save language*.

**NOTE:** english by default does not have a prefix, other languages should have a prefix if you are using *URL* as a *detection method* in `admin/config/regional/language/configure`. *URL detection method* is customary to be used in multilingual sites or you might end up with same paths for translated pages (i.e. `/contact` in english `/contact` in french)
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: how to get the url to usefor a private path
if I have a file saved in private:://somefile.txt , what function can I use in drupal to give me the external URL to access that?

I tried `PrivateStream::getExternalUrl()` but I get this error

`PHP Fatal error: Call to undefined method Drupal\mymodule\myservice::getTarget() in /opt/DrupalSites/drupal-wcms-migration/docroot/core/lib/Drupal/Core/StreamWrapper/PrivateStream.php on line 50`

# Answer
You can't call `PrivateStream::getExternalUrl()` directly because it's not a static function; it needs an instantiated stream before you can call `getExternalUrl()` on it.

You can retrieve it via the stream wrapper manager's `getViaUri()` method:

```
$stream = \Drupal::service('stream_wrapper_manager')->getViaUri('private:://somefile.txt');
$stream->getExternalUrl();

```
> 4 votes

# Answer
You don't have to call getExternalUrl() directly either, you should just use file\_create\_url('private://somefile.txt').

There is no OOP version of it yet, this is being worked on.
> 0 votes

---
Tags: 8, stream-wrappers
---


title: Run code when a session ends

text:
# Question
Title: Run code when a session ends
Is there a hook or something similar that triggers when a PHP session ends?

When a user signs in, I'm writing a few things to the cache, and I need to delete them from the cache when the user exists the site. If the user manually logs out, that's no problem, but I still need to clear that data when users close the browser.

# Answer
Drupal doesn't have hooks that are invoked when a session ends, probably also because the code would not be able to understand if the session cookie is not present because it expired (which means the session ended) or because the browser has not been used to log in on a Drupal site.

Drupal invokes a hook when the user is logged out, either because the user clicked on the *Log out* link, or because the user was forced to log out, which is what happens when the site is in maintenance mode and the account isn't exempted from being automatically logged-out.
Drupal 7 and Drupal 8 invoke `hook_user_logout()` when the user is logged-out, and the code invoking the hook also destroys the user session.

Since you are talking of cache to clear, if you are using Drupal 8, you can also investigate if there are cache tags or contexts that tell Drupal to invalidate the data when the session is destroyed.
Cache contexts lists session.exists as context that can be associated to cache data. I didn't test it, but from the context name, I take it invalidates the cache data when the session doesn't exist, which is what you are trying to achieve. (See also Cache API for more information on cache tags and cache contexts in Drupal 8.)

As side note, a Drupal session doesn't normally end when users close their browser. It would happen when using an incognito window with Google Chrome, or the equivalent of other browsers, but when you are not using that, the session doesn't end when the browser is closed, or when the browser tab is closed. (If that were to happen, it would mean logging off the users.)
> 1 votes

# Answer
There is no Drupal hook for session management. The closest thing \[to inserting your own custom code in session management\] is overriding core session management functions.

While you could simply copy/paste/override (existing session management code) to hook into execution, you should consider an alternative seeing how session cache cleanup can be performed without hooking into session management (e.g. cronjob, etc).
> 0 votes

# Answer
There is no possible way you can know when a user closes the browser. But as a general rule if something is written to cache, it should be disposable, and can be regenerated on demand if necessary. Cache is not meant for data that has any value in itself.

Assuming that is the case here, what you need to do is to ensure your cached items expire after a while. Use a timestamp value for the expiry option of cache\_set() for Drupal 7 or CacheBackendInterface::set() for Drupal 8.
> 0 votes

---
Tags: sessions
---


# Question
Title: How to automatically populate a field with a value part of another field
I will try to be as specific as possible.

I have a required text plain field in a content type, say 'field\_A'. This will have values of minimum 2 words, maximum 5 words. **Words will be separated by spaces**. I can be certain of this.

What I want, is to have another field, say 'field\_B' in which I want to keep the **last word of field\_A**. I would like this to happen automatically (upon creation of a node of this type).

I have no idea if this is possible ...

So, say I 'm adding new content of this type, and use value "lorem ipsum whatever" for field\_A, upon submitting I would like the word 'whatever' to be inserted as a value in field\_B.

I 'd be grateful of any help .. I couldn't find relevant info on this, it's kinda hard to describe in a few words.

Working on D8.

# Answer
You probably need a custom module for this.

Add `MODULENAME` directory inside your `modules` directory. Inside the directroy create file `MODULENAME.info.yml` with contents:

```
name: Last word copy
description: 'gets last word from field_a and saves it to field_b'
core: 8.x
type: module
package: COMPANYNAME
dependencies:
  - node

```

This module implements `hook_form_alter` that will make *field\_b* readonly / disabled and `hook_entity_presave` which will get the last word added to `field_b` upon save or update of a node of *CONTENTTYPE*

Create also `MODULENAME.module` file with contents:

```
<?php
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if(in_array($form_id,['node_CONTENTTYPE_form','node_CONTENTTYPE_edit_form'])) {
    $form['field_b']['#disabled'] = 'disabled';
  }
}

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if($entity->bundle() == "CONTENTTYPE"){
    $pieces = explode(' ', $entity->field_a->value);
    $last_word = array_pop($pieces);
    $entity->field_b->value = $last_word;
    //save is done automatically
  }
}

```

You NEED to replace *MODULENAME* and *CONTENTTYPE* in the above code.

If all is correct go to *Extend* (admin/modules) and enable the module.
> 3 votes

---
Tags: 8, entities
---


title: Routing for dependent entities

text:
# Question
Title: Routing for dependent entities
Assume we have two entity types with a 1:n relationship, e.g. an Event type that has a number of Participants that belong to that type. I have implemented this such that Participant has an entity\_reference field that specifies the Event.

Now I would like to change the dependent (Participant) entity's add\_form route, so that I can easily add Participants to an Event:

```
@ContentEntityType(
    id = "participant",
// ...
  links = {
    "add-form" = "/admin/structure/event/{event}/participants/add",
// ...
  },

```

I've managed to make this work on the AddForm. But now I get lots of routing errors like this in other places (such as when deleting a participant entity):

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("event") to generate a URL for route "entity.participant.add\_form".

The add\_form route comes from DefaultHtmlRouteProvider. I've tried overriding it with a static route that includes a default value:

```
entity.participant.add_form:
  path: '/admin/structure/event/{event}/participant/add'
  defaults:
    _title: 'Add participant'
    _entity_form: participant.add
    event: NULL

```

but this doesn't work – page not found.

What would be the best way to supply a default value, or is there a better way to handle this kind of entity relationship?

# Answer
A default value does not work in this case, as - strangely - this will override the context provided event id. Some default entity methods, such as delete, seem to require the route URLs and therefore fail when the parameter is not given.

The add\_form route, which is automatically created by DefaultHtmlRouteProvider from the @ContentEntityType annotation, causes problems here. The easiest solution is probably to remove this route by deleting the line

```
"add-form" = "/admin/structure/event/{event}/participants/add"

```

from @ContentEntityType (under "links") – do not remove the add form in section "form" – and providing the route in `modulename.routing.yml`:

```
entity.participant.add_form:
  path: '/admin/structure/event/{event}/participant/add'
  defaults:
    _entity_form: participant.add
    entity_type_id: 'participant'
    _admin_route: TRUE
  requirements:
    _entity_create_access: 'participant'

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to send multiple emails after creating a node
I'm using SMTP module to send e-mail messages after creating nodes. It takes about 3-4 seconds to send each such message using hook\_node\_insert. So if I want to send 10 messages, then I have to wait for 30-40 seconds for the iteration to complete and then only I get redirected to create new node. **It's very slow**.

I tried use event KernelEvents::TERMINATE per this article, but it did not speed up the whole process.

Is there a way just to complete creating a node without waiting and immediately proceed to creating a new node, while sending e-mail messages at the same time?

**Note: I don't want to create queue and wait for the next cron run to send e-mails. Because e-mails need to be sent instantly after creating respective node**

# Answer
> 2 votes
As noted on the Reddit thread, this event will not work as described in this blog unless you are using PHP FPM. For most hosting providers this is the default setup. So, if you are using Apache with mod\_php you are out of luck, it seems.

Are you hosting with Apache and mod\_php? You'll need Apache and use PHP FPM with some settings changed. Or use nginx.

Sounds like the problem is due to your server not streaming the output. Per the Symfony docs

> Internally, the HttpKernel makes use of the fastcgi\_finish\_request PHP function. This means that at the moment, only the PHP FPM server API is able to send a response to the client while the server's PHP process still performs some tasks. With all other server APIs, listeners to kernel.terminate are still executed, but the response is not sent to the client until they are all completed.

https://symfony.com/doc/current/components/http\_kernel.html#the-kernel-terminate-event

---
Tags: 8, emails
---