# Question
Title: Why is my $node always null in my custom block (using plugin contexts)?
I am trying to make a block that gets the current node via Plugin Contexts.

But my `$node` is always null. Can anyone tell me why?

I am placing the block with the context module if that makes a difference?

```
<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header' block.
 *
 * @Block(
 *   id = "header",
 *   admin_label = @Translation("Header"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
 */
class ProductStickyHeader extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $node = $this->getContextValue('node');
    // $node is always null!

    return $build;
  }
}

```

Many thanks!

# Answer
Thanks everyone - turns out the answer was deceptively simple - I had to remove the block using context & then re-add it. When I re-added it there was an extra option in context to use the current node. Then the context plugin worked!
> 2 votes

# Answer
The most common way to get the current node in a block is to use the route parameters. E.g.:

```
$node = \Drupal::routeMatch()->getParameter('node');
if ( $node == NULL || $node->getType() != 'blog_post') {
  return;
}

```
> 0 votes

---
Tags: 8, blocks, plugins
---


# Question
Title: How to override default template files of a view
I have to implement my custom markup in a view. How I can override the markup for the views header, footer, and attachments? Which TPL files I have to modify and how will be its machine names. Which also respects keeping the templates of the other views unchangeched.

# Answer
> 1 votes
If you have a view called `foobar` than you can create this tpl file in your templates/views directory:

`views-view--foobar.tpl.php`

Then change `foobar` to whatever your view is called and then clear the cache.

To create custom variables to your view create a `hook_preprocess_views_view` in your template.php file, like this:

```
function template_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  $vars['foobar'] = 'Hello World';
}

```

Now you have a `$foobar` variable in your template.

# Answer
> -1 votes
To override a view you need to write three template files. Below are the files:

1. views-view--search-page.html
2. views-view-unformatted--search-page.html
3. views-view-fields--search-page.html

To know exact names of template files, you can even use Devel module to find out the suggested names.

Location of these files will be : \themes\bootstrap\templates\views\ \[place-your-files-here\]

After you create your files, clear drupal cache for the code in twigs to be reflected.

---
Tags: views, theming
---


# Question
Title: Alter menu link path based on content type
I'm stumped on how to achieve this in Drupal 8 due to the removal of menu related functions. What I would like to do is check whether a menu link points to a node of content type File, and then alter the link path to point to a File field value on node (so that the menu link points to the file itself). I just need help getting to the point where I have both the path/route and the node object. I have tried to do this in `menu--main.html.twig`, where I *can* get the node id for each menu item. However there does not seem to be a way to load a node object through Twig and even if there were, I doubt this is the correct way to go about this.

I have found tutorials pointing me to implement `alterRoutes()`, for example:

```
public function alterRoutes(RouteCollection $collection, $provider) {
  // Find the route we want to alter
  $route = $collection->get('example.route.name');
  // Make a change to the path.
  $route->setPath('/my/new/path');
  // Re-add the collection to override the existing route.
  $collection->add('example.route.name', $route);
}

```

This doesn't seem helpful because I do *not* want to alter the route to the node whenever it is visited. I only want to alter the route when it is visited *from the menu*.

# Answer
wow I feel silly. You can still preprocess the menu template in Drupal 8. So by using `hook_preprocess_menu__main()` it looks like I will have access to everything I need and not have to do everything in the Twig template.
> 1 votes

---
Tags: 8, routes, navigation
---


# Question
Title: How to access all images uri in node's field in custom module?
I already know I can get an url for field of node this way:

```
$src = file_create_url($node->get('name_of_image_field')->entity->uri->value);

```

The problem is, my field `name_of_image_field` has multiple images. **How to access them all?**

# Answer
You can try this code:

```
$img_urls = array();
foreach ($node->field_image as $item) {
  if ($item->entity) {
    $img_urls[] = $item->entity->url();
  }
}

```

Then all `field_image` image urls available in `$img_urls` variable.
> 4 votes

# Answer
```
$srcs = array();
// Loop through the Languages
foreach ($node->field_image as $items) {
  // Loop through each item in each language
  foreach($items as $item) {
    if ($item->entity) {
      // Set the path as the key, to prevent duplicates
      $srcs[$item->entity->url()] = $item->entity->url();
    }
  }
}

```

$srcs will contain an array web-accessible URLs for every image attached to every language of the node.
> 4 votes

# Answer
Maybe you could use:

```
$delta = 0;
$file_item_list = $node->field_image;

if ($file_item_list && $file_item_list->offsetExists($delta)) {
$image_url = file_create_url($file_item_list->offsetGet($delta)->get('entity')->getValue()->getFileUri());
}

```

Check Class FileFieldItemList for more details.
> 0 votes

---
Tags: nodes, 8, uri
---


title: Add CSS class to unpublished node items

text:
# Question
Title: Add CSS class to unpublished node items
I am showing nodes from a 'news' content type in a view. In this view I want to add a CSS class to the unpublished items. So, am I able to style (e.g. red background color) on the unpublished items?

How can I do this? Is there a way to write a hook in `template.php`?

# Answer
> 0 votes
See if this works for you. In your theme's template.php:

```
function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}

```

You need to define classes\_array with whatever classes you need to be added.

---
Tags: views, theming, nodes, hooks
---


# Question
Title: How to restrict group node access to a user/member of an group?
I am using the Group module and I have created a group called "Group-Y" and group type "Group-type-Y". I also defined a group role name "Admin". Added an member with role "Admin".

I have checked this module, which provided the access based on page,

https://www.drupal.org/project/page\_access

Page access module does work with global user admin, like here:

I tried to achieve it for group admin. In the edit node, page access settings are not displayed.

I need to achieve to restrict node based on user/role in a group. Can anyone help me out?

# Answer
> 1 votes
It seems to me that, for what you're trying to achieve, you do not need the "Page access" module. Instead only using the Group module it should be possible to get it to work.

Some basics about the Group module to be aware of:

* Make sure you enable `gnode`, a submodule of the Group module.
* For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
* Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

It seems that you would want to grant access to what, in Group, is called "Members". But you woudn't allow access to "Anonymous" (site visitors that are not logged it). However, you also need to think about which access you want to give to "Outsiders" (= logged in users who are not a member of a group).

With the above in place, it's just a matter of assigning a node to a Group. So if the `gnode` submodule is enabled, you should be able to do so via a group-related field that will be shown on the node edit form, via which you can then select the appropriate group

### More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more info about all this.

---
Tags: nodes, group
---


# Question
Title: How to get product image URL from product page?
I'm developing a module for Drupal Commerce - Drupal 7 and I need to get the product image URL from product page but I couldn't find a solution for this.

I'm successfully fetching the product name, title, url but not the its image URL which really bothers me as I am used to WooCommerce where there is a very simple way of getting the image URL.

# Answer
I have found a quick fix for this issue.

```
$product = commerce_product_load($productId); // loads the product by id
$productImage = drupal_json_encode(file_create_url($product->field_images['und'][0]['uri'])); // gets the main image of the product if it has multiple images and formats the link properly

```
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Error viewing articles/pages after assigning
As an experiment I've merged core from 8.3.x branch to try out workflow. After successfully assigning 'editorial workflow' to articles and pages, I cannot access the pages or articles anymore neither to read them as a guest or to edit them as an admin.

Visiting /admin/reports/status, I see this error:

> Mismatched entity and/or field definitions
> The following changes were detected in the entity type and field definitions.
>
> * Comment
>
> The Publishing status field needs to be updated.

My expectation is that the existing entities needs their workflow states to be set, but I expected the workflow module to automatically assign 'published' state to published articles. How can I fix that?

I was wrong about that this was only happening with existing articles. Another article after been created as well started behaving the same.
This was the error from log:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'content\_moderation\_state\_field\_data.workflow' in 'where clause': SELECT base\_table.revision\_id AS revision\_id, base\_table.id AS id FROM {content\_moderation\_state} base\_table INNER JOIN {content\_moderation\_state\_field\_data} content\_moderation\_state\_field\_data ON content\_moderation\_state\_field\_data.id = base\_table.id WHERE (content\_moderation\_state\_field\_data.content\_entity\_type\_id IN (:db\_condition\_placeholder\_0)) AND (content\_moderation\_state\_field\_data.content\_entity\_id IN (:db\_condition\_placeholder\_1)) AND (content\_moderation\_state\_field\_data.workflow IN (:db\_condition\_placeholder\_2)) AND (content\_moderation\_state\_field\_data.default\_langcode IN (:db\_condition\_placeholder\_3)); Array ( \[:db\_condition\_placeholder\_0\] =\> node \[:db\_condition\_placeholder\_1\] =\> 8 \[:db\_condition\_placeholder\_2\] =\> editorial \[:db\_condition\_placeholder\_3\] =\> 1 ) in Drupal\Core\Entity\EntityStorageBase-\>loadByProperties() (line 503 of \core\lib\Drupal\Core\Entity\EntityStorageBase.php)." Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE…

# Answer
> 0 votes
Missing column of the contrib module indicates the corruption of the database. In your case `workflow` field is missing in `content_moderation_state_field_data`.

If this error start happening after upgrade, try running *Database Update* (either by going to `/update.php` or running `drush updb` command).

There is a Unofficial content\_moderation 8.2.x to 8.3.0 upgrade path which can also help. It has relevant patches for `content_moderation` module with update hooks, which will migrate the tables accordingly.

Otherwise you'll have to reinstall the module, so its tables are re-created from scratch.

---
Tags: nodes, 8, workflows
---


# Question
Title: Ajax fields do not work on custom page with `drupal_render`
From my module `test` I render the create node form on URL `admin/test` using the following:

```
function test_menu() {
  return array(
    'admin/test' => array(
      'title' => 'test',
      'access callback' => '_test_access',
      'page callback' => '_test_render',
      'type' => MENU_LOCAL_TASK
    )
  );
}

function _test_access() {
  return true;
}

function _test_render() {
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('my_content_type');
  return array(
    'whatever' => array(
      '#type' => 'markup',
      '#markup' => drupal_render($form),
    )
  );
}

```

Form works well and can create a new node of type `my_content_type`. The problem is that some fields where ajax is involved give me the following error when pressing "Add Items":

> Error: Call to undefined function node\_form\_validate() in form\_execute\_handlers() (line 1520 of /webapp/includes/form.inc).

The details of those fields are:

* Field type: Entity Reference
* Widget: View
* View display type: Entity Reference View Widget

# Answer
Solution can be found at Embed a "node add" form in a page. You have to implement hook\_menu\_alter() for ajax calls.
> 1 votes

---
Tags: views, ajax, debugging
---


title: Adding a token to a views block title

text:
# Question
Title: Adding a token to a views block title
I am displaying some view blocks on a page. The content is being filtered by passing the nid from the url into some custom php. I wish to change the block title to use a field from the node in question. Is this possible?

# Answer
For Views 3 , the given answers are partially incorrect. Tokens are allowed in the header area of view blocks. The only tokens available are for the fields used in the view. So you can set the field that will be used only for its token to hide.

You have to select the *Global: Text area* option in *Header*, check *Use replacement tokens from the first row* and select the token from the *Replacement Patterns* dropdown.
> 4 votes

# Answer
In the current version of Views (3.14), you can write tokens in the view title.

It doesn't say so in any help messages, but I have tested it on https://simplytest.me and it worked.

You can see the available token names by selecting the last field and activating `Rewrite the output of this field` and folding out `Replacement patterns`.
> 3 votes

# Answer
I don't believe this is possible from the Views UI.

You could do this by creating the title using `[theme_name]_preprocess_block` hook in your theme. You might also be able to set the block title in a preprocess hook for the view, but I don't know which one you should use.
> 1 votes

# Answer
This is not possible because views doesn't allow you to used tokens.

That being said it is technically achievable. When you say you pass the nid into some custom php. What do you mean? Does the view use the nid as an argument? or are you returning something else.

The real question is are you actually filtering the content by the field? If you happend to be passing in the nid, doing a node load, then filtering on that field then this is indeed possible. I'm just guessing this is what you're doing. I might be wrong.

If you happend to actually be filtering by the field, then when you edit the argument you will see there's an option to override the title. You should be able to use %1 or %2 depending which argument is the field value.

Note I'm making a lot of assumptions on this answer. So again, this is only possible if the value you're actually filtering on is the field.
> 1 votes

# Answer
I understand that each views returns a single node displayed in a block and you want to change the title of this block. You could easily do this with a tricky trick :).

* Build your view with all the fields you need, don't put it a title
* Select the node title field and select "rewrite output", put the field token in the textarea with `<h2>`: `<h2>[field_FIELDNAME_value]</h2>`
* Don't put a title to your block with `<none>`

Normally with this you should see your block with the title of the node returning by your view styled like a block title due to the presence of the `<h2>`, a little more CSS to polish and you're done.
> 0 votes

# Answer
It is easy. In the title of the block you only have to add the token, that if, this field obviously must exist in your view, rewrite the field output to be able to get the name of the token and copy and paste in the title of the block.
> 0 votes

---
Tags: views, 6, blocks
---


# Question
Title: How to create dynamic contents with view
I have to create some different pages in Drupal 7.
I need a different header and a custom text for the pages appearing in the same block, so I thought that it would be useful to create a view.
I did not develop that website, is it the right way to do that?

I will explain it better.
I have to do 4 landing pages with the same structure.
I created a webform block for the right block. It will be the same on the four pages. Now I want to create two more blocks, one for the header and the other one for the text. I'd like to change the block content in the different pages.
How can I do it?

# Answer
There are multiple ways to implement this. Either by creating a new content type landing pages and set a specific template file only for this content type (I think this is the most strait forward option), or you can create a view with multiple pages (if you want to work with views) and again create a specific template for the view. Also I think that you could use the panels module and create your landing page with custom layout.
> 0 votes

---
Tags: 7, views
---


# Question
Title: What happened to the links to import or export a View?
In Drupal version 7, within the overview of all Views available in a site (located at "`admin/structure/views`"), for each view there are these options (links) at the very right after each view:

* Enable (if view is disabled) or Disable (if view enabled).
* Edit.
* Delete.
* Clone.
* **Export**.

And near the top there is also an "**import**" link.

However, in Drupal version 8, on the equivalent page (also at "`admin/structure/views`"), there is no more link like **export** or **import**.

So what happened to importing/exporting of a view in D8?

# Answer
> 4 votes
That Views import/export facility is **no longer available in Drupal version 8** (within "`admin/structure/views`") ...

A possible way to do similar Views imports/exports in Drupal version 8 is to use the new configuration management facilities, which can typically be used to migrate configuration items, such as Views, between **related** dev, staging and production sites.

So it appears to me that as of right now (8.0.5) there is no "***easy***" way (as it used to be in Drupal version 7) to do such imports/exports between 2 sites that are not "related". Except probably/maybe with some special manual editing to make the site Ids match somehow.

Though according to Berdir's comment below (excl. some typos), "***that's not true. You can use single import/export of any configuration file between any site, as long as you take care of the dependencies as well. The related site/UUID checks only apply to a whole config sync.***". And followed by the `/admin/config/development/configuration/single/import` suggestion (merci Berdir).

Maybe an opportunity for a new D8 contributed module to bring this import/export facility back ... and/or one of the "*reasons to be*" for the Features module in D8 (as suggested in another comment by Danny Englander) (merci Danny).

PS: For some more info about `/admin/config/development/configuration/single/import` mentioned above, refer to the Community documentation about "Managing configuration in Drupal 8". Part of what is included on that page is like so (bold markup added here):

> It is possible to export a single configuration file and paste it into another **environment**. The single import option lets you specify the type of the configuration file and import it from your copy-pasted value.

Though nowhere on that page I could find an indication if using "environments" for which site Ids are different (for "single" imports) is allowed or not.

If you want to get an idea of how it is like to use these import/export features, then have a look at the slideshow "The Magic of Drupal 8’s Configuration Management on a Managed Workflow" (especially slides like on page 44 to 48).

# Answer
> 0 votes
You have to install Configuration Manager module . Then, go to **admin/config/development/configuration/single/export** and get your yml file.

---
Tags: views, 8, importing-exporting
---


# Question
Title: Is there a better way than twig files overwrite?
In my project, I have a " field--node--title.html.twig " file, I used this file to overwrite the title label to be able to give it a certain class.

I know you can be more specific using " field--node--title-x.html.twig ", Where x can be a block or a page!

I was wondering if there exists a better way of doing this. Maybe I could do IF conditions inside " field--node--title.html.twig " file to check for a certain block or a certain page.

This would be much easier and it would also decrease the number of files in the field folder in templates.

# Answer
> 1 votes
Yes, usually there is a better way: preprocess functions allow you to alter the render array that is passed to the twig template. Adding a class is, in most cases, possible, but you might need to check how the twig file is turning the render array into markup.

This article has more info: https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file

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


# Question
Title: View doesnt work properly when logged out
I have a question about a problem I met. I'm working on Drupal 7 site that has a menu made with a view but for some reason the structure of menu is totaly different when user is logged in than when the user is logged out. Everything works fine when I'm logged as admin but when I logged out it seems like some of configurations doesnt load. I don't have any errors in console.

I\`m not sure what kind of informations from view I can share or will be usefull so I will add every need informations which you asked for.

Adding a code from inspect: Image with both inspects

# Answer
A possible cause is that anonymous users don't have access to the content or fields. The inspect images aren't helpful to determine what permissions could be missing. In the UI, go to *People \> permissions* and check that:

* Anonymous users can see published content
* If there are field-level permissions, anonymous can see all the fields involved in the view
* There aren't restrictions to access the view (this is unlikely, the view wouldn't render at all)
> 0 votes

---
Tags: views
---


# Question
Title: How to set or get the triggering element upon submit a form using JQuery?
I have a Drupal 8 form with checkboxes. The form submits upon clicking on a checkbox using JQuery.

Here is my code.

```
 $('#edit-event-types input[type=checkbox]').on('change', function(event, ui){
    $('#events-to-doc').submit();
  })

```

Unfortunately, if there isn't any submit button in the form, then function submitForm in the form class doesn't execute. But I don't need in a submit button on the form, I want to submit the form clicking on the checkboxes.

Can I somehow set the checkboxes element as the triggering element with Jquery? I need the function submitForm to execute and $form\_state-\>getTriggeringElement() return the checkboxes as the triggering element.

# Answer
Submit buttons (and their names) are special for Drupal. I'm not sure how this changed in D8, but in D7, the submit button name was used (IIRC) to determine which one was clicked.

I would suggest adding the submit button, hiding it with CSS and triggering a `.click()` to the button instead of doing `.submit()` directly. You can then either get the checkbox value if that's enough, or use a hidden field and some JS to determine which checkbox triggered the submit event (last clicked checkbox).
> 2 votes

---
Tags: 8, forms, javascript
---


title: Remove count from glossary view

text:
# Question
Title: Remove count from glossary view
I have a situation where I need to remove (via client request) the letter count in the header of a view based on Glossary view. How might I remove the numbers (in parenthesis)

Previous question history: Paginate views by first letter of Node title

# Answer
> 1 votes
Copy `views-view-summary-unformatted.tpl.php` to your theme and edit the file and remove line 17 `(<?php print $row->count; ?>)`

or wrap line 17 `(<?php print $row->count; ?>)` with a span and hide it using css

```
<span>(<?php print $row->count; ?>)</span>

```

# Answer
> 5 votes
* Go to the Attachment details of the Glossary view
* Under Contextual Filters (you may need to click Advanced to see it) click on "Content: Title"
* Uncheck "Display record count with link"

# Answer
> 0 votes
Since I can't comment, I have to add an answer. I agree with Bill's answer. This also works for Drupal 8 and no code change is required. De-selecting "Display record count with link" will remove the parenthesis.

---
Tags: views
---


# Question
Title: Using hook_user_format_name_alter(), how to change username on user paths?
I am using `hook_user_format_name_alter()` to change the way usernames are displayed through my site.

However, on the user paths:

* user/UID
* user/UID/edit

The page title is set to the **username**, not the result of `hook_user_format_name_alter()`.

Is there an easy way to override the username here (and preferably anywhere else) and replace it with `hook_user_format_name_alter()`?

My goto solution would be the Real Name module, but I ran into a bug so I'm trying to do this programatically myself.

# Answer
> 2 votes
This is the title callback you have in core for /user/UID:

*UserController::userTitle*

```
/**
   * Route title callback.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   *
   * @return string|array
   *   The user account name as a render array or an empty string if $user is
   *   NULL.
   */
  public function userTitle(UserInterface $user = NULL) {
    return $user ? ['#markup' => $user->getUsername(), '#allowed_tags' => Xss::getHtmlTagList()] : '';
  }

```

Unfortunately this uses the method `getUsername()`, which doesn't invoke hook\_user\_format\_name\_alter().

You need a custom title callback, where you get the username with the method `$user->getDisplayName()`, which does invoke the hook.

Then change the title callback in the user route `entity.user.canonical`:

```
$route->setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::userTitle');

```

See https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones.

---

Had the feeling this can't be right and searched for an issue: https://www.drupal.org/node/2648420. This is committed for D8.5. Until then you can apply the patch, which simply replaces getUserName() with getDisplayName() in UserController.

---
Tags: 8, users, hooks
---


# Question
Title: Need to migrate large, complex Drupal 6 site to Drupal 8. Suggestions for a good way to tackle this if the core Migrate Upgrade doesn't work for me?
I have a lot of experience with Drupal 5, 6 and 7 and am just starting with Drupal 8 and I have a large, complex Drupal 6 site that I need to migrate to D8.

I first tried using D8's Migrate Upgrade but it fails part way through. I didn't have high hopes for this to work but I thought if it could at least get the users and bulk content in then that would be a great starting point. It was unable to accomplish either.

So now I'm going to go the export/import route and try to rebuild the data manually. I've done this a number of times upgrading D6-\>D7 using XML Views to create the export and Feeds to map and import. It looks like Feeds is nowhere near ready for use yet.

**Is using core Migrate module along with other contrib modules to right approach? Is what I'm trying to do even possible?**

If so, could anyone point me in the correct direction to get started? I've heard migration plugins mentioned before, I'm assuming that I'll have to create custom migration plugins to make this work, correct?

# Answer
I guess it depends on what your Drupal 6 does and contains. It's not the same if your complex site has lots of content but little functionality (a large blog, for example), or if it has some or lots of content AND complex functionality (news site publishing workflow with rules, complex permissions, etc). Every case is different.

If what you have is lots of content, this could apply: I recently moved lots of content (around 26k items that became nodes) from a Frankenstein WordPress-based app, and found the following approach useful:

Do exhaustive pre-production:

* Make an inventory of everything you have in your old site. Mark what is valuable and what is not.
* Based on that inventory, design the entities, fields, taxonomy and relationships that will contain them in your D8 instance.
* Make a detailed migration map that makes it explicit how each fragment will map to its new location, and what will be left behind / lost.

Then implement your migration tools:

* Export your content (the things you decided are worth migrating) to XML, JSON, or whatever format you feel more comfortable with.
* Instead of messing with migration modules, I wrote several drush scripts that read from the old app's db, extract items and save them into entities.
* The scripts had reset, migrate\_all and type-specific migration routines that helped me test again and again and again, until everything was just right.
* Automate everything and make it easy to clear and repeat. There are lots of things that can go wrong, but it's not a problem if you can simply `./reset.drush; ./migrate_all.drush`.

Hope this helps.
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: Why wont drupal recognize my base table name?
So I have been playing around with the poll module in Drupal8-beta14 and I just upgraded the site to RC1. I am trying to uninstall the poll module now but i get this error everytime

```
exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown      [error]
column 'base_table.id' in 'field list'' in
/srv/www/dtadev2/core/lib/Drupal/Core/Database/Statement.php:64

```

the only place i can find the string "base\_table" in the poll module at all is in the @ContentEntityType annotation

```
 @ContentEntityType(
 *   id = "poll",
 *   label = @Translation("Poll"),
 *   handlers = {
 *     "access" = "\Drupal\poll\PollAccessControlHandler",
 *     "storage" = "Drupal\poll\PollStorage",
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler",
 *     "list_builder" = "Drupal\poll\PollListBuilder",
 *     "view_builder" = "Drupal\poll\PollViewBuilder",
 *     "views_data" = "Drupal\poll\PollViewData",
 *     "form" = {
 *       "default" = "Drupal\poll\Form\PollForm",
 *       "edit" = "Drupal\poll\Form\PollForm",
 *       "delete" = "Drupal\poll\Form\PollDeleteForm",
 *       "delete_vote" = "Drupal\poll\Form\PollVoteDeleteForm",
 *       "delete_items" = "Drupal\poll\Form\PollItemsDeleteForm",
 *     }
 *   },
 *   links = {
 *     "canonical" = "/poll/{poll}",
 *     "edit-form" = "/poll/{poll}/edit",
 *     "delete-form" = "/poll/{poll}/delete"
 *   },
 *   base_table = "poll",
 *   data_table = "poll_field_data",
 *   admin_permission = "administer polls",
 *   field_ui_base_route = "poll.poll_list",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "question",
 *     "uuid" = "uuid",
 *       "category" = "category",
 *     "langcode" = "langcode"
 *   }
 * )

```

So all I can think of is that for some reason when uninstalling the module Drupal is supposed to use poll but is take base\_table instead.

Is this something in RC1 or is there an easy syntax error I am missing?

edited to add the backtrace info

```
    exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column            [error]
'base_table.id' in 'field list'' in /srv/www/dtadev2/core/lib/Drupal/Core/Database/Statement.php:64
Stack trace:
#0 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Statement.php(64): PDOStatement->execute(Array)
#1 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Connection.php(615):
Drupal\Core\Database\Statement->execute(Array, Array)
#2 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(73):
Drupal\Core\Database\Connection->query('SELECT base_tab...', Array, Array)
#3 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Query/Select.php(481):
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT base_tab...', Array, Array)
#4 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(262):
Drupal\Core\Database\Query\Select->execute()
#5 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(89):
Drupal\Core\Entity\Query\Sql\Query->result()
#6 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(74):
Drupal\Core\Entity\Query\Sql\Query->execute()
#7 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentUninstallValidator.php(47):
Drupal\Core\Entity\ContentEntityStorageBase->hasData()
#8 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(539):
Drupal\Core\Entity\ContentUninstallValidator->validate('poll')
#9 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(343):
Drupal\Core\Extension\ModuleInstaller->validateUninstall(Array)
#10 /srv/www/dtadev2/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(95):
Drupal\Core\Extension\ModuleInstaller->uninstall(Array, true)
#11 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(227):
Drupal\Core\ProxyClass\Extension\ModuleInstaller->uninstall(Array)
#12 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(80):
drush_module_uninstall(Array)
#13 /home/ubuntu/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1190): _drush_pm_uninstall(Array)
#14 [internal function]: drush_pm_uninstall('poll')
#15 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(364):
call_user_func_array('drush_pm_uninst...', Array)
#16 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(215): _drush_invoke_hooks(Array,
Array)
#17 [internal function]: drush_command('poll')
#18 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(183):
call_user_func_array('drush_command', Array)
#19 /home/ubuntu/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#20 /home/ubuntu/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#21 /home/ubuntu/.composer/vendor/drush/drush/drush.php(11): drush_main()
#22 {main}

Next exception 'Drupal\Core\Database\DatabaseExceptionWrapper' with message 'SQLSTATE[42S22]: Column not
found: 1054 Unknown column 'base_table.id' in 'field list': SELECT base_table.id AS id, base_table.id AS
base_table_id
FROM
{poll} base_table
GROUP BY base_table.id
LIMIT 1 OFFSET 0; Array
(
)
' in /srv/www/dtadev2/core/lib/Drupal/Core/Database/Connection.php:676
Stack trace:
#0 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Connection.php(640):
Drupal\Core\Database\Connection->handleQueryException(Object(PDOException), 'SELECT base_tab...', Array,
Array)
#1 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(73):
Drupal\Core\Database\Connection->query('SELECT base_tab...', Array, Array)
#2 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Query/Select.php(481):
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT base_tab...', Array, Array)
#3 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(262):
Drupal\Core\Database\Query\Select->execute()
#4 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(89):
Drupal\Core\Entity\Query\Sql\Query->result()
#5 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(74):
Drupal\Core\Entity\Query\Sql\Query->execute()
#6 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentUninstallValidator.php(47):
Drupal\Core\Entity\ContentEntityStorageBase->hasData()
#7 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(539):
Drupal\Core\Entity\ContentUninstallValidator->validate('poll')
#8 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(343):
Drupal\Core\Extension\ModuleInstaller->validateUninstall(Array)
#9 /srv/www/dtadev2/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(95):
Drupal\Core\Extension\ModuleInstaller->uninstall(Array, true)
#10 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(227):
Drupal\Core\ProxyClass\Extension\ModuleInstaller->uninstall(Array)
#11 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(80):
drush_module_uninstall(Array)
#12 /home/ubuntu/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1190): _drush_pm_uninstall(Array)
#13 [internal function]: drush_pm_uninstall('poll')
#14 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(364):
call_user_func_array('drush_pm_uninst...', Array)
#15 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(215): _drush_invoke_hooks(Array,
Array)
#16 [internal function]: drush_command('poll')
#17 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(183):
call_user_func_array('drush_command', Array)
#18 /home/ubuntu/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#19 /home/ubuntu/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#20 /home/ubuntu/.composer/vendor/drush/drush/drush.php(11): drush_main()
#21 {main}

```

describe poll shows this

```
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| pid   | int(11) | NO   | PRI | 0       |       |
+-------+---------+------+-----+---------+-------+

```

# Answer
> 1 votes
Whatever the exact reason is, this is another variant here:

Not being able to uninstall a module when storage is messed up.

You could start a patch for that by adding a `try`/`catch` around the `hasData()` call in `ContentUninstallValidator` and ignoring the problem. No table or messed up table likely also means no data ;)

There might be additional errors after that, where you need similar fixes.

# Answer
> 1 votes
### Explanation

The error means that `id` column is missing in your base table (`poll`) and it happens during uninstall process where `ContentUninstallValidator::validate` (part of Entity) determines the reasons a module can not be uninstalled and it fails.

This issue is further explained in the following bug report:

> ContentEntityStorage base has a `hasData()` method that checks if any entities exist at all. This method is called during the uninstall process of a module to warn the user that data will be lost if the module is uninstalled.
>
> When a module has deployment issues and the entity storage table has not been created, the `hasData()` method will throw an exception, completely blocking the uninstall process. So basically you end up with a broken module, that you cannot uninstall.

This is the code which fails in `validate()`:

```
if ($module == $entity_type->getProvider() && $entity_type instanceof ContentEntityTypeInterface && $this->entityManager->getStorage($entity_type->id())->hasData()) {
  $reasons[] = $this->t('There is content for the entity type: @entity_type', array('@entity_type' => $entity_type->getLabel()));
}

```

---

### Workaround

One workaround is to recreate the missing field, truncate table and uninstall the module again, e.g.

```
drush sqlq 'ALTER TABLE poll ADD COLUMN id INT(11)'
drush sqlq 'TRUNCATE TABLE poll'
drush -y pm-uninstall poll

```

Warning! By truncating you're removing all the data in that table, so backup it before if required.

Source: SQL Error on redirect uninstall.

---

### Solution

To fix this problem completely, please apply the patch attached in the below bug report:

---
Tags: entities, 8
---


# Question
Title: Add link gone from main menu and getting errors when trying to add new menu item
Running D7

For some reason the add link is gone from the admin menu view...can only edit but can't add any links or menu items, getting errors also:

```
Warning: Illegal string offset 'hierarchical_select' in
drupal_array_set_nested_value() (line 6776 of
C:\aquiasites\redoII\includes\common.inc).

Fatal error: Cannot create references to/from string offsets nor
overloaded objects in C:\aquiasites\redoII\includes\common.inc on line
6776

```

I disabled hierarchical\_select to no avail...I can't find the view to control those settings, but this is a core view right?

Usually menus say:

```
    list links    edit menu    add link

```

But now these options are gone...

It only says:

```
    MENU LINK   ENABLED TARGET  OPERATIONS

```

# Answer
> 0 votes
Ok, found the answer, eventually another error popped up when trying usermenu:

```
Warning: Illegal string offset '#value' in
content_menu_form_menu_item_delete_form_alter() (line 270 of
C:\aquiasites\redoII\sites\all\modules\content_menu
\content_menu.module)

```

I disabled all possible menu plugins...the offending module didn't create any errors on main menu and other, **ONLY on usermenu...**

Disabled this module https://www.drupal.org/project/content\_menu

Now works fine

---
Tags: views, navigation, taxonomy-terms
---


# Question
Title: How to display DB data from Custom module using custom HTML markup?
I am putting a custom module together. It will take data submitted from a form from site users and store it in the DB. Admins will then be able to review the data and make changes to it. It is easy enough to display the DB data with something like:

```
return theme('item_list', array('header' => $header,'items' => $rows));

```

But I need to customize it to have custom HTML markup. Any thoughts, answers or direction?

# Answer
There are 2 ways of doing it. First one is to define your own theme function using hook\_theme and then either create a theme function of a template file inside of your module or theme folder. example code is given here

```
/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $custom_theme = array();
  $custom_theme['my_new_theme'] = array(
    // example theme template register
    // for
    //sites/all/modules/mymodule/templates/my_new_theme.tpl.php
    'template' => 'my-new-theme',//dash will convert to underscore in template name.
    'path' => drupal_get_path('module', 'mymodule') . '/templates',
    'variables' => array('header' => null,'rows'=>null),
  );

  return $custom_theme;
}

```

You can then use

```
theme('my_new_theme', array('header' => $header, 'rows' => $rows));

```

instead of your theme function call. And then inside of your my\_new\_theme.tpl.php you can access $header and $rows variables.

Second method is not recommended but a possible way of doing this. So you can just create your HTML output in your callback function where you are creating that list. Store your full html to be out-puted in some variable and finally just return that variable at the end. Drupal will render your HTML as it is.
> 0 votes

---
Tags: 7
---


# Question
Title: Insert login form in a personalized form
I'd like to insert the login form in my own form. To be clear, I have a quotation form and after we answer all the questions I would like to find the user login block. And after the user is logged in, I would like to reload the page to show differents elements.

In the form, I insert this code to show the login block:

```
$dgf_login_block = drupal_get_form('user_login_block');
$render_login_block = drupal_render($dgf_login_block);
$form['envoi']['login_block'] = array(
    '#markup' => $render_login_block ,
    '#prefix' => '<div class="lead text-left">',
    '#suffix' => '</div>',
);

```

But it doesn't work.

My question is: what is the best way to insert the user login form inside an other form? Or does it better to define two fields (username and password) and validate them (and how can I validate the login)?

Thanks in advance for your help.

Alexandre

# Answer
In general it is not possible to have one form inside of another form. So even if you do it with pure HTML, you can't have another form inside of the form tag.

To have login block you will need to add it as a separate form. So either you can redirect user to a page where you have login form after they have filled your original form. I don't have reputation to comment but I would like to know how have you created your original form. That way I might be able to help you with what you want to achieve.
> 0 votes

# Answer
I found a solution for a multistep form. I used the user login block, and in my module :

```
function mymodule_form_user_login_block_alter(&$form, &$form_state) {
  $form['field_data_hidden'] = array('#type'=> 'hidden');
  unset($form['#action']);
  $form['#submit'][] = 'mymodule_user_redirect';
}
function mymodule_user_redirect($form, &$form_state) {
  drupal_goto('my-form-page-to-reload', array('query'=>array('data'=>$form_state['values']['field_data_hidden'])));
}

```

The hidden field stores the datas for the query from the multistep form (with JS). The query is used for reload the form with the previously entered data.

Note: if you have trouble for redirect the page in the module, **take care that the "TRIGGER: AFTER A USER HAS LOGGED IN" has no assign**.

There's may be a best way to do this, but it works.
> 0 votes

---
Tags: forms, users
---


# Question
Title: Communicating Drupal module settings module to module every page load for use in drupalSettings in Drupal 8
I have a code base I am working in that has plenty of custom modules. It also has an analytics scheme already in place that have been trying to make work with certain customer requirements.

One of these is to report a 'page\_type' value, that if set on certain landing pages is reported correctly in another module called my\_analytics. The landing pages are custom module also, named my\_landing\_page.

I added the page\_type property successfully to the module and have developed code to add analytics information from other modules. The set up I have works- actually, but it only works on the first page load, due to caching. I know why I am having the issue but am looking for solutions to get around it. I am an experienced programmer, but not an experienced Drupal-person.

Here is how I had it set up. The only place I could find to grab the field info from the my\_landing\_page module is in the preprocess hook, as follows:

```
function my_landing_page_preprocess(&$variables) {
  if (isset($variables['entity'])) {
    $node = $variables['entity'];

      my_analytics_get_landing_page_analytics($node);
  }
}

```

This calls a series of functions in the other module my\_analytics which eventually merges these global additions into an array that becomes drupalSettings. There some analytics populated in my\_analytics\_page\_bottom as well. This allows the javascript to use these values to send the analytics call with the info on the client side. The use of globals is unfortunate, but do you have a better idea?

```
function my_analytics_get_landing_page_analytics($node) {
  if ($node instanceof Node && $node->getEntityTypeId() == 'node' && $node->getType() == 'landing_page') {

    if ($node->hasField('field_page_type') && count($node->get('field_page_type')->getValue()) > 0) {
      my_analytics_add_tags_global([
        'TagID_channel' => $node->get('field_page_type')->getValue()[0]['value'],
      ]);
    }

  }
}

function my_analytics_add_tags_global(array $tags) {
  if (isset($GLOBALS['my_dtm_global_tags']) && is_array($GLOBALS['my_dtm_global_tags'])) {
    $GLOBALS['my_dtm_global_tags'] = array_merge($GLOBALS['my_dtm_global_tags'], $tags);
  }
  else {
    $GLOBALS['my_dtm_global_tags'] = $tags;
  }
}

function my_analytics_add_set_tags(array &$build, array $tags) {
  if (!empty($build['#attached']['drupalSettings']['my_analytics']['setTags'])) {
    $build['#attached']['drupalSettings']['my_analytics'['setTags'] = [];
  }

  // Search for global tags added from other modules.
  if (isset($GLOBALS['my_dtm_global_tags']) && is_array($GLOBALS['my_dtm_global_tags'])) {
    $tags = array_merge($tags, $GLOBALS['my_dtm_global_tags']);
  }

  foreach ($tags as $tag_id => $tag_value) {
    $build['#attached']['drupalSettings']['my_analytics']['setTags'][] = [
      'id' => $tag_id,
      'value' => $tag_value,
    ];
  }
}

```

So as I mentioned, this works on the first page load. I have done enough of my own investigating to know this is because the preprocess hook in my\_landing\_page does not fire after the page is cached and that this is intended behavior.

Keep in mind I do *not* have complete control over how the rest of the set up was written. I have inherited it.

So here are the options I have considered, but in most cases don't know how to accomplish.

1) Find something better than preprocess, a way to get the info (page\_type) from my\_landing\_page each page load so that it populates my\_analytics properly each time the page loads.

2) Somehow cache the drupalSettings with the page (or something similar) be it by using the Cache API or addCacheableDependency or something I am unaware of so that the original cached version is used for subsequent page loads.

3) ???

Does anyone know how to accomplish what I am trying here? Basically, grabbing info from one module and sharing it with another in a way that happens every page load? I want to get the page\_type value from my\_landing\_page and into the drupalSettings object we populate in my\_analytics and that to happen every visit to the page.

Thanks.

# Answer
In general when you add attachments to a build array, then add the cache metadata in the same place:

```
$build = [];

// attach libraries and their drupal settings
$build['#attached'] = [...];

// add the cache dependencies for this data
$build['#cache'] = [
  'contexts' => ['url'],
  'tags' => ['dtm_global'],
  'max-age' => 60,
];

```

If you want to add cacheable dependencies of objects to the build array, you can use `addCacheableDependency()`, see https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

Now sharing this with other modules is no problem anymore, Drupal builds a page with hundreds of render arrays like this, all from different modules.
> 0 votes

---
Tags: 8, caching
---


# Question
Title: Using feeds and xpath to import multiple images into a node
I am using feeds to import a heavily customised wordpress site into drupal using xpath and a custom xml file. All is going well until I try to import multiple images into a node.

The image field is a multi value field (not multiple different image fields)

Only the first image is imported the rest are ignored.

When I have xpath debugging on it correctly shows multiple image URI's and their titles.

Is there a way using feeds and xpath to import multiple images into a node?

This is an example of one item from the feed

```
<root>
    <item>
        <wordpress_id>85672</wordpress_id>
        <title>.....</title>
        <content>.....</content>
        <created>2017-03-17 10:13:24</created>
        <custom_fields>
            <url type="Website">......</url>
            <url type="Website2">.....</url>
        </custom_fields>
        <attachments>
            <images>
                <item>
                    <ID>85671</ID>
                    <post_author>0</post_author>
                    <post_date>2017-03-08 18:00:00</post_date>
                    <post_title>.....</post_title>
                    <uri>.....</uri>
                </item>
                <item>
                    <ID>85671</ID>
                    <post_author>0</post_author>
                    <post_date>2017-03-08 18:00:00</post_date>
                    <post_title>.....</post_title>
                    <uri>......</uri>
                </item>
            </images>
        </attachments>
    </item>
</root>

```

The post title and uri from the attachments are the two fields I am trying to map to the node image type

for my xpath I am referencing them using...

```
image_title => attachments/images/item/post_title
image_source => attachments/images/item/uri

```

and in my mapping I am using...

```
image_title (image_title) => Image: Title (field_image:title)
image_source (image_source) =>  Image: URI (field_image:uri)

```

in the section I have no trouble mapping website and website2 to to a multi value link field so I am not sure why the image field should be any different.

edit: added xml snippet and mappings and further explanation

# Answer
> 1 votes
The issue was resolved.

Feeds importer was working correctly all along. The problem it seems was with the actual images themselves. I didn't realise, but the in some cases the source images where huge (in excess of 18Mb) It just co-incidentally happened that the large image was the second image for the node. Thus when the feeds importer failed. It actually looked like it worked but only managed to import the first image.

When I resized all the images and then re-imported them, it imported all the images correctly.

There is still an unresolved issue in that the import was failing silently. After a few tweaks import suddenly failed with server 500 errors. That's when the apache logs showed a memory allocation error.

Once I saw that, I was able to determine the issue was related to the source images.

I guess the outcome of this is don't assume the problem is related to something you did.

# Answer
> 0 votes
You will need to use the feeds tamper module: https://www.drupal.org/project/feeds\_tamper

With this module you can alter (tamper) the content of the (XML-)feed values. One of the tamper-functions allows you to split the value at the comma (or other character you set) so then you can import all the images in this field.

An example XML like this could all be imported into one image field.

```
<xml>
    <node>
        <images>file_1.jpg, file_2.jpg, file_3.jpg</images>
    </node>
</xml>

```

---
Tags: media, feeds
---


# Question
Title: How to get value from URL in a view block using contextual filter?
I want to show related nodes of an open article in a block, but how do I access Node IDs from url in block view.

# Answer
> 1 votes
Assume your article is located at `node/nid` (with `nid` the id of the node of the article), then configure your contextual filter like so:

> When the filter value is not available: Provide a default value with Type = "Content ID from URL" (that value should correspond to the `nid` of your article).

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


title: Render view in specific language

text:
# Question
Title: Render view in specific language
How to render view in specific language?

```
$view = views_get_view("commerce_line_items_custom");
////Pass arguments
$view->set_arguments(array($data['commerce-order']->order_id));
$view->hide_admin_links = TRUE;
////Generate content
$content =  $view->execute_display('block');

```

I tried following overide, but it did nothing:

```
$view->set_display('block');
$view->display_handler->options['field_language'] = 'fr';
$view->display_handler->display->display_options['field_language'] = 'fr';
$view->display_handler->default_display->options['field_language'] = 'fr';
$view->display_handler->set_option('field_language', 'fr');

```

# Answer
I used following solution:

```
      // Replace language by language of user for correct rendering of view.
      $language_list =  language_list();
      $language_org = $language;
      $language = $language_list[$lang];
      ////Get view
      $view = views_get_view("commerce_line_items_custom");
      ////Pass arguments
      $view->set_arguments(array($data['commerce-order']->order_id));
      $view->hide_admin_links = TRUE;
      ////Generate content
      $content =  $view->execute_display('block');
      $replacements[$original] = $content['content'];
      // Restore language
      $language = $language_org;

```
> 0 votes

# Answer
May be you can try this.

```
function yourmodule_views_pre_render(&$views) {
  if ($views->name == 'yourviewname') { //yourviewname is the machine name of the view
    $_SESSION['language'] = fr;
  }
}

```
> 0 votes

---
Tags: 7, views, theming, i18n-l10n
---


# Question
Title: Datepicker not working for a field in node edit form pulled with drupal_get_form
I have a custom table that pulls all the node of a 'seminar' content type and displays it in this way.

```
 Nid | Speaker_name | Speaker_language | Date | Edit
 --------------------------------------------
 124 | Sanjok       |     Eng         |  12-09-2017     | editlink
 *****************************************************************
 125 | Sam          |     Spanish     |   12-10-2017    | editlink
 *****************************************************************

```

Each `editlink` is linked to a bootstrap popup modal which renders respective node edit form. The node form is rendered this way.

```
$node = node_load($singlerow['nid]);
$popup_form = drupal_get_form('seminar_node_form',$node);
print drupal_render($popup_form);

```

I wanted a popup node edit functionality where the admin/editor does not need to go to /admin/content to edit/update the node. The form is rendered perfectly in a popup modal fashion except for the date field which does not display the default drupal datepicker. I have added the required datepicker.js files located on my `base_url().'misc/ui/jquery.ui.datepicker.min.js'` on my template file and on the table file but the datepicker does not work for some reason. PS the consolelog does not throw any error as well.

# Answer
> 0 votes
After hours of experimenting I finally found a workaround. On my template file I used a `preprocess_page` function to add my required js

```
   drupal_add_js(base_path().'misc/ui/jquery.ui.core.min.js', array( 'scope' => 'footer', 'weight' => 5));
   drupal_add_js(base_path().'misc/ui/ate_popup/jquery.timeentry.pack.js', array( 'scope' => 'footer', 'weight' => 5));
   drupal_add_js(base_path().'misc/ui/jquery.ui.datepicker.min.js', array( 'scope' => 'footer', 'weight' => 5));

```

And on my custom Js script file I did this. Since all my date input field had a class `date-clear`

```
$('body').on('focus','.date-clear',function(){
      $(this).datepicker({dateFormat: 'd M yy'});
});

```

Obviously this answer can be improved but for now, this does to me.

---
Tags: forms, datetime, javascript
---


# Question
Title: Form alteration is not working from within my form class
I am following https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api for my hello world module.

Below is my code

```
namespace Drupal\hello_world\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an hello_world form.
 */
class HelloWorldForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'hello_world_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['phone_number'] = array(
            '#type' => 'tel',
            '#title' => $this->t('Your phone number'),
        );
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
            '#button_type' => 'primary',
        );
        return $form;
    }

    function hello_world_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
        if ($form_id == 'hello_world_form') {
            $form['phone_number']['#description'] = t('Start with + and your country code.');
        }
    }

}

```

I also cleated cache. Not sure why form is not altering.

# Answer
> 0 votes
Use your hello\_world\_form\_alter in your module file. I guess should be hello\_world.module. I guess you already have a folder hello\_world where you placed the file above. In this folder you should also have an .info.yml file at the same folder place your hello\_world.module file.

Please check https://www.drupal.org/docs/8/creating-custom-modules. You will find a lot of tutorials about how to create a custom module. Just google it!

# Answer
> 0 votes
Remove function `hello_world_form_alter` from Form file & add below code in **hello\_world.module**

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

/**
 * Implements hello_world_form_alter().
 */
function hello_world_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id === 'hello_world_form') {
    $form['phone_number']['#description'] = t('Start with + and your country code. - Test');
  }
}

```

---
Tags: 8, forms
---


# Question
Title: Missing title in template for custom route
I'm missing a title `(_title)` being shown on a custom route page. I wonder where i can place it in a template for it to show up.

My route:

```
bg_helper.blogs_overview:
  path: '/blog'
  defaults:
    _controller: '\Drupal\bg_helper\Controller\DefaultListController::overview'
    _title: 'Blog'
    type: 'blog'
  requirements:
    _permission: 'access content'

```

And the overview method:

```
class DefaultListController extends ControllerBase {
  public function overview($type, $language = false) {
    $query = \Drupal::entityQuery('node');
    $query->condition('status', 1);
    $query->condition('type', $type);
    $query->pager(10);
    $nids = $query->execute();

    $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

    $build = \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'teaser');
    $build['pager'] = [
      '#type' => 'pager',
    ];
    return $build;
  }
}

```

# Answer
> 1 votes
You find the `_title` default in the route object of the current route match, which you get by using a type-hinted argument in the controller method:

```
use Drupal\Core\Routing\RouteMatchInterface;

...

  public function page(RouteMatchInterface $route_match) {
    return [
      '#markup' => $this->t($route_match->getRouteObject()->getDefault('_title')),
    ];
  }

```

For multilingual sites use `$this->t()` to translate the title. In more advanced cases with placeholders in the title use `TitleResolver::getTitle`.

---
Tags: theming, routes
---


# Question
Title: Unable to set #default_value for a date field
I have a form with a date field.

```
$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
    '#default_value' => [
        'year' => 2015, 'month' => 05, 'day' => '09',
    ]
];

```

But when the form is displayed the date field doesn't contain the value "09.05.2015". The date field is empty.

Could you clarify me, how can I fill the date field with the value ? I watched it as on my form as on the examle form from the Examples module.

# Answer
> 1 votes
Set it like this

```
$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
       '#default_value' => [
        '2015-05-09',
    ]
];

```

---
Tags: 8, forms
---


title: entityQuery vs. entityTypeManager

text:
# Question
Title: entityQuery vs. entityTypeManager
I have a custom content type `user_in_club` and I'd like to load a single specific node matching two field values. There are 2 ways (I know of) which can solve this:

```
$result = \Drupal::entityQuery('node')
->condition('type', 'user_in_club')
->condition('field_user_id', $account->id())
->condition('field_club_id',$active_club)
->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

```

OR

```
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'user_in_club', 'field_user_id' => $account->id(), 'field_club_id' => $active_club ]);

```

In my single example only one node id is returned, but in case I have multiple node ids returned, is one method to be preferred over the other in terms of performance etc ? I currently don't see a big difference other than ETQ is better to create more complex queries.

# Answer
They're identical. loadByProperties() actually converts your conditions to an entity query internally.

I'd acually recommend to do an entity query yourself, directly. It's more readable and loadByProperties() might get deprecated in the future.
> 10 votes

---
Tags: 8, entities, database
---


# Question
Title: How can I theme the Responsive Image module in a specific Paragraph Type
I have a responsive image field inside two different paragraph types. I am on Drupal 8.3.7. I want to theme the module in one paragraph type but not the other. I want to render a modified version of this code :

https://api.drupal.org/api/drupal/core%21themes%21stable%21templates%21field%21responsive-image.html.twig/8.2.x

I tried putting my modified code inside responsive-image--field\_my\_resp\_image.html.twig but it is not being used. I can't seem to find the correct filename for a theming a responsive image from a specific paragraph type. Any ideas?

My goal is to render embedded CSS for a background image instead of the HTML picture element that responsive images uses. Is there a better method than what I'm attempting above?

# Answer
> 0 votes
I found a solution, but I'm honestly not happy with it. I can use 'responsive\_image\_style\_id' to identify this responsive image. The problem with this approach is that it relies on specific keywords ('\_style') in 'responsive\_image\_style\_id' and if a site admin changes that, it will break :

```
function paia_theme_suggestions_responsive_image_alter(&$suggestions, $vars, $hook) {

  $newHook = str_replace('_style', '', $vars['responsive_image_style_id']);

  if ($newHook != $vars['responsive_image_style_id']) {
    $suggestions[] = $hook . '__' . $newHook;
  }
}

```

It seems I am using entirely the wrong approach for this, and I should probably be rolling my own module or something totally different. But I have a deadline to meet and I need to move on.

---
Tags: media, theming, paragraphs
---


# Question
Title: How to determine the code for settings.php config override based on .yml?
I am trying to put my API keys in a separate file instead of storing them in config management.

For example, I installed the Commerce Stripe module.

When I export the config, it looks like this:

**commerce\_payment.comerce\_payment\_gateway.stripe\_test.yml**

```
uuid: 430a9544-c852-4a14-b7b0-3a833a02dd06
langcode: en
status: true
dependencies:
  module:
    - commerce_stripe
id: stripe_test
label: 'Stripe Test'
weight: null
plugin: stripe
configuration:
  publishable_key: thisishidden
  secret_key: thisishidden
  display_label: Stripe
  mode: test
  payment_method_types:
    - credit_card
conditions: {  }
conditionOperator: AND

```

Now, I want to store `publishable_key` and `secret_key` in a file, but **how do I determine the "path" to call them?**

```
$config['whatgoeshere?']['configuration']['secret_key'] = 'abcdefg';

```

# Answer
> 3 votes
The first key is the name of the config object/file, so... `commerce_payment.comerce_payment_gateway.stripe_test`.

The rest you already figured out, it's an array that's recursively merged into the other one.

---
Tags: 8, security, configuration
---


# Question
Title: Confirmation popup before delete file/image
I'm working on a D8 project and in many cases I use file and image upload fields.

The files and the images are visible above the field and the user can delete them by using the default 'Remove' button.

What I want to do, is to add a confirmation popup asking if they really want to delete that files/images.

Is there any hook that I could use to make that check? If I use javascript, how can I say to drupal that now can proceed to deletion?

Thank you in advance.

EDIT:

I tried to do what @Ivan suggested but I can't make it work. My form has submit and ajax callback. Should I alter both?

Is there any working example? I am so desperate!!

# Answer
> 0 votes
After long time I managed to find the solution. I didn't manage to make it work server side with modals so I managed to solve it using jQuery.

So I created a javascript file:

```
    Drupal.behaviors.confirm = {
        attach: function(context, settings) {

            $.each($('.form-submit'), function(){
                var str = $(this).attr('id');
                //find the id for each button
                var remove_btn_id = '#' + $(this).attr('id');

                //apply only to remove buttons and only to those that the functionality is not applied yet.
                if (str.indexOf("-remove-button") >= 0 && !$(remove_btn_id).hasClass('custom-handler')){

                    //Drupal.behaviours are triggered every time my ajax was submitted and I ended up with multiple events to each button.
                    //In order to avoid it, add a class to check if the button already has that functionality.
                    $(remove_btn_id).addClass('custom-handler');
                    $(remove_btn_id).bindFirst('mousedown', function(e, next) {

                       //Display popup and get user's decision.
                        var choice = confirm('Are you sure you want to delete that?');
                        if(!choice){
                            //if user clicks cancel then do nothing
                            e.stopImmediatePropagation();
                        }
                    });
                }
            });
        }
    }

```

I'm not sure if this the right way to implement that functionality (I guess is not the Drupal way) but at leat it works!

---
Tags: 8, entities
---


# Question
Title: Create a route to show a node with a custom display/view mode
In Drupal 8, it is easy to add display/view modes. Let say I created the *tech* display mode and I set it up for the *film* content type.

Now, I would like to create a route for it and access it as local task of entity.node.canonical.

How can I achieve this?

# Answer
In Drupal 8 there are two display modes: view mode and form mode.

You can define the view mode in a route using the `_entity_view` key.

> \_entity\_view: The value is entity\_type.view\_mode. Will find an entity in the path and render it in the given view mode. E.g. \_entity\_view: node.teaser will return the render array of the {node} in teaser mode.
> 11 votes

# Answer
The View Mode Page module does just what you're looking for, creating alternate paths to access different view modes.

> Create separate pages for different view modes for a given content type.
> 1 votes

---
Tags: 8, entities
---


title: How do I modify the result?

text:
# Question
Title: How do I modify the result?
Having an issue with HOOK\_views\_pre\_render and HOOK\_views\_post\_render, trying to alter the rendered output of the view. There are similar questions like: Hide view results with hook but I am not seeing the results as I am expecting under $view\['result'\]

There is what looks like a full entity and not the markup that I'm expecting.

# Answer
You can use HOOK\_views\_post\_execute() and cycle through the results rows, updating the row with something like:

```
        foreach ($viewExecutable->result as $key => $rr) {
          $title = $rr->_entity->getTitle();
          // update $title value...
          $viewExecutable->result[$key]->_entity->set('title', [['value' => $title]]);
        }

```
> 2 votes

# Answer
Thanks @jons, your answer allowed me to move further and I was able to set other fields in the view result now:

```
// Testing how we can update view result title value
$title = 'This is a custom title';
$newurl = 'http://www.nextide.ca';
$view->result[$key]->_entity->set('title', $title);
$view->result[$key]->_entity->set('body', 'This is a custom content');
$view->result[$key]->_entity->set('field_coned_site_course_url', $newurl);

```
> 0 votes

---
Tags: views, 8
---


title: Reducing file size of styled images

text:
# Question
Title: Reducing file size of styled images
I always thought styled images are smaller than original ones in file size. So the main reason for styling was to reduce the file size. But today I noticed it isn't always the case. For example:

I downloaded an image `abcd.jpg` from facebook and then uploaded it to my Drupal website.

Originally the image was `405.3 kB` which is `2048px X 1536px`.

After downloading the same image from my drupal website the image is `698 kB` which is `1100px X 845px`.

```
Style Effect:(Scale width 1100)

```

And when I checked I found the same in most of the cases. Can anything be done about it without compromising image quality?

# Answer
> 1 votes
It's in the nature of image compression that compressing an already compressed image can result in larger filesize. The image-toolkit (be it GD or image magick) can not know on what level the image is already compressed and will try to make the best of it (following the quality setting that No Sssweat describes). So you may want to try to set this to 100% to prevent repeated compression.

Further reading:

# Answer
> 0 votes
You can always lower the image toolkit quality

# Answer
> 0 votes
You may choose to use the reSmush.it image style optimizer module, see https://www.drupal.org/project/resmushit

It uses the eponymous service (see https://www.resmush.it/) which optimizes image size without affecting its quality. This optimization service is free (contrary to many other ones).

---
Tags: files, media
---


title: How to know the module package?

text:
# Question
Title: How to know the module package?
I need to know the package of a given module to performs some actions inside the implementation of a custom a drush command. So usually you will find that we will found this information in the module\_handler service. But there is not method to get the module package.

So, how can I know the module package?

# Answer
Maybe another simpler way exists, but after a little digging in the core I found that the modules list (admin/modules) with all the information is retrieve from the \_system\_rebuild\_module\_data() function that use the info\_parser service to retrieve all the module information.

If you want to know the module package you can use this code:

```
$module_machine_name = 'views';
$module = \Drupal::service('module_handler')->getModule($module_machine_name);
$module_info = \Drupal::service('info_parser')->parse($module->getPathname());
// To use dpm() you need the devel module.
dpm($module_info['package']);

```

Output:

> Core
> 2 votes

---
Tags: 8, drush
---


title: Migration not found - D8

text:
# Question
Title: Migration not found - D8
Following this I have created a module to migrate d7 users to d8. I have enabled all mandatory modules needed to run migration. But when I do `drush migrate-import {mymigrationid}` ; it says : **Migration not found**.

But When I did `"drush config-list|grep migrate"` , it is showing that particular migration:

> migrate.migration.d7vm\_users
>
> migrate\_plus.migration.custom\_user

But when I'm doing `drush migrate-status`, these migrations are not listing up there.

**Can anyone tell what's supposed to get missed?**

Here is my mymodule/config/install/vm.yml file

```
id: d7vm_users
label: User accounts
migration_tags:
  - Drupal 7
dependencies:
  enforced:
    module:
      - mymodule
source:
  plugin: d7vm_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  created: created
  access: access
  login: login
  status: status
  timezone: timezone
  langcode: language
  init: init

```

and src/Plugin/migrate/source/User.php

```
<?php
/**
 * @file
 * Contains \Drupal\mymodule\Plugin\migrate\source\User.
 */

namespace Drupal\mymodule\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Extract users from Drupal 7 database.
 *
 * @MigrateSource(
 *   id = "d7vm_users"
 * )
 */
class User extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('users', 'dcf_u')
      ->fields('dcf_u', ['uid', 'status', 'created','access', 'login',    'name',
        'pass', 'mail', 'init', 'language']);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'uid' => $this->t('Account ID'),
      'status' => $this->t('Blocked/Allowed'),
      'created' => $this->t('Registered date'),
      'access' => $this->t('Time of last access'),
      'login' => $this->t('Time of last login'),
      'name' => $this->t('Account name (for login)'),
      'pass' => $this->t('Account password (raw)'),
      'mail' => $this->t('Account email'),
      'init' => $this->t('init'),
      'language' => $this->t('language'),
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'dcf_u',
      ],
    ];
  }

}
?>

```

# Answer
If your source plugin extends SqlBase, you need to make sure you have the database configuration set up correctly. Otherwise Migrate will silently ignore the migration.

In your settings.php or settings.local.php, add the following database configuration:

```
$databases['migrate']['default'] = array(
  'driver' => 'mysql',
  'database' => 'NAME OF YOUR SOURCE DB',
  'username' => 'YOUR DB USER',
  'password' => 'YOUR DB PASSWORD',
  'host' => 'localhost',  // change this as necessary
);

```

By default, Migrate looks for a DB connection named "migrate". If you use any other name, the migrations won't appear when you run `drush migrate-status`.

Note: The "migrate" connection is in addition to your "default" connection. You should have two connections in your settings if you're migrating from a MySQL database.

In case anyone's curious, the DB connection check occurs in the method SqlBase::getDatabase() in drupal/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php.

This is documented in https://www.drupal.org/node/2830031 and apparently will be fixed in Drupal 8.4.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: MySQL error when creating custom theme hooks for Paragraph Module [Drupal 8]
I'm trying to theme a paragraph module on a specific page. The bundle-view suggestions wont seem to help here, so I am trying to create a custom hook suggestion to push my template. I tried both of these methods in my mytheme.theme file ;

```
function mytheme_theme_suggestions_paragraph_alter(&$suggestions, $variables) {
  kint($variables);
}
function mytheme_preprocess_paragraph(&$variables) {
  kint($variables);
}

```

After refreshing cache, I get these errors :

I've successfully done this on other modules in the same file, but for some reason it breaks here. Any ideas what I'm doing wrong and how to correctly do this ?

EDIT: I've increased the max\_allowed\_packet in MySQL my.ini from 1M to 256M and I now get " an unexpected error..." message and no errors in the drupal log. I do however get these errors from apache :

https://pastebin.com/FVL8DGJa

# Answer
> 1 votes
It looks like you're MySQL server is getting overloaded and going down, too much kint() debugs runned at once maybe? It doesn't look like issue with module itself.

---
Tags: paragraphs, theming
---


# Question
Title: The web service endpoint returned a "HTTP/1.1 403 Forbidden" response
There are 12 or so similar questions but not drupal related. Here is my site on a digitalocean droplet: http://104.236.27.226/

It is apache2 on ubuntu16 php7. I am using: 000-default.conf:

```
ServerName casey.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory "/var/www/html">
  AllowOverride All
  Require all granted
</Directory>

```

I made file permission as permissive as possible:

```
drwxrwsrwx  4 casey    www-data 4096 Sep 20 12:15 www/

```

I put an echo in the settings.php, at the very end to show the user for apache:

```
casey@dchouse02:/var$ tail -n 3 www/html/sites/default/settings.php
echo('<h4>ECHO: from setting.php after databases array; and apache user is (via exec whoami): ');
echo exec('whoami'); echo ('</h4>');

```

Knowing that settings.php is being read, I moved to indx.php for this D7 site:

```
casey@dchouse02:/var$ tail -n 3 www/html/index.php
echo('<p>from index.php: before menu_execute_active_handler:</p>');
menu_execute_active_handler();
echo('<p>After menu_execute_active_handler</p>');

```

At this point the error appears:

```
The web service endpoint returned a "HTTP/1.1 403 Forbidden" response

```

The list of apache processes look similar to what I get from the ubuntu on my laptop:

```
casey@dchouse02:/var$ ps aux | grep apache
root     16068  0.0  4.7 327752 23512 ?        Ss   16:59   0:00 /usr/sbin/apache2 -k start
www-data 16071  0.0 10.2 345548 51244 ?        S    16:59   0:00 /usr/sbin/apache2 -k start
www-data 16072  0.0 10.2 343656 51176 ?        S    16:59   0:01 /usr/sbin/apache2 -k start
www-data 16073  0.0 10.7 347648 53632 ?        S    16:59   0:00 /usr/sbin/apache2 -k start
www-data 16074  0.0 11.1 349660 55520 ?        S    16:59   0:01 /usr/sbin/apache2 -k start
www-data 16075  0.0 10.1 345548 50888 ?        S    16:59   0:01 /usr/sbin/apache2 -k start
www-data 16099  0.0 10.0 343428 50248 ?        S    16:59   0:00 /usr/sbin/apache2 -k start
www-data 16764  0.0 10.3 345600 51792 ?        S    18:37   0:00 /usr/sbin/apache2 -k start
www-data 17344  0.0  1.3 327784  6612 ?        S    21:38   0:00 /usr/sbin/apache2 -k start
www-data 17347  0.0  1.3 327784  6612 ?        S    21:38   0:00 /usr/sbin/apache2 -k start

```

I don't know what else to do to troubleshoot this.

# Answer
This is a pretty basic error most likely having to do with your digital ocean config than Drupal. You've got a named virtual host (casey.com) in your config file. Not sure how pointing us to an IP address helps us to help you.

Read through the digital ocean server set up documentation and make sure you've covered all your bases.
> 0 votes

---
Tags: 7, http-request
---


title: Invalidate cache on a REST endpoint

text:
# Question
Title: Invalidate cache on a REST endpoint
I have an endpoint that returns an array of Order entities, but it's caching the results so when a new order is placed the cache has to be cleared.

The code within the endpoint is:

```
// Tried this also.
// $this->orderManager->resetCache()
$orders = $this->orderManager->loadByProperties([
  'uid' => $this->customer->id(),
]);
$response = new ResourceResponse($orders);
// maybe this doesn't work because it's an \Drupal\Entity\commerce\Order[]
$response->addCacheableDependency($orders);

return new ResourceResponse($orders);

```

What am I missing?

# Answer
See the comment from @Clive, you can only add single objects as dependency. But you need to add a list tag as well, because the entity query may change because of entities added or modified that are not in the cached list.

```
$list_tags = \Drupal::entityTypeManager()->getDefinition('entity_type')->getListCacheTags();
$response->getCacheableMetadata()->addCacheTags($list_tags);

```
> 2 votes

---
Tags: 8, caching
---


# Question
Title: How do I setup Drupal/Varnish caching so Content Editors don't see browser-cached pages after logging in?
I've got a bit of a situation going on with our caching solution and would love some input.

We use a solution of HAProxy -\> Varnish -\> Apache. HAProxy terminates SSL and sends that to Varnish which then requests from Apache if needed.

We are using Drupal 7, Purge, and Cache Expiration. We have Cache Expiration set to use external expiration and include the baseurls. Our sites have "Minimum cache lifetime" set to "none" and "Expiration of cached pages" set to "6h".

The Varnish cache always has the correct versions of the cached pages and those get expired correctly.

If an anonymous user visits a page, say node/123, and then logs in and subsequently navigates back to the same page the browser still serves the browser cached version of the page. This is the expected behavior from Drupal as I would expect the page to stay cached for an anonymous user.

Our content editors are required to reload the page (F5) and think there is an "error" because they need to perform this in order to see the expected, authenticated, version of their page.

How do other administrators who allow editing on production instances tackle the issue?

I toyed around with the idea of shortening the cache lifetime that comes out of Varnish, but that feels like a band-aid (30s cache vs. 6h). I also toyed with the idea of removing the cache headers coming out of Varnish, but allowing Varnish to hold the cache for its lifetime.

I'd like to be able to cache responses to keep the load off of our server if at all possible.

Thanks in advance!

# Answer
> 0 votes
I ended up solving this by making sure that our proxy sent out the following header for cacheable pages.

`Cache-Control: public, max-age=0`

The behavior I was experiencing was due to page\_cache\_maximum\_age being set, and in reality I didn't want that being sent to clients, only my caching server.

`sub vcl_backend_response() {
 if (not static content && !beresp.uncacheable) {
 unset beresp.http.Cache-Control;
 set beresp.http.Cache-Control = "public, max-age=0";
 }
}`

# Answer
> 0 votes
See the answer to this question: https://drupal.stackexchange.com/a/117984/3279

Example usage for the D6 varnish module can seen here: https://www.drupal.org/node/738420

So, you could do a `hook_form_alter` in a custom php module for D7 that adds an additional submit handler to your nodes that basically calls the D7 equivalent code to clear the varnish caches for the 1 node path path/aliases in question.

---
Tags: 7, caching, performance, proxies
---


title: How do I set up HTTPS on a multi-site?

text:
# Question
Title: How do I set up HTTPS on a multi-site?
I made a couple websites on a drupal multisite setup.. and I want to start using https. And.. I'm just lost. Can anyone help me get started?

So, here's the details of how I have things set up..

So I have like a drupal 7 install on ubuntu, with 3 sites.. all in the var/www/html/sites folder, so for example, the folders are named

```
site1.example.com
site2.example.com
site3.example.com

```

and the sites.php file directs the requests so like

```
$sites = array(
    'domain1.com' => 'site1.example.com',
    'domain2.com' => 'site2.example.com',
    etc
);

```

and as far as dns is concerned, each domain just points at the IP of the ubuntu server and drupal handles the rest.

All that is so far so good. Got several working sites.. each domain goes to the right site.. etc. But they use http. How.. do I go about.. getting a certificate that handles the 3 sites so that they can use https? I've not set this up before.. I've been trying to read through whatever I can find.. but I'm confused! Sorry, not sure what to do, I'm just .. lost!

# Answer
Alright .. solution time. Found a solution.. took me a little while to understand. (I, um, guess there's more than one way to skin a cat.. and more than one way to do multi site. This is a solution that works with my particular setup)

So the first step is to set up a virtual host (Once again I'm using Ubuntu.. version 14.04 if you wanna know.. although I'd bet the overall steps would work for any other distribution even if the details were slightly different)

So I set up a virtual host as described here: https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-14-04-lts

So for like, domain1.com on my multisite instillation, my virtual host file looked like this, more or less

```
<VirtualHost *:80>
    ServerAdmin myemail@gmail.com
    ServerName domain1.com
    ServerAlias www.domain1.com
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

```

My DocumentRoot is exactly the same as my drupal base instillation Also, my DNS doesn't use www so .. I'm not sure if I really needed that ailas but I had it

Then.. for this domain.. I had to use LetsEncrypt and got a free certificate as described here: https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-14-04

(And I had to open port 443 to traffic on my server too .. I was using AWS and they use a thing called "security groups" so I added port 443 to the server's security group on the admin panel)

And then.. bingo! My site in my multisite setup can use https now. I expect I would have to simply just repeat the steps for any other sub-site that I want to use https for. I feel like there would be a way to use some kind of like... multi domain certificate.. for like, every site.. somehow ... But this way is free and doesn't take too long!
> 0 votes

# Answer
Are you using a module to handle the multisite configuration? A place where you can associate each site to a domain, theme and other configuration settings. Also you should be able to add https protocol to the desired domain.

If you don't use any module, check settings.php of each site looking for $base\_url where you can change it from http to https.
> -1 votes

---
Tags: 7, multi-sites, ssl
---


# Question
Title: How to add a css file to the admin theme from a front subtheme?
Is it possible to add a css file to the back office from a front sub-theme?

I would like to avoid having to create an admin sub-theme or a module just for the sake of adding one line of css to modify the existing back office styling.

# Answer
> 1 votes
There are a few options to accomplish this.

1. If your admin theme has a `html.tpl.php` you could manually add it in the head using `<link type="text/css" rel="stylesheet" href="linktoyourcssfile">`

Although, know that, when you update your admin theme, the html.tpl.php file probably will be overwritten so you will need to add it every time again.

---

2. Another solution is to install the Add To Head module and add the above line to the head without having the trouble it will be overwritten the next time you update the theme.

It's up to you to see which solution fits you best.

---
Tags: 7, theming
---


# Question
Title: How to display taxonomy term image in a view
I have image field in taxonomy tags. Tags are term referenced in article content type, so now I want to show image field of my taxonomy term in my view. I have tried but I did not find any possible solution.

# Answer
For that you can add a relationship in advanced. Search for your term reference field in it and add the relation.

Then go to fields and search for your image field which is inside of the taxonomy. That way you will be able to add the image.
> 2 votes

---
Tags: views, nodes, entities, taxonomy-terms, media
---


title: Loop through nested array in Twig

text:
# Question
Title: Loop through nested array in Twig
I have created a variable to use in my twig template. The variable consists of a nested array. If I dump the variable I get the following result:

```

dump(gallery_images)
array (size=2)
  'img' =>
    array (size=15)
      0 => 'path-to-file.jpeg'
      1 => 'path-to-file.jpeg'
      .....
   'alt' =>
    array (size=15)
      0 => 'img 1 alt text'
      1 => 'img 2 alt text'

```

I want to loop through gallery\_images and map the alt text to the image. My loop was working fine before I added the nested array / alt text. This is how I expected it to work:

```
{% for gallery_image in gallery_images %}
  <li>
      <img src="{{ gallery_image.img }}" alt="{{ gallery_image.alt }}" />
  </li>
{% endfor %}

```

That did not work, then I tried to call the src and alt with

```
{{ gallery_image.0 }}
{{ gallery_image.1 }}

```

Then I only got 1 file and 1 alt text. What is the correct way to loop through the nested array? Also bear in mind I may want to add title text next.

# Answer
Do you have control over your array structure?

Why not just change it to this:

```
[
  0 => ['alt' => 'alt text', 'img' => 'image-path'],
  1 => ...?
]

```

Because then your logic would work, but right now you have the reversed structure. What you could do is loop over the image paths with `{% for key, path in gallery_images.img %} and use the key to`access gallery\_iamges.alt\[key\]\` (not 100% sure about the exact syntax). Certainly more complicated that way.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to create a "pay per node" "pay to publish" type flow in Commerce 2?
I'm experimenting with Commerce 2 and Drupal 8.

I want to set up a flow where people can pay for a node-- use cases like classified ad listing (pay per post), event signup (pay to register), and so on.

Here's what I did so far.

* Create a content type **classified ad**.
* Create a product **1 month of ad exposure**.
* Add an *entity reference* field on **classified ad** with the default value set to **1 month of ad exposure**. Set the display widget for this field to *rendered entity*. Hide this field with field permissions. (This allows the user to create a **classified ad** node and then see an *Add to cart* button for the correct product after saving.)

So far, so good. But, with this configuration, the **order** doesn't have any information about the original node (content type: **classified ad**). I need to know which node the purchase/order was made for because I want to publish that node.

So, I changed the **default order type**: I added an *entity reference* to content of type **classified ad**. But how do I populate this *entity reference* field with the correct node? Or is there a better way to link the node for which the product was purchased with the order?

# Answer
You need to create an order and an order item yourself and then add those values, I assume you need to do this from the context of your node anyway and not use a standard "buy this product" form.

A snippet from a project:

```
$order_item_values = [
  'type' => 'order_item_type',
  'title' => 'label',
  'unit_price' => new Price(...),
  ...
];
$order_item = $this->entityTypeManager()->getStorage('commerce_order_item')->create($order_item_values);
$order_item->save();

$order_type = $this->orderTypeResolver->resolve($order_item);

$stores = $this->entityTypeManager()->getStorage('commerce_store')->loadMultiple();
$store = reset($stores);

// Create the new order.
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $this->entityTypeManager()->getStorage('commerce_order')->create([
  'type' => $order_type,
  'store_id' => $store->id(),
  'uid' => $this->currentUser()->id(),
  'cart' => FALSE,
]);

$order->addItem($order_item);
$order->save();

$this->cartSession->addCartId($order->id(), CartSessionInterface::COMPLETED);

return $this->redirect('commerce_checkout.form', ['commerce_order' => $order->id()]);

```

You don't even need to use products, you can define an order item that just has a price and reference to your node. But you can also use products to define e.g. the length/price.
> 3 votes

---
Tags: 8, commerce
---


# Question
Title: Disable CSS and JS from a contributed module
I am using Simple Mega Menu module.

I want to disable the CSS and JS provided by this contributed module:

* modules/contrib/simple\_megamenu/js/simple\_megamenu.js
* modules/contrib/simple\_megamenu/css/style.css

In the module description the say

> Simple Mega Menu provide basic styling. You can override the library (css/js) provided by this module simply by adding theses lines into your theme file my\_theme.info.yml

```
libraries-override:
  # Replace an entire library.
  simple_megamenu/base: my_theme/megamenu

```

How do I *disable* the CSS and JS files properly in `my_theme.info.yml`?

# Answer
> 1 votes
I think setting the library to `FALSE` should work:

```
libraries-override:
  # Replace an entire library.
  simple_megamenu/base: false

```

---
Tags: 8, theming
---


# Question
Title: Possible options for single language site other than English?
What are the possible options for having a single language non-English site? I am thinking of performance mostly.

I don’t want prefix or suffix in urls. I don’t preferably want entity language (Language neutral possible in Drupal 8)

Adding a second language, deleting English? Will this have implications?

# Answer
For a Single Language non English site, When you install Drupal 7, it gives you option of selecting the Language. Plus you will need to download the language PO files for your language.

But if you are using Drupal 8 the only requirement is selecting correct language when you install your Drupal. Drupal 8 will automatically download all the language files for you.
> 4 votes

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


# Question
Title: How do I use bigdump.php with Acquia Dev Desktop?
I am trying to import a rather large database (~450MB) on my local machine (running Acquia Dev Desktop). To do this, I was going to use BigDump.

However, I must not be configuring bigdump.php correctly because I keep getting this error:

> Database connection failed due to No connection could be made because the target machine actively refused it.

Here's my database configuration in bigdump.php.

```
$db_server   = 'localhost';
$db_name     = 'testdb';
$db_username = 'drupaluser';
$db_password = '';

```

Do I have to edit something in Acquia Dev Desktop to allow connections?

# Answer
If you want a web based solution for moving in database files, you should be using the Drupal solution for it:

http://drupal.org/project/backup\_migrate

*Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.*

*With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server, and to restore from an uploaded or previously saved database dump. You can chose which tables and what data to backup and cache data is excluded by default.*
> 0 votes

# Answer
While the other answer is certainly an acceptable solution for some... for anyone looking for the answer to the actual original question (like I was):

You enter the port on the $db\_server line.

```
$db_server   = 'localhost:port';

```
> 0 votes

# Answer
Just specifying `$db_server = 'localhost:port';` didn't work for me (BigDump v0.36b). To connect to the DB, BigDump uses `new mysqli(...)` that accepts port as a separate parameter. Thus, all what you need is to edit your `bigdump.php` a bit:

1) Add `$db_port` variable at line 42:

```
$db_port = '33066';

```

2) Use it at line 395:

```
{ $mysqli = new mysqli($db_server, $db_username, $db_password, $db_name, $db_port);
  ...

```
> 0 votes

# Answer
Little late to the game here, but why can't you use the mysql prompt (type `mysql` in terminal) to connect to the database, and use mysqldump to import the db file?

See: https://dba.stackexchange.com/a/24372/10994
> 0 votes

---
Tags: database, importing-exporting
---