# Question
Title: How to replace drush_download_file in Drush 9
`drush_download_file()` existed in includes/drush.inc for Drush 8 and below, but this has been removed in Drush 9 as far as I can tell.

Is there a standard way that file downloads should be executed in custom commands written for Drush 9?

# Answer
> 3 votes
With Drush 9 dropping support for the `drush dl` command, the need for keeping a download function was dropped.

The remnants of `drush_download_file()` were dropped into the `SyncViaHttpCommands.php` example class to demonstrate creating a custom a Drush commandfile. You could copy that as a template if you're looking to mimic the old `drush_download_file()`, or you could use the Guzzle client or some other PHP function; use what works best for your command's download needs.

---
Tags: drush
---


# Question
Title: How do I dynamically change cookie_lifetime?
I'm trying to change cookie\_lifetime dynamically in my D8 project, to set cookie\_lifetime to 0 or to some value(for example 24 hours). I know that this can be partially acomplished by changing cookie\_lifetime variable in sites/default/services.yml, but this is not my case.

I've tried to use this answer but looks like it works only when I use start() method of the session manager.

So how do I change dynamically cookie\_lifetime for existing session? Any answers appreciated, thanks in advance!

# Answer
You can override SessionConfiguration::getOptions to set the cookie lifetime dynamically:

*/mymodule/src/MySessionConfiguration.php:*

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\SessionConfiguration;
use Symfony\Component\HttpFoundation\Request;

/**
 * Sets session cookie lifetime dynamically.
 */
class MySessionConfiguration extends SessionConfiguration {

  /**
   * {@inheritdoc}
   */
  public function getOptions(Request $request) {
    $options = parent::getOptions($request);

    // Set the cookie lifetime dynamically depending on the request.
    $options['cookie_lifetime'] = 30;

    return $options;
  }

}

```

Swap the service class in the container:

*/mymodule/src/MymoduleServiceProvider.php:*

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('session_configuration');
    $definition->setClass('Drupal\mymodule\MySessionConfiguration');
  }

}

```

See Altering existing services, providing dynamic services.
> 4 votes

---
Tags: 8, sessions, cookies
---


title: Add an anchor to the redirect URL

text:
# Question
Title: Add an anchor to the redirect URL
I have a website with some news. I create a view that shows them and filter by category. When I use the filter, it reloads the page and goes at the top of the page. I want it doesn't move on the top of the page.

I added an anchor to the page, but I can't add it to the view redirect link. I tried implementing `hook_view_form_alter()` to add a custom submission handler, but it breaks the entire form and the news are not filtered.

I also looked at `hook_views_query_alter()`, but it doesn't seem it allow to do what I am trying to achieve.

Is there any way to do this?

# Answer
Here is a simple solution to scroll to top of the views results using jquery `scrollTop`

*THEMENAME/js/views-scroll-top.js*

```
(function ($, Drupal) {
  Drupal.behaviors.viewsScrollTop = {
    attach: function (context, settings) {
      //var scrollto = ".view-content"; // top of results
      var scrollto = ".view-filters"; // top of filters
      var url = window.location.href.split('?');
      if (url.length > 1 && $(scrollto).length) {
        $("html, body").animate({ scrollTop: $(scrollto).offset().top }, "slow");
      }
    }
  };
})(jQuery, Drupal);

```

*THEMENAME/THEMENAME.libraries.yml*

```
views-scroll-top:
  js:
    js/views-scroll-top.js: {}

```

*THEMENAME/THEMENAME.theme*

```
function THEMENAME_preprocess_page(&$variables) {
  // attach library only on specific view
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === "view.article.page_1") {
    $variables['#attached']['library'][] = 'THEMENAME/views-scroll-top';
  }
}

```

Change `THEMENAME` to your theme's name
> 1 votes

---
Tags: views, 8
---


# Question
Title: May I know the difference between field_data_body and field_revision_body?
As I am a beginner of this Drupal 7 I have some doubts regarding these database tables.I need a short notes regarding all these database tables.The doubt which I had found is that when I add the content in Drupal 7 it is inserting in these two database tables i,e field\_data\_body and field\_revision\_body and in similar way when I add comment it is also doing the same functionality. I need someone's help.

# Answer
**In short:**

field\_data\_body is the current body data.

field\_revision\_body is a historic backup, that you can revert to if necessary.

**Detailed explanation of revision:**

> Drupal lets you create a new revision every time a node is updated. This allows you to track how the node has changed over time on your site.
>
> To enable this feature you go to the default node editing form (D6: administer/content management/content types/edit/workflow settings; D7: administer/structure/content types/edit/publishing options) and check the box Create a new revision in the node editing form. This will result in a new revision being created every time the node is edited. (Administrators can override this when editing an individual node.)
>
> To view and manage revisions, use the Revisions tab when viewing a node (you must have "view revisions" or "administer nodes" permission to view revisions.) From the Revisions tab, you can view the individual revisions, revert to an earlier revision, and delete revisions (you must have the "administer nodes" or "revert revisions" and "delete revisions" permissions).
>
> One interesting detail of the system is the behaviour of the reverting mechanism. Let's say you have revisions {1,2,3,current}. If you revert to revision #2, a copy of #2 is made and the copy is set as the current revision. Thus, after reverting you'll have {1,2,3,4,current}, where current is a clone of #2, and #4 is the previous current revision.
>
> Another useful feature of the revision system is the Log field, which appears near the "Create a new revision" check box on the node editing form. If you add a message to the Log field when you create a revision, that message will appear on the Revisions tab along with the revision. It is a good idea to add a meaningful Log message whenever you create a node revision, so that others (or you, months later) can see why you changed the node and what your changes were, without having to actually view the previous revision.
>
> You can enhance the revisions tab by installing the contributed Diff module. This module allows you to see the differences between two revisions; without this module, you can only view the entire content of each revision, and it may be difficult to tell exactly what has changed between the revisions.
>
> Note that the node\_revisions table in the database will always have one record associated with each record in the node table, which it keeps track of as the current revision. This will happen even if you do not have revisions enabled. On the other hand, if you have enabled revisioning, you will have multiple entries in your node\_revision table associated with each node, corresponding, not just to the current revision, but all past revisions too.

Source: Node revisions

Related:
> 5 votes

---
Tags: views
---


# Question
Title: Creating a "tag blacklist" for users on a view
I'm looking to allow users to create a "blacklist" of certain tags on a site. My plan was to do this through adding a "Blacklisted Tags" field on the user entity, but I'm open to other solutions. If an item is tagged with a tag they've blacklisted, it won't appear in a view. Is there a way to do this using default views functionality? If not, what's the simplest way to achieve this?

# Answer
> 1 votes
I guess using the ER field on user profiles is the easiest way, it all depends on your requirements.

If you need users to interactively "mark" tags on tags pages or through some other places you could use Flag modules and let them flag tags to blacklist them by simply clicking on the "Blacklist" flag link.

Either way you can build Views that show only content that hasn't been tagged with those.

Add the Contextual filter for the Blacklisted ER field (Default value...) then under `More` check the `Exclude`. This way your list will not show any content that has blacklisted tags.

Of course, your Contextual needs to be configured properly but there are many answers here you can find with all the options listed.

Flags views take some more steps to configure but the logic is the same.

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


title: Print image URL with image style

text:
# Question
Title: Print image URL with image style
I would like to print an image URL with an image-style. This doesn't work, since I don't have a ".value"-value for the image: How to find image style URL from within twig template?

Is there anything different on field-templates?

My code in *field--field-images.html*:

```
{% for item in items %}
    <img src="{{ item.content['#url'].uri }}">
{% endfor %}

```

This doesn't work (results in no filename since .value isn't available:

```
<img src="{{ item.content['#url'].uri.value  | image_style('image_style') }}">

```

This crashes the page:

```
<img src="{{ item.content['#url'].uri | image_style('image_style') }}">

```

Thanks!

# Answer
Change the display mode of your field with the image style you want. And it's ok

But If you want do this with a custom module, you can do this:

```
$imageFile = Media::load($media_mid);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$imageThumbnailUri = $style->buildUrl($imageFile->get('thumbnail')->entity->getFileUri());

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How do you populate existing entities with the default value for a newly added field?
Let's say I have a content type, *Article*, with several fields. I already have hundreds of Article nodes created, but now I want to add a new field. After I set a default value for this field, how can I make it so that all existing Articles have this new field populated with this value? In other words, I don't want all my existing Articles to have a blank value for this new field.

This seems like it *should* be a simple task, but I can't find anything when searching for this issue online.

# Answer
> 1 votes
I just found this module: https://www.drupal.org/project/field\_defaults

It seems like it might work. But I'll withhold accepting this as the answer unless there are better ideas out there.

---
Tags: 8, entities
---


# Question
Title: How to display a token in plain text (without link)?
I created a form with the module "Webform" on "Drupal 8".

In the form submission email, there is a token:

```
[webform_submission:values:profil:entity:field_personnel_sexe]

```

In the inbox, the term taxonomy displays a link. I want to display the text without the link.

How to do this ?

# Answer
> 2 votes
If you want the name of the term, use `[webform_submission:values:profil:entity:field_personnel_sexe:name]`.

If you have another field for the *personnel\_sexe*, for example you want to show the description, you can:

1. Change display for *Token*
2. Use `[webform_submission:values:profil:entity:field_personnel_sexe:description]` as token for the description field

# Answer
> 3 votes
I'm might be late to the game but after way too long, I was able to get a Taxonomy Term without a link using this. I needed this in a hidden field.

`[webform_submission:source-entity:field_department_owner:entity:name]`

`[webform_submission:source-entity:FIELDMACHINENAME:entity:name]`

So now instead of this `<a href="/taxonomy/term/4" hreflang="en">Computer Science</a>` in my webform submissions, I get `Computer Science`.

Since I tried the solution in this ticket numerous times with failure, I thought this would be a good place to log this solution.

# Answer
> 0 votes
You can you **:htmldecode:striptags** at the end of your token.

Care of the security (seen on the token tree page) :

> This suffix has security implications. Use :htmldecode with :striptags. :striptags removes all HTML tags from returned value.

---
Tags: 8, webforms, tokens
---


# Question
Title: Wrong status after updating from 7.64 to 7.66
I recently manually updated my localhost drupal site from 7.64 to 7.66. I ran update.php without errors. When the process finished, I cleared all cache and checked the status. It still reported 7.64. I then re-ran the manual update and got the same results. When I look at system.info, I see:

```
; Information added by Drupal.org packaging script on 2019-04-17
version = "7.66"
project = "drupal"
datestamp = "1555533576"

```

I've noticed other posts (here and here) on the Drupal site that report the same type of symptoms, but, no one has reported a valid solution to resolve this discrepancy. Does anyone know how to get things back in sync?

**UPDATE**: As part of this process, I successfully updated two other sites I maintain to 7.66. The glaring difference that I need explained is after running update.php on localhost, I do not see "Pending Update" as I did on the other two sites.

# Answer
Try to delete the includes folder and add new includes folder from 7.66 version, `bootstrap.inc` defines the drupal version.
> 0 votes

---
Tags: 7, updating
---


title: Display related media entities

text:
# Question
Title: Display related media entities
We are using the `Basic Page` content type and it has an `Entity Reference` field (`field_document`) that points to the `Document (Media bundle)`, which has a `field_document_tag` (taxonomy term field). The `field_document` is not a reference to the taxonomy term, but the `Media` bundle itself. On the `Basic Page` we add a `Related Documents View` at the bottom of the page.

Setup

* Illustration of relationship

Example

Goal

* Based on the current page's `Linked Document`, fetch it's `field_document_tag` values and return other `Basic Pages` that have a `Linked Document` who's `Linked Document->field_document_tags` match.

**How would we use the field value from the current page's `field_document` to pull other related `Basic Pages` with a similar `Linked Document->field_document_tag` values?**

`Basic Page` Fields

* Linked Document (Entity reference - Media - Document bundle, single value, machine name `field_document`)

`Media - Document Bundle` fields

* Document Tags (taxonomy term - vocabulary = tags, machine name = `field_document_tags`)
* Name (text field)
* File

Here are the view settings we tried, but it does not return other related `Basic Pages` even when we add any field under `Contextual Filters` and `Relationship`:

Format

* Unformatted list
* Show: Content | Teaser

Filter Criteria

* Content: Published = Yes
* Content: Content type = Basic Page
* (`field_document_tags: media`) Media: Document Tags

Contextual Filters

* `content: id` -\> When the filter value is not available -\>provide default value-\> content id from url & more -\> `exclude = enabled`
* Relationships -\> `field_document: media`

Additional relationships added under `contextual filters`

* `Taxonomy term referenced from field_document_tag`: relationship -\> `field_document: media`
* `content using field_document`: relationship -\> `field_document: media`

Expected results

* when i am on `page 1`, i expect to see none return
* when on `page 2`, I expected to see `page 4` is returned since the `linked document->field_document_tags` are the same

Current results

* All pages are returned

# Answer
The combination of Relationships and Contextual filters to make it work isn't random, it actually follows your requirements just as you've written them, you only need to add them to your Views configuration the way you describe.

## How Views types work

You want a list of nodes, that is why you create a Content Views Display. Content Views display information that is stored on nodes. When a node has an Entity reference field, that field stores only the information about what entity that is, usually the entity ID. For example, when referencing files what is stored in the Entity file reference field is the FID. The node (the node's table in the database) doesn't store anything more about that field.

The entity that is being referenced may have fields of its own. These fields are stored with the entity data (in the database they are stored in the related "entity table"). Simply put; nodes have their own tables of data, other entities have their own separate tables of data. The connections between nodes and other entities can be done through small "bridges" that are Entity reference fields that store only the connection between two IDs.

When you create Views of a certain type, you're basically choosing which entity database table to pull information from. To overly simplify for clarity: If you want to list nodes, views set nodes table and you can only show data stored in nodes, if you want to list documents, views set files table and you can only show data stored in files.

## How to show referenced data in Views

But what if you want to show more information about the related entities, like in your case? You need to add Relationships towards the related entities. Relationships make *other* database tables data available into your Views!

Once you add some related entity Relationship to your Views you will see new options appear under Fields and Filters, options related to the referenced entity, options you didn't have before you added the Relationship.

And that is what you need to do to your Content Views. Your content references some Files and you want files data to be available in your content views. If you wanted to list content that shares the same file reference you would then add another Relationship, the "backwards" Relationship pointing towards the content that uses the file field we added the Relationship to, and add a Contextual filter that uses that second "backwards" Relationship.

## How to show data that is referenced by referenced data

But in your case, there is one extra layer of connection, and you need to add 2 *more* Relationships. You're not matching the referenced files, you're matching the taxonomy terms that are referenced from files that are referenced from content:

Page \> File \> Term \< Other Files \< Other Pages

Here are the steps for your case:

1. Create Content Views Block Display listing Page nodes
2. Add Relationship towards your "Linked Document" field, you can require it since you won't have nodes with empty document field in the results
3. Add another Relationship **Taxonomy term referenced from field\_document**, it will use the first Relationship automatically, you can require it since that field won't be empty either, so you won't be excluding any nodes you don't need to if you require it

So far we've been going in the direction from nodes to their referenced files, to terms referenced from those files.

Now we have all that information in Views, we can start matching "backwards" to get term siblings and file second cousins.
4. Add the third Relationship **Taxonomy term using field\_document\_tag** and make it use the **second** Relationship. You can require it
5. Add the fourth Relationship **Content using field\_document** and make it use the **third** Relationship, you can require it

This fourth Relationship is pointing to **nodes** that reference files that refrence terms that are referenced from files that are referenced from nodes listed in this Views.
6. Now we can add a **Contextual ID filter** from `Content` Category, and configure it:
Make it use the fourth Relationship (the only one available)
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Content**
**Basic Page**
Hide View if the argument doesn't validate, or some other options that makes sense to you.
7. Place the Block on Basic pages, adjust the `Node from URL` and other Block options.

## Remove the current node from the list

The node you're currently viewing will also be listed. To Exclude it add the **second Contextual ID filter**:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`More`
**Exlude**
> 1 votes

# Answer
Although @prkos answer lead to my solution, I wanted to add that i had to modify the `where` clause because it was still not filtering. In order to alter the `where` clause I had to create a `mymodule` custom module that had to call `hook_views_query_alter()` in the `mymodule.views_execution.inc` file.

It went something like this.

```
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  foreach($query->where as &$condition_group) {
    foreach($condition_group['conditions'] as &$conditions) {
      /**
       * my_field_name_value is the Linked Document->media.field_document_tag.target_id (taxonomy term id)
       */
      if($condition['field'] == 'my_field_name') {
        $condition = [
          'field' => 'my_field_name',
          'value' => 'my_field_name_value',
          'operator' => '=',
        ];
      }
    }
  }
}

```
> 0 votes

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


title: Using parameters in routes

text:
# Question
Title: Using parameters in routes
I am using the pathauto module to create url aliases for all user account url, so:

`/user/[uid]` will become `/u/[user:account-name]-[user:uid]`

which means:

`/user/36` will become `/u/john-smith-36`

In my custom module, I have created a route to fire a controller when `/u/john-smith-36/settoken?token=123456` url is accessed.

**The controller will:**

1. Fetch the account of the current logged in user.
2. Update the text field `field_user_push_token` with the query parameter value: 123456
3. Save the account of the current logged in user.
4. Redirect the user to the page: `/thank-you`

I am finding a difficulty on how to use parameters in route for the user account url !

**save\_push\_token.routing**

```
save_push_token.SavePushToken:
  path: '/{user}/settoken'
  defaults:
    _controller: '\Drupal\save_push_token\Controller\SavePushTokenController::SavePushToken'
  requirements:
    _permission: 'access content'

```

**SavePushTokenController.php**

```
<?php

namespace Drupal\save_push_token\Controller;

use Symfony\Component\HttpFoundation;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SavePushTokenController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   */
  public function SavePushToken(AccountInterface $user, Request $request) {

// Get token value from url.
    $request = Request::createFromGlobals();
    $userpushtoken = $request->query->get('token');

// Load the (current logged user) account.
// No need to load the user account because of {user}
    // $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Set the (token).
    $user->set('field_user_push_token', $userpushtoken);

// Save the (current logged user) account.
    $user->save();

// Redirect to "/thank-you" page.
    return new RedirectResponse('/thank-you');

  }
}

```

But simply the controller is not fired when I access for example `/u/john-smith-36/settoken?token=123456` url is accessed.

any help on how to properly use parameters in routes ?

# Answer
> 3 votes
I see two problems. First your routing file has the path set to:

```
path: '/{user}/settoken'

```

To do what you're describing I would expect to see:

```
path: '/u/{user}/settoken'

```

Second, are you opposed to using a second parameter in the URL instead of the Get Method variable? If not opposed you can add a second parameter that will handle the 'token' variable.

In your routing file you can set up the pareters like this:

```
path: '/u/{user}/settoken/{token}'

```

The url would then be (cleaner I think):

```
/u/john-smith-36/settoken/123456

```

Lastly, to access the parmeters in your controller you shouldn't need to access the Globals. The parameters get passed to your function directly. Use this as the function declaration to pick up the variables:

```
public function SavePushToken($user, $token)

```

---
Tags: 8, routes
---


# Question
Title: Not able to access uploaded images in AWS
1. When we upload an image using the URL 'https://website.com/file/add' , the image is **getting uploaded**. While uploading, we have chosen the destination as ' Public local files served by the webserver' and the media folder as 'Media Root'.
2. But when we hover over the uploaded image inside https://website.com/admin/content/file, its showing "**The file doesn't exist**".
3. And when we try to access the uploaded image, then **either** of the following messages would show up:-
    1. **Warning: filesize(): stat failed for public://download (2).jpg in file\_save()(line 614 of /var/www/html/website/includes/file.inc)**.
    2. **Page not Found Error - The requested The requested URL "/sites/default/files/image.jpg" was not found on this server**.

My website is working under Drupal 7(7.63) and hosted in AWS. There are 2 servers under a load balancer. PHP:- Version 5.5.9-1ubuntu4.17. The public directory mentioned in the file system is 'sites/default/files' and it has given 777 permission.

Could anyone please guide me on how to solve this issue? Is this issue related to server-specific configurations?

Thanks

# Answer
> # Configuration examples
>
> For example, on many systems the Apache process runs as a user called "www-data" that is in a group called "www-data". This user should be able to read all of the files in your Drupal directory either by group permissions or by "other" permissions. It should not have write permissions to the code in your Drupal directory. If you use features of Drupal which require the "files" directory, then give the www-data user the permission to write files only in that directory.
>
> The following is an example file listing of a safe configuration showing two files in a site where uploaded files are stored in the "files" directory. In order to see the file permissions set for your setup, go to the command line and type: `ls -al`.
>
> ```
> drwxrwx---  7 www-data    greg-group  4096 2008-01-18 11:02 files/
> drwxr-x--- 32 greg-user   www-data    4096 2008-01-18 11:48 modules/
> -rw-r-----  1 greg-user   www-data     873 2007-11-13 15:35 index.php
>
> ```
>
> source: Securing file permissions and ownership

Your issue is that the /files folder has the wrong owner. (The 1st one is the owner, the 2nd is the group).

In SSH command line, you need to do:

```
cd /var/www/html/website/sites/default

```

For checking purposes do

```
ls -al

```

You will see that your files folder has the wrong owner. (The 1st one is the owner, the 2nd is the group).

To fix it, now do:

```
sudo chown www-data:<the-group-name> -R files

```

**Note:** Replace `<the-group-name>` with your actual group name, without the `<>` part. I'm just indicating it's a place holder.

> **DO NOT DO:**
>
> ```
> NOTE: THIS IS AN INSECURE CONFIGURATION
> drwxrwx---  7 www-data  www-data  4096 2008-01-18 11:02 files/
> drwxrwx--- 32 greg-user www-data  4096 2008-05-16 11:48 modules/
> -rw-rw-rw-  1 www-data  www-data   873 2007-11-13 15:35 index.php
>
> ```
>
> source: Securing file permissions and ownership

Related:
> 0 votes

---
Tags: files
---


# Question
Title: How do I overwrite the controller for admin/content?
On admin/content, I have created different views for articles and basic pages (the default content types created from Drupal). On admin/content, it shows *Content | Article | Basic Page*. When I already have *Article* and *Basic page* as separate.

On admin/content, I would like to show as Blank means no data instead of showing all data.

I tried the following code.

`modules/custom/content/src/Routing/RouteSubscriber.php`

```
namespace Drupal\content\Routing;

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

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

  /**
   * Used to alter routes.
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setDefaults(array(
        '_controller' => '\Drupal\content\Controller\ContentOverviewController::overview',
      ));
    }
  }

}

```

I'm trying to override its default controller, so it show blank.

The code for the controller is the following one.

```
namespace Drupal\content\Controller;

use Drupal\system\Controller\SystemController;

/**
 * Class ContentOverviewController.
 */
class ContentOverviewController extends SystemController {

  /**
   * Content Overview.
   */
  public function overview($link_id) {

    $build = [
      '#markup' => $this->t('Hello World!'),
    ];
    return $build;
  }

}

```

The code doesn't seem to work.

I also tried to disable the content view, but that is not needed.

# Answer
As per documentation:

> The \Drupal\example\Routing\RouteSubscriber::alterRoutes method is an event subscriber because it extends RouteSubscriberBase. Therefore, the class must be registered as an event subscriber service.

In your example you also need a `content.services.yml`:

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

```
> 1 votes

# Answer
Check a namespace in your RouteSubscriber.php

You have

```
namespace Drupal\content\Routing

```

Should be

```
namespace Drupal\mcontent\Routing

```

Because your custom module is **mcontent** (not **content**)
> 0 votes

---
Tags: 8
---


# Question
Title: Alter webform messages found in WebformMessageManager
1. List item

Is there a way to change the hardcoded webform messages from /webform/src/WebformMessageManager.php?

for example, the one on line 284

```
  case WebformMessageManagerInterface::DRAFTS_PREVIOUS:
    $t_args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.drafts')->toString()];
    return $this->t('You have pending drafts for this webform.') . ' ' . $this->t('<a href=":href">View your pending drafts</a>.', $t_args);

```

# Answer
The beauty about Services is that they can be overridden to your liking.

So all we have to do is extend the WebformMessageManager so we inherit all of it's properties and methods and simply alter the method you need to modify.

my\_module/src/**CustomWebformMessageManager.php**

```
<?php

namespace Drupal\my_module;

use Drupal\webform\WebformMessageManager;
use Drupal\webform\WebformMessageManagerInterface;

class CustomWebformMessageManager extends WebformMessageManager implements WebformMessageManagerInterface {

  /**
   * {@inheritdoc}
   */
  public function get($key) {
    // Get custom message from settings.
    if ($custom_message = $this->getCustomMessage($key)) {
      return $custom_message;
    }

    $webform = $this->webform;
    $source_entity = $this->sourceEntity;

    // Get custom message from settings with arguments.
    switch ($key) {
      case WebformMessageManagerInterface::PREVIOUS_SUBMISSION:
        $webform_submission = $this->entityStorage->getLastSubmission($webform, $source_entity, $this->currentUser);
        $args = [':href' => $this->requestHandler->getUrl($webform_submission, $source_entity, 'webform.user.submission')->toString()];
        return $this->getCustomMessage('previous_submission_message', $args);

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSIONS:
        $args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.submissions')->toString()];
        return $this->getCustomMessage('previous_submissions_message', $args);
    }

    // Get hard-coded messages.
    switch ($key) {
      case WebformMessageManagerInterface::ADMIN_PAGE:
        return $this->t('Only webform administrators are allowed to access this page and create new submissions.');

      case WebformMessageManagerInterface::ADMIN_CLOSED:
        $t_args = [':href' => $webform->toUrl('settings-form')->toString()];
        return $this->t('This webform is <a href=":href">closed</a>. Only submission administrators are allowed to access this webform and create new submissions.', $t_args);

      case WebformMessageManagerInterface::ADMIN_ARCHIVED:
        $t_args = [':href' => $webform->toUrl('settings')->toString()];
        return $this->t('This webform is <a href=":href">archived</a>. Only submission administrators are allowed to access this webform and create new submissions.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_DEFAULT_CONFIRMATION:
        $t_args = ['%form' => ($source_entity) ? $source_entity->label() : $webform->label()];
        return $this->t('New submission added to %form.', $t_args);

      case WebformMessageManagerInterface::FORM_SAVE_EXCEPTION:
        $t_args = [
          ':handlers_href' => $webform->toUrl('handlers')->toString(),
          ':settings_href' => $webform->toUrl('settings')->toString(),
        ];
        return $this->t('This webform is currently not saving any submitted data. Please enable the <a href=":settings_href">saving of results</a> or add a <a href=":handlers_href">submission handler</a> to the webform.', $t_args);

      case WebformMessageManagerInterface::HANDLER_SUBMISSION_REQUIRED:
        $t_args = [':href' => $webform->toUrl('handlers')->toString()];
        return $this->t('This webform\'s <a href=":href">submission handlers</a> requires submissions to be saved to the database.', $t_args);

      case WebformMessageManagerInterface::DRAFT_PREVIOUS:
        $webform_draft = $this->entityStorage->loadDraft($webform, $source_entity, $this->currentUser);
        $t_args = [':href' => $webform_draft->getTokenUrl()->toString()];
        return $this->t('You have a pending draft for this webform.') . ' ' . $this->t('<a href=":href">Load your pending draft</a>.', $t_args);
      case WebformMessageManagerInterface::DRAFTS_PREVIOUS:
        $t_args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.drafts')->toString()];
// ALTER THE LINE YOU WANT
        return $this->t('MY CUSTOM VIEW PENDING DRAFT MESSAGE.') . ' ' . $this->t('<a href=":href">MY CUSTOM VIEW PENDING DRAFT MESSAGE.</a>.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_UPDATED:
        $t_args = ['%form' => ($source_entity) ? $source_entity->label() : $webform->label()];
        return $this->t('Submission updated in %form.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_TEST:
        return $this->t("The below webform has been prepopulated with custom/random test data. When submitted, this information <strong>will still be saved</strong> and/or <strong>sent to designated recipients</strong>.");

      case WebformMessageManagerInterface::TEMPLATE_PREVIEW:
        $t_args = [':href' => $webform->toUrl('duplicate-form')->toString()];
        return $this->t('You are previewing the below template, which can be used to <a href=":href">create a new webform</a>. <strong>Submitted data will be ignored</strong>.', $t_args);

      case WebformMessageManagerInterface::PREPOPULATE_SOURCE_ENTITY_TYPE:
      case WebformMessageManagerInterface::PREPOPULATE_SOURCE_ENTITY_REQUIRED:
        return $this->t('This webform is not available. Please contact the site administrator.');

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSION:
        $webform_submission = $this->entityStorage->getLastSubmission($webform, $source_entity, $this->currentUser);
        $args = [':href' => $this->requestHandler->getUrl($webform_submission, $source_entity, 'webform.user.submission')->toString()];
        return $this->getCustomMessage('previous_submission_message', $args);

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSIONS:
        $args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.submissions')->toString()];
        return $this->getCustomMessage('previous_submissions_message', $args);
    }

    return FALSE;
  }

}

```

my\_module/**my\_module.services.yml**

```
services:
  webform.message_manager: # The service ID you want to alter
    class: Drupal\my_module\CustomWebformMessageManager // Your Custom Class
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@logger.channel.webform', '@renderer', '@messenger', '@webform.request', '@webform.token_manager']

```

> **Important:** Make sure you give your module a higher weight than webform so your service alter runs.

You could use the Modules weight module.

OR

In Devel's execute php, execute `module_set_weight('my_module', 10);`
> 1 votes

# Answer
Extending the WebformMessageManager is the right approach to address the immediate issue/limitation of hardcoded messages.

To address the specific issue of changing the hardcoded WebformMessageManagerInterface::DRAFTS\_PREVIOUS message in /webform/src/WebformMessageManager.php, I created Issue #3050884: Allow WebformMessageManagerInterface::DRAFTS\_PREVIOUS to be customized
> 1 votes

---
Tags: 8, hooks, webforms
---


# Question
Title: Composer.json deletes dir even with preserve path
I am running composer on Drupal 7 and I am just trying to update my site; however when I run `composer update`, the composer deletes all the preserve paths I had specified.

My structure is as follows:

```
composer.json

composer.lock

web/

    -sites/default

```

in my composer.json I have as follow:

```
{
...
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/7"
    }
],
"require": {
   ...
},
"conflict": {
    "drupal/core": "8.*"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
      "sort-packages": true
},
"autoload": {
    "classmap": [
        "scripts/composer/ScriptHandler.php"
    ]
},
"scripts": {
    "pre-install-cmd": [
        "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "pre-update-cmd": [
        "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "post-install-cmd": [
        "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-update-cmd": [
        "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-create-project-cmd": [
        "DrupalProject\\composer\\ScriptHandler::removeInternalFiles"
    ]
},
"extra": {
    "installer-paths": {
        "web/": ["type:drupal-core"],
        "web/profiles/{$name}/": ["type:drupal-profile"],
        "web/sites/all/drush/{$name}/": ["type:drupal-drush"],
        "web/sites/all/libraries/{$name}/": ["type:drupal-library"],
        "web/sites/all/modules/contrib/{$name}/": ["type:drupal-module"],
        "web/sites/all/themes/contrib/{$name}/": ["type:drupal-theme"]
    },
    "patches": {
        "cweagans/composer-patches": {
            "Call the preserve paths hooks" : "https://github.com/SebCorbin/composer-patches/commit/1cb9bacba51f8bba0c5f3f322c3bb61e4ceae974.patch"
        }
    },
    "preserve-paths": [
        "web/sites/all/drush",
        "web/sites/all/libraries",
        "web/sites/all/modules/contrib",
        "web/sites/all/modules/custom",
        "web/sites/all/modules/features",
        "web/sites/all/themes/contrib",
        "web/sites/all/themes/custom",
        "web/sites/all/translations",
        "web/sites/default"
    ]
}

```

}

What ends up happening is it install the core and modules correctly in web/ folder, but deletes all the preserve paths as well. Any suggestions as to why i am having this problem? Thank you.

I have tried to put composer.json in the web/ folder as well, that just imports all the require modules and core in a subfolder (web/web/).

I am now getting:

`Files of installed package were overwritten with preserved path x/web/sites/default!`

`Files of installed package were overwritten with preserved path x/web/sites/all/libraries!`

and the preserve paths didn't do anything.

# Answer
> 2 votes
It looks like you haven't installed the plugin. Just run:

```
composer require drupal-composer/preserve-paths

```

And try again.

If it still doesn't work, you'll probably need to report it as a bug to the plugin's issue queue.

---
Tags: 7, updating, composer
---


# Question
Title: How do I know what setSetting is suppose to be?
I am creating a custom content entity and in the BaseFieldDefinitions, I am trying to create a field for assigning a user as the designated assigner and will follow up with a assignee. So far, the code has been pretty easy to follow and makes sense, except for setSetting.

Basically the field below works, but its copy and pasted from drupal console as boiler plate code. What I don't understand is the setSetting part. If I comment out `->setSetting('target_type', 'user')`, the field displays but no longer works.

So my question is, how am I suppose to know, or figure out, that I should be typing in 'target\_type' and value 'user'? I went through the API but haven't managed to find any references to this. And I don't understand the setSetting below it either, 'handler' = 'default. I can comment that out and it works fine. So what gives?

How am I suppose to know what to set in the setSettings part? As I also noticed, not every field definition even has this.

```
$fields['assigner'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Assigner'))
  ->setDescription('The person who will issue this Task.')
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'author',
      'weight' => 0,
  ])
  ->setDisplayOptions('form', [
      'type' => 'entity_reference_autocomplete',
      'weight' => 5,
      'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
      ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

# Answer
> 0 votes
You can look at the source code of the corresponding field type class to get an idea of the available settings.

`target_type` is something specific for an ER field

Base classes for field types provided in Drupal core

Almost all field types are derived from one of the above base classes, e.g. there are several number field types deriving from NumericItemBase

Custom field types are usually located in `module_name/src/Plugin/Field/FieldType`

---
Tags: 8, entities, users, forms
---


# Question
Title: Related content in a view using entity reference
I've browsed through (and tested) every solution I could find here to this seemingly simple challenge.

I've got multiple content types (fx. News, Releases, Events, Videos etc.) that are referencing the content type "Artists" using an entity reference-field.

I want to have related content-blocks that shows the related news, releases etc. for the artists references in the node.

I've done this in D7 but it seems the approach have changed a bit since then (?).

What I thought I should do (with content type 'release' as example:

* Create a related release-block in views
* The a relationship 'Content using field\_artist', require this relationship
* Add contextual filter, select relationship, select 'content id from URL' as default value

But no results appear when doing this. If I remove the relationship I get 1 result, the node I'm already on...

What am I doing wrong?

# Answer
As mentioned in the comments you don't need any Relationships to filter out the related content. Simply add the Contextual filter for your Entity Reference field, and configure it with a Default value to pick up Content ID from URL, and validation criteria to the Artist content.

---

You can use the Relationship if you need information other than the Artist node ID in your Views, for example, if you have an independent Views Page showing all Releases, and you want your Contextual filter to be in your URL showing the Artist name and not the ID number:

`/releases/Beatles`

for all Releases nodes referencing the Artist Beatles.

And it's still working the same as it did in Drupal 7, apart from the different wording in the names, you just added the wrong Relationship.

It should *not* be the 'Content using field\_artist', but **Content referenced from field\_artist**.

'Content using' that field are the nodes *with* the ER (News, Releases, etc.) so you're just pointing back to what you already have in your Views. This is a "backwards" Relationship.

The 'Content referenced from field\_artist' Relationship is pointing towards the Artist nodes, and through adding that Relationship you'll have the Artist data available in your (Releases) Views. This is the Relationship you want to you in this case.
> 0 votes

---
Tags: 8, views
---


title: Sell a unique product with

text:
# Question
Title: Sell a unique product with
I would like to sell a single product (a CD) on a Drupal 8 site and I'm looking for a simple way to pay.

I guess in this case, it's not worth using the Commerce or Ubercart module.

In fact, I intend to make a page presenting the CD with a button referring to a means of payment and return once the transaction made.

Is this the right solution? Or maybe there is another way of doing things?

Thank you for any suggestions.

# Answer
Yes, it seems a full commerce solution is an overkill for a single product.

If you don't need visitors to pay through your site you can use some solutions that take them away to payment processors website to complete the order.

You will have to pull reports and sort out the accounting side of things from the payment processor records, since you won't have orders on your website.

You have to investigate for the ways you "deliver" the product once someone pays for your product, and how that is tracked, maybe again through the payment processor.
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: Remove Filter When Exposed Filter is Selected
Currently, I'm working on an events view in Drupal 8 which needs to only show events that are on or after the current date (now() filter). This view also has an exposed date range filter that allows user's to select a start date and end date. The start date can be from before the current date.

The problem is that the now() filter isn't letting user's see anything before the current date. How can I remove the now() filter when a user enters a start date so they see the list of all the events in the date range they've selected?

# Answer
> 0 votes
You can do this by combining two "Authored on" Filters, one regular and the other one Exposed with the `OR` Operator working between them/groups of Filters.

Add the regular "Authored on" Filter **Is less than or equal to** `now`.

Add another "Authored on" Filter and Expose it with your preferred settings, how you want your visitors to use it, don't enter a default value.

Then under `Add` dropdown choose `And/Or Rearrange`, Create a new filter group. move the Exposed "Authored on" to it, and choose the `OR` between the groups, while keeping `AND` within groups.

Recreate any Filters you might need in the second group.

That's it!

Be very careful of your entire Filters configuration. If you have Exposed filters in the first group too, they will not be able to be applied at the same time (because OR), which may be confusing to users...

---
Tags: views
---


title: Change article date format

text:
# Question
Title: Change article date format
I'd like to change the date format that is used for articles in Drupal 8. It looks like it uses the `Default medium date` format by default. I added my own format at `admin/config/regional/date-time`, but I can't find where to edit the format that articles use.

Is there a way to do this from the CMS or does this need to be done in code?

# Answer
So after spending more time than I care to admit looking into this, I've come up with two solutions to this.

**Solution 1**

One way to do it is with the date function that darol100 mentioned in his answer. Modifying his example for my case, in my `node--article.html.twig` file, I changed:

```
{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

```

to

```
{% set createdDate = node.getCreatedTime|date('j F Y') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}

```

The advantage to this approach is that it's easy and quick. The disadvantage is I'm not using Drupal's built-in date format system.

**Solution 2**

In order to use Drupal's date format system, I first created my custom format at `admin/config/regional/date-time`. Then I edited `node--article.html.twig` as follows:

```
{% set createdDate = node.getCreatedTime|format_date('my_custom_format') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}

```

This assumes I named my custom format "**My Custom Format**", which results in the machine name `my_custom_format`.

While this solution requires an extra step, I feel it's the more Drupal way to do it.

I learned about it on this page about Drupal's Twig Filters.
> 49 votes

# Answer
If you want to change the date format base on article content type level. You can edit/add the following code `post.published_at|date` and use a filter to alter the date format.

**node--article.html.twig**

```
{# Here are few example #}
{{ post.published_at|date(format='j  F  Y') }} {# Output = 10 March 2001#}
{{ post.published_at|date(format="F j, Y, g:i a") }} {# Output = March 10, 2001, 5:16 pm#}
{{ post.published_at|date(format='m/d/Y') }} {# Output 10/3/2001 #}

```

Twig use the same naming code as php date format. For more information about twig date formats visit - http://twig.sensiolabs.org/doc/filters/date.html
> 11 votes

# Answer
I'm more for Chris's solution 2. As he says it IS more the drupal way... but it's not the best option yet.

format\_date() has been deprecated and will be removed before Drupal 9... meaning that one day, you'll do a drupal update and this will break.

Instead, it's better to do this in your .theme file in a preprocess function.

```
function [theme_name]_preprocess_node(&$variables) {
  $variables['date'] = \Drupal::service('date.formatter')->format($variables['node']->getCreatedTime(), 'my_custom_format');
}

```
> 10 votes

# Answer
It is also possible to find the date format already in use, and just change that in the UI. Just compare what you see on the page with the date formats in `admin/config/regional/date-time/`

If you change eg "Default medium date" it will change the dates using this format without touching any template/twig files.

Date formats can also be set/translated per language for multi language setup.
> 3 votes

# Answer
An observation about what Duke said:

> format\_date() has been deprecated and will be removed before Drupal 9...

Yes, Drupal function format\_date() defined in *core/includes/common.inc* is, in fact, deprecated. But, when you use the twig filter *format\_date()* you are NOT calling that Drupal function, instead of that you are using the twig filter defined by Drupal in TwigExtension::getFilters(), and this filter calls DateFormatter::format().

Hence, using the twig filter *format\_date()* is safe and Chris's solution 2 is fine.
> 2 votes

# Answer
You can customize the format in node.html.twig like this:

```
{{ node.createdtime|date(format="Y-m-d") }}

```
> 2 votes

# Answer
You can create your own Submitted By field by using Display Suite to create a Token Field.

In Drupal 8 /structure/ds/fields

Then add a field using html and tokens like...

```
By [node:author] on [node:created:custom:F j, Y]

```
> 1 votes

# Answer
To be sure that I change only the characters of the date but not any surrounding HTML elements, I use the following hook:

```
function [theme_name]_preprocess_field(array &$variables) {
  if ($variables['field_name'] === 'created') {
    $timestamp = $variables['element']['#items']->value;
    $markup = \Drupal::service('date.formatter')->format($timestamp, 'html_date');
    $variables['items'][0]['content']['#markup'] = $markup;
  }
}

```

Replace `[theme_name]` with the name of your theme and `html_date` with your desired time format, one of those you find under `/admin/config/regional/date-time`.
> 0 votes

# Answer
You can have all the formats PHP for Date and Time

```
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
date("m.d.y");                         // 03.10.01
date("j, n, Y");                       // 10, 3, 2001
date("Ymd");                           // 20010310
date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
date("H:i:s");                         // 17:16:18
date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)

{% set createdDate = node.getCreatedTime|date('F j, Y, g:i a') %}
<div class="newsSingleAuthorDate">
      {% trans %}Submitted by <span>{{ author_name }}</span>  on {{ createdDate }} {% endtrans %}
</div>

```
> -1 votes

# Answer
I used the following code for node--article--full.html.twig :

```
<li class="post-date">
    {% set day = node.createdtime|date("d") %}
      <span class="day">{{ day }}</span>
    {% set month = node.createdtime|date("M") %}
        <span class="month">{{ month }}</span>
 </li>

{% set date = node.createdtime|date("M d, Y") %}
   <span>{{ date }}</span>

```
> -2 votes

---
Tags: 8, datetime
---


# Question
Title: Add print button in the "Review order" page
I want to know, is there any way to add print button to "Review order" page.

by clicking this button, a pop up page is loaded with good style for print mode and user can print the cart items , taxes and all information in Review order page.

Please guide me.

# Answer
> 0 votes
You can try using the PrintFriendly & PDF module, which has a version for Drupal 7 and one for Drupal 8. (The development snapshot for Drupal 8 has been created on July 27, 2017.)

The description of the module says:

> The #1 Print and PDF button for your Drupal site. Printer Friendly pages without coding, css, or print.css. Fast, easy, and professional.
>
> The Print Friendly & PDF button saves paper and ink when printing or creating a PDF. It's fast, easy, and looks great when printed. Add the button now, and your users will see the difference.

Using this module you can add a print button to review order pages.

# Answer
> 0 votes
The issue of PrintFriendly & PDF does not work with views in case you need, you can try with https://www.drupal.org/project/entity\_print if is view page.

---
Tags: commerce
---


# Question
Title: How to clone a node without translations
I have a site with multiple language. Assume I have a node (nid = 1) with **origin languages is en** and **translate to es**. And I clone this node with code:

```
$node = Node::load(1);
$nodeDuplicate = $node->createDuplicate();
$nodeDuplicate->save();

```

And I have a new node (nid = 2), and the new node have two content translate en, es same the node id 1.

But I don't want clone all content translate. **I only want to clone one language es or en**. So how can do that?

# Answer
> 3 votes
A suggestion : use `->removeTranslation()` to get rid of the languages you don't want to be cloned.

Example to get rid of 'es language' so that we clone only the english version :

```
$langcodetoremove = 'es';
$node = \Drupal\node\Entity\Node::load(1);
$node->removeTranslation($langcodetoremove);
$nodeDuplicate = $node->createDuplicate();
$nodeDuplicate->save();

```

hope this helps

# Answer
> 3 votes
You can create a new node with the field values retrieved from the (translated) node:

```
$node = Node::load(1);
$values = $node->getTranslation('es')->toArray();
// remove nid, uuid, vid and revision details from $values
$node_duplicate = Node::create($values);
$node_duplicate->save();

```

# Answer
> 2 votes
Try this:

```
$node = Node::load(1);
$nodeDuplicate = $node->createDuplicate();

$langcode = 'fr';
$nodeDuplicate->removeTranslation($langcode);
$nodeDuplicate->save();

```

# Answer
> 0 votes
You can try to use this code for copy translation with all field types and all node types:

`<?php
 use Drupal\node\Entity\Node;
 $exclude = [
 'nid',
 'vid',
 'revision_timestamp',
 'revision_uid',
 'revision_log',
 'revision_default',
 'revision_translation_affected',
 'content_translation_source',
 'content_translation_outdated',
 'created',
 'changed',
 'default_langcode',
 'uuid'
 ];
 $node = Node::load(NODE_ID);
 if (!empty($node->hasTranslation(LANGCODE))) {
 $node = $node->getTranslation(LANGCODE);
 }
 $node_type = $node->getType();
 $fields = $node->getFieldDefinitions('node', $node_type);
 $copyied_fields = [];
 foreach ($fields as $field_name => $field_definition) {
 $field_name = $field_definition->getName();
 if (!in_array($field_name, $exclude)) {
 $field_value = $node->$field_name->value;
 if (empty($field_value)) {
 $field_value = $node->$field_name->getValue();
 }
 $copyied_fields[$field_name] = $field_value;
 // Add body format.
 if ($field_name == 'body') {
 $copyied_fields['body'] = array(
 'value' => $node->body->value,
 'format' => 'full_html',
 );
 }
 }
 }
 $new_node = Node::create($copyied_fields);
 $new_node->save();`

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


# Question
Title: Reference current user when creating a content type
I am creating a new content type and one of the fields I d like to add owner.

I ve chosen reference - user as the field type Type of item to reference = user

How do I make the default value the name of the current user?

Many Thanks

# Answer
> 0 votes
You can set default values in a hook\_ENTITY\_TYPE\_create:

```
/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {
  if ($node->getType() == 'my_content_type') {
    $node->field_user->target_id = \Drupal::currentUser()->id();
  }
}

```

---
Tags: users
---


title: Submenu tree problem

text:
# Question
Title: Submenu tree problem
I have a website build with Drupal 7 CMS and I am using the Submenu tree module. Everything was working fine for months, but few weeks ago I have received a feedback from the client that all the links of sub and sublink content was disappeared. I have checked my local version of the website, and there are no any links also.

I have tried to use the same module on another local Drupal 7 website and the result is the same - no matter how I try to set it up - it does not show any sub or sublink content links.

Does anyone has the same problem? Anybody using the same module - can you confirm that it works fine with your website ?

# Answer
> 0 votes
I have managed to fix this issue by reverting the module to an older version.As I see in the release notes

> Issue #3037177 by itcrowd72, omrmankar, troybthompson: PHP 7.2 each() function is deprecated

The php version I am still using is 5.6. It looks like the new module version is not ok with 5.6, or at least with my setup.

---
Tags: 7, navigation
---


title: Can't edit block

text:
# Question
Title: Can't edit block
I´m new with Drupal. I started a month ago with Drupal 8. Everything works fine. I had some own custom blocks. Then I added some javascript to one block.

Immediately after that editing of the block or other content was not possible. I can edit nodes, if I open them, there are tabs. But my own block is not possible to edit. If I remove this block, I can edit all other content. If I publish it again, edit button (pen) is missing.

How I can edit my own block again?

The code in the block is taken from here: http://kotisivuapu.suntuubi.com/?cat=194&aid=19&fid=57&mid=57&c=57

I have some code in the block before this script: some links to
\- own folders, like /sites/default/files/picture.gif" \- internet, www-pages

I see, this is problem with this code and I´ll do it with php.

# Answer
> 0 votes
If you want to embed javascript into a block make sure that your format is not stripping out parts of your code. Full HTML supplied with core is probably good enough.

Paste the following javascript code just to test that everything works properly.

```
<script>
document.write("test javascript");
</script>

```

And make sure your format is **Full HTML**

**NOTE:** The recommended way to introduce javascript into a Drupal site would be with a theme or a module as described here

# Answer
> 0 votes
Problem solved!

This line: document.write("Onnea: " + nimipv + "!");

Shortened like this and everything works: document.write("Onnea: " + nimipv + "!");

---
Tags: blocks
---


# Question
Title: Does $element['#title'] need to be escaped with check_plain()?
I see (with grep) that the value of `$element['#title']` in a render element is sometimes sanitized with `check_plain()`, and sometimes printed unfiltered.

Which one is correct? Is the value considered safe to print? Or does it depend on the theme hook?

Examples from core:

```
modules/field/field.form.inc
314:        'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",

```

(notice the "!" in the placeholder, this means that `format_string()` will not escape the placeholder value)

```
modules/field/field.module
1052:  $variables['label'] = $variables['label_hidden'] ? NULL : check_plain($element['#title']);

```

This question applies in both ways:

* When setting `$element['#title']` in a render element.
* When printing the value of `$element['#title']`.
* When printing a `$variables['title']` value that was extracted from a render element property.

Note: Very often the `$element['#title']` property comes directly from a `t()` call.

# Answer
It's user input and should be considered unsafe; you should always sanitise it.

For the specific example you've given where it isn't, the title is already sanitised before it's passed to the theme function containing the `t()` call. This happens in `field_multiple_value_form()`

```
$title = check_plain($instance['label']);

...

$element = array(
  ...
  '#title' => $multiple ? '' : $title,
  ...
);

```

As an aside, if you ever did need to preserve HTML in the title for whatever reason, you could consider using `filter_xss()` instead.
> 1 votes

# Answer
The correct way is to check with `check_plain()` to prevent cross site scripting attacks in the first example from `modules/field/field.form.inc` `$element['#title']` passed as `arg` to `t` function.
if you look at t function source code it call format\_string function it check plain `$args[$key] = check_plain($value);`.
> 0 votes

---
Tags: 7, theming
---


# Question
Title:
Classification: {{ content.field_classification.value }}
 not displaying
Hoping someone can assist me please.

I am trying to display the value of a custom field in a bootstrap sub theme

I have created my `node--testtype.html.twig` template and that seems to work.

I'm trying to just show the content of one field, the machine name is field\_classification.

When I use `<h1>Classification: {{ content.field_classification.value }}</h1>` the Classification displays as expected, but the value of my field\_classification doesn't.

Can anyone see what I am doing wrong please as thought I d copied the correct code from what I have read?

# Answer
`{{ content }}` is a render array and does not have a `.value`, just use `{{ content.field_name }}`

You only need the `.value` when you want to print the raw values of an entity object like `node`, e.g. `{{ node.field_my_integer.value }}`
> 1 votes

---
Tags: theming, bootstrap-theme
---


# Question
Title: How can I use month name as contextual filter?
I have a contextual filter to filter by month:

Date in the form of MM (01 - 12).

However, I want to filter by month name (january, february, march, etc.) to get nicer URL and breadcrumb.

Is there an easy way to do it?

# Answer
You can programmatically alter the contextual filter value of "january" to "01 - 12" in hook\_views\_pre\_view

```
/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for my_special_view.
  if ($view->id() == 'my_special_view') {
    // insert here some php magic to format "January" to "01".
    $og_arg = t('@og_arg', ['@og_arg' => $args[0]], ['langcode' => 'en']);
    $date = date_parse($og_arg);
    // assign formatted value.
    $args[0] = $date['month'];
  }
}

```
> 0 votes

# Answer
I needed to make it work for multilingual websites. This is how I solved it in the end:

```
use Drupal\views\ViewExecutable;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if (($view->id() == 'my_special_view') && isset($args[0]) && !is_numeric($args[0])){
    $og_arg = $args[0];
    switch($og_arg){
      case strtolower(new TranslatableMarkup('January', [], ['context' => 'Long month name'])):
        $args[0] = '01';
        break;
      case strtolower(new TranslatableMarkup('February', [], ['context' => 'Long month name'])):
        $args[0] = '02';
        break;
      case strtolower(new TranslatableMarkup('March', [], ['context' => 'Long month name'])):
        $args[0] = '03';
        break;
      case strtolower(new TranslatableMarkup('April', [], ['context' => 'Long month name'])):
        $args[0] = '04';
        break;
      case strtolower(new TranslatableMarkup('May', [], ['context' => 'Long month name'])):
        $args[0] = '05';
        break;
      case strtolower(new TranslatableMarkup('June', [], ['context' => 'Long month name'])):
        $args[0] = '06';
        break;
      case strtolower(new TranslatableMarkup('July', [], ['context' => 'Long month name'])):
        $args[0] = '07';
        break;
      case strtolower(new TranslatableMarkup('August', [], ['context' => 'Long month name'])):
        $args[0] = '08';
        break;
      case strtolower(new TranslatableMarkup('September', [], ['context' => 'Long month name'])):
        $args[0] = '09';
        break;
      case strtolower(new TranslatableMarkup('October', [], ['context' => 'Long month name'])):
        $args[0] = '10';
        break;
      case strtolower(new TranslatableMarkup('November', [], ['context' => 'Long month name'])):
        $args[0] = '11';
        break;
      case strtolower(new TranslatableMarkup('December', [], ['context' => 'Long month name'])):
        $args[0] = '12';
        break;
    }
  }

```
> 0 votes

---
Tags: views, 8
---


title: How to make a module contribution

text:
# Question
Title: How to make a module contribution
I find some bugs in a contrib module I have fixed them and I want to commit my change to that module ,what is the right procedure to do that .

I did this is that ok.

1. create a new drupal site instlation.
2. cd to the module folder then clone the module git inside it (following the Version control instruction page)
3. I have fixed the problem , then commit and push to the git repo.

the problem with this method is that I can't explain the problem in detail with a just a commit so should I open a module issue in drupal website and link it to my commit ?

# Answer
Until pull requests on https://git.drupalcode.org become a thing the procedure still is basically as follows:

1. Create an issue in that module's issue queue on drupal.org.
2. Git clone that module's repo and checkout the branch where you wanna fix something.
3. Fix the bug.
4. Create a patch: `$ git diff > [project_name]-[short-description]-[issue-number]-[comment-number].patch`
5. Upload that patch in the issue from step 1. and set the issue to "Ready for review".

Now everybody finding the same bug can apply that patch at best using Composer and maybe `cweagans/composer-patches` until the patch got committed and released by one of the module's maintainers.

The full documentation can be found on drupal.org:
> 1 votes

---
Tags: community-official-site
---


# Question
Title: How to render image uploaded from a configuration form
I'm working on a custom module, that contains a block and I'm currently having an issue to render an image that is being uploaded through a form at the configuration of the block.

I'm getting this error:

> Error: Call to a member function getFileUri() on null in Drupal\onyx\_experiencia\Plugin\Block\onyx\_experiencia-\>build() (line 52 of....)

The file is being uploaded correctly to the specified directory. I've been reading about similar problems and errors but haven't found the correct solution.

What I'm trying to achieve is to get the *uri* of the image uploaded through the form. I've read that some times is necessary to load the entity or the image first, I've already tried but I still get the same error but on the line where I try to load the file.

**This is the code:**

```
<?php

namespace Drupal\onyx_experiencia\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Druap\image\Entity\ImageStyle;

/**
 * Provides a 'Hello' Block.
 *
 * @Block(
 *   id = "onyx_experiencia",
 *   admin_label = @Translation("Servicios OnyxGroup"),
 *   category = @Translation("Servicios OnyxGroup"),
 * )
 */
class onyx_experiencia extends BlockBase implements BlockPluginInterface {

 /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();
    $build = array();

    if (!empty($config['card_title'])) {
      $name = $config['card_title'];
    }
    else {
      $name = $this->t('Onyx Group Card');
    }

    if (!empty($config['card_text'])) {
      $cardText = $config['card_text'];
    }
    else {
      $cardText = $this->t('A service of Onyx Group');
    }

    $cardImg = File::load($config['card_image']);
    $cardUrl = $config['card_link'];

    $imgVar = array(
        'style_name' => 'thumbnail',
        'uri' => $cardImg->getFileUri(), //<--- THIS IS LINE 52:ERROR
    );

    $image = \Drupal::service('image.factory')->get($cardImg->getFileUri());
      if($image->isValid()) {
          $imgVar['width'] = $image->getWidth();
          $imgVar['height'] = $image->getHeight();
      } else {
          $imgVar['width'] = $imgVar['height'] = NULL;
      }

    $build[]['#attached']['library'][] = 'onyx_experiencia/onyx-experiencia-style';

    $build['CardTitle'] = array(
            '#prefix' => '',
            '#markup' => $this->t('Hello @name!', array('@name' => $name,)),
            '#suffix' => '',
        );

    $build['CardText'] = array(
            '#prefix' => '',
            '#markup' => $this->t('Card text: @cardText!', array('@cardText' => $cardText,)),
            '#suffix' => '',
        );

    $cardImg_array = array(
        '#prefix' => '',
        '#theme' => 'image_style',
        '#style_name' => $imgVar['style_name'],
        '#width' => $imgVar['width'],
        '#height' => $imgVar['height'],
        '#uri' => $imgVar['uri'],
        '#suffix' => '',
    );

      $renderer = \Drupal::service('renderer');
      $renderer->addCacheableDependecy($cardImg_array, $cardImg);

    return $build;

  }

 /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['card_title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Card Title'),
      '#description' => $this->t('Type title of the service card.'),
      '#default_value' => isset($config['card_title']) ? $config['card_title'] : '',
    ];

    $form['card_text'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Card Text'),
      '#format' => 'full_html',
      '#description' => $this->t('Type the list of the services.'),
      '#default_value' => isset($config['card_text']) ? $config['card_text'] : '',
    ];

    $form['card_image'] = [
        '#type' => 'managed_file',
        '#title' => t('Card image background'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(25600000),
        ),
        '#theme' => 'image_widget',
        '#preview_imgage_style' => 'medium',
        '#upload_location' => 'private://card_service_img',
        '#progress_message' => 'One moment while we save your file...',
        '#required' => TRUE,
    ];

    $form['card_link'] = [
        '#title' => t('Type card link. Example: /erp_cloud'),
        '#type' => 'url',
    ];

    return $form;
  }

 /**
   * Custom submit actions
   */
  public function custom_submit_form($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    //Perform the required actions
  }

 /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['card_title'] = $form_state->getValue('card_title');
    $this->configuration['card_text'] = $form_state->getValue('card_text');
    $this->configuration['card_image'] = $form_state->getValue('card_image');
    $this->configuration['card_link'] = $form_state->getValue('card_link');
  }

}

```

# Answer
I finally got it working, I was kind of lost. The key was to correctly submit the image at *blockSubmit function* and effectively load the file at the *build function*

**This is the final code that is working for me**

```
<?php

namespace Drupal\onyx_experiencia\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Druap\image\Entity\ImageStyle;

/**
 * Provides a 'Hello' Block.
 *
 * @Block(
 *   id = "onyx_experiencia",
 *   admin_label = @Translation("Servicios OnyxGroup"),
 *   category = @Translation("Servicios OnyxGroup"),
 * )
 */
class onyx_experiencia extends BlockBase implements BlockPluginInterface {

 /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();
    $build = array();

    if (!empty($config['card_title'])) {
      $name = $config['card_title'];
    }
    else {
      $name = $this->t('Onyx Group Card');
    }

    if (!empty($config['card_text'])) {
      $cardText = $config['card_text'];
    }
    else {
      $cardText = $this->t('A service of Onyx Group');
    }

    $build[]['#attached']['library'][] = 'onyx_experiencia/onyx-experiencia-style';

    $build['CardTitle'] = array(
            '#prefix' => '',
            '#markup' => $name,
            '#suffix' => '',
        );

    $build['CardText'] = array(
            '#prefix' => '',
            '#markup' => $cardText,
            '#suffix' => '',
        );

    $cardImage = $this->configuration['card_image'];
    if (!empty($cardImage[0])) {
        if ($file = File::load($cardImage[0])) {
            $build['CardImg'] = array(
                '#theme' => 'image_style',
                '#style_name' => 'medium',
                '#uri' => $file->getFileUri(),
            );
        }
    }

    $cardLink = $this->configuration['card_link'];
    $build['CardLink'] = array(
        '#markup' => $cardLink,
    );

    return $build;

  }

 /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['card_title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Card Title'),
      '#description' => $this->t('Type title of the service card.'),
      '#default_value' => isset($config['card_title']) ? $config['card_title'] : '',
    ];

    $form['card_text'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Card Text'),
      '#format' => 'full_html',
      '#description' => $this->t('Type the list of the services.'),
      '#default_value' => isset($config['card_text']) ? $config['card_text'] : '',
    ];

    $form['card_image'] = [
        '#type' => 'managed_file',
        '#title' => t('Card image background'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(25600000),
        ),
        '#theme' => 'image_widget',
        '#preview_imgage_style' => 'medium',
        '#upload_location' => 'private://card_service_img',
        '#progress_message' => 'One moment while we save your file...',
        '#default_value' => isset($this->configuration['card_image']) ? $this->configuration['card_image'] : '',
        '#required' => TRUE,
    ];

    $form['card_link'] = [
        '#title' => t('Type card link. Example: /erp_cloud'),
        '#type' => 'url',
        '#default_value' => isset($this->configuration['card_link']) ? $this->configuration['card_link'] : '',

    ];

    return $form;
  }

 /**
   * Custom submit actions
   */
  public function custom_submit_form($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    //Perform the required actions
  }

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

      $cardImage = $form_state->getValue('card_image');
      if ($cardImage != $this->configuration['card_image']) {
          if (!empty($cardImage[0])) {
              $file = File::load($cardImage[0]);
              $file->setPermanent();
              $file->save;
          }
      }

    $this->configuration['card_title'] = $form_state->getValue('card_title');
    $this->configuration['card_text'] = $form_state->getValue('card_text');
    $this->configuration['card_image'] = $form_state->getValue('card_image');
    $this->configuration['card_link'] = $form_state->getValue('card_link');
  }

}

```
> 2 votes

---
Tags: 8, forms, blocks, media
---


# Question
Title: Get all nodes of a specific content type and print the data of each node inside page.html.twig
I have a content type (*Flower*) with two fields: *Name* and *Color*.

In *my-theme/templates/page.html.twig*, I want to print the name and the color of each flower.

```
<div id="page">
    {% for flower in flowers %}
        <div class="flower-item">
            <h3>{{ [Flower Name Here] }}</h3>
            <p>{{ [Flower Color Here] }}</p>
        </div>
    {% endfor %}
</div>

```

How can I get all nodes of a given content type and print the values of each node inside page.html.twig?

# Answer
Putting this in `page.html.twig` is a **bad idea**. Since this template will be used for every page rendered from Drupal using that theme.

Instead you should simply create a View. Views can be used to query a certain content type and to list nodes in a certain view mode or just certain fields of these nodes (the title and a color field for example). Then configure your view to provide a block and place that block in the region you wanna have the Flowers printed.

Views and block will take care of the caching. And you can use the block's visibility settings to have it displayed only on paths or nodes where you really need it.

---

If you still insist on coding this in a template (not recommended, too performance-heavy, too much logic in templates) you first have to pass all Flower nodes to the template.

```
/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {

  $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();

  // Get all Flower node IDs.
  $nids = $query->condition('type', 'flower')->execute();

  // Load all Flower nodes.
  $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  // Pass them to page.html.twig.
  $variables['flowers'] = $nodes;
}

```

Then in your `page.html.twig`:

```
{% for flower in flowers %}
  {{ flower.title.value }}
  {{ flower.field_color.value }}
{% endfor %}

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Why does the favicon sometimes not show up and generate "page not found" errors, and other times does show up
As the question implies, on occasion Drupal's log is showing that the favicon is not found. Indeed, it does not show in the browser tab or address bar. At other times, even within the same surfing session, it does show up.

Why does it do this and how can I prevent it so that the favicon will always show?

I am using version Drupal 7.22. with a custom subtheme and an admin theme (Stark).

My favicon is set in the subtheme theme configuration at sites/default/files/images/favicon.ico and that is located there as I have checked via FTP.

The log shows the browser is looking in example.com/favicon.ico.

The custom subtheme I use has `<link rel="shortcut icon" href="http://example.com/sites/default/files/images/favicon.ico"; type="image/vnd.microsoft.icon" />` in the source code and the admin theme (Stark) uses `<link type="image/vnd.microsoft.icon" href="http://example.com/misc/favicon.ico"; rel="shortcut icon">` and this file also exists in that location (not actually using example.com, of course).

Drupal is using clean URLs.

The web server is Apache on Debian Linux.

Thank you.

# Answer
> 4 votes
Some browsers search for favicon under http://example.com/favicon.ico without checking. But they are minority now.

Most respect:

```
<link rel="icon" href="http://example.com/img/icon.png">

```

as described by W3C.

If your site tries to use `<link>` approach but fails on some pages, like admin pages rendered using different template, and you do not have favicon.ico in default location, you will get exactly described effects.

If browser is looking for http://example.com/favicon.ico when you have proper `<link rel="shortcut icon">` it is a browser problem, not yours. It means browser (or at least that part of it's code) is outdated, unless it looked under correct URI first and got another error, but then you would see two errors in log, one for right place, second for outdated one. In Mozilla's queue there is a number of reports about improper favicon detection by FireFox - in example this one. It shows how even modern browsers can sometimes fall back to old methods.

# Answer
> 2 votes
Quick and easy fix for this pain, is to use the Redirect module and make a redirect for it.

Once the module is enabled, go to `admin/config/search/redirect/add` and use `favicon.ico` under from and to should be the actual location of your theme's `favicon.ico`.

# Answer
> 0 votes
If you're using Apache, the best way I found to fix it is to put:

```
<Location /favicon.ico>
  ErrorDocument 404 "No favicon"
</Location>

```

This code should work in your vhost file or should also work in the .htaccess file, see http://httpd.apache.org/docs/2.4/sections.html for more details

# Answer
> -1 votes
You can try https://www.drupal.org/project/favicon It to make requests to http://example.com/favicon.ico forward to the actual site's true favicon.

---
Tags: 7, files
---


# Question
Title: Can't submit data when rendering a webform programmatically
I'm working on a Drupal 8 project, when trying to load a webform programmatically in a controller, the webform is rendered correctly but when data has been submitted no values founded on webform results page (still always empty).

Injecting the form in a paragraph as block and then submit data work perfectly, also submitting data from the webform node page works as it should (We can find data on form results page).

Here is my code:

MyController.php

```
namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\webform\Entity\Webform;

class MyFormPage extends ControllerBase {

  public function content() {
      $webform = Webform::load('my_webform_id');
      $view_builder = \Drupal::service('entity_type.manager')->getViewBuilder('webform');
      $webform        = $view_builder->view($webform);
      return [
        '#theme'   => mycontroller_page',
        '#content' => [
          'title'     => t('I am a page from your controller'),
          'form'      => $webform,
        ],
      ];
  }
}

```

mycontroller-page.html.twig

```
<article>
  <h1>{{ content.title }}</h1>
  <div>
    {{ content.form }}
  </div>
</article>

```

Any idea about this behaviors? Thanks

# Answer
@see How to embed a Webform?

I recommend using something like...

```
return [
  '#theme' => mycontroller_page',
  '#content' => [
    'title' => t('I am a page from your controller'),
    'form' => [
      '#type' => 'webform',
      '#webform' => 'my_webform_id',
    ],
  ],
];

```
> 3 votes

---
Tags: 8, webforms
---


# Question
Title: How do I resolve an unnamed requirements problem during an update?
I am attempting to update my Drupal 8.2 instance to Drupal 8.6.4. I have faithfully followed the manual installations steps found here https://www.drupal.org/docs/8/update/update-core-manually.

I replace the core and vendor folders and replace all the files in the root with the 8.6.4 files. I rename the 8.6.4 defaults.settings.php file to settings file, move my unique settings into that file and upload it to sites/default. I then visit update.php, but I get stuck at the requirements stage.

There is an error saying "Requirements Problem: Check the messages and try again." There are, however, no messages.

I'm happy to keep troubleshooting this but I need to know where I'm going wrong. How can I discover what the Requirements Problem(s) are?

**Some Other Details**

* Both the database and the Drupal server are running in a AWS VPC.
* The server is a linux machine: VERSION="16.04.5 LTS (Xenial Xerus)
* Drush is not working or installed. The original sysadmin didn't install it as part of the Drupal installation and I haven't added it since.
* Composer is installed but I've never used it to manage Drupal versions or dependencies.
* Drupal is behind an nginx reverse-proxy. I have the made allowances for Drupal in the nginx conf file as recommended here: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/. Mostly just this rule `location ~ '\.php$|^/update.php' {...}`
* There are other non-Drupal tables in the same DB that Drupal uses.
* Drupal tables are prefixed: drupal\_
* We use drupal in a headlessly. A separate Node.js app interacts with Drupal via Drupal Rest routes and is also connected to the same DB as Drupal.

**Issues I've already resolved**

* Missing sourcecode for hello\_world module. Removed hello\_world from Drupal table: drupal\_key\_value
* `$settings['update_free_access'] = TRUE;`

**Things I've tried:**

* checking the apache2 error logs. No errors thrown.
* checking the apache2 access logs. Just shows access to update.php

Let me know if I should post any more information. Also, if using drush or composer would help, I'm interested in getting those going on my site anyway, and would be happy to install them. In summary, during a Drupal 8 upgrade, Drupal complains about Requirement Problems but never lists them. How can I discover what the Requirements Problem(s) are?

# Answer
Since the database information was transferred into a new settings.php file instead of keeping the old one, it is possible that the the custom value for the path to the synch configuration directory is not found.

Reference: Upgrading Drupal

Look for the code:

```
$config_directories['sync'] = 'sites\default\files\your-config-folder

```

in the settings.php file & update it to match the address on your web server.

*"This solution worked for me. In order to find that config\_gobblygook, I looked in docroot/sites/default/files and in there is a folder named config\_ and then a whole bunch of letters and numbers. I copied that full name and then inserted it into line 247 of the settings.php file."*

The same problem is described here with a similar solution.

Related:

Otherwise make sure the most recent nginx.conf file for Drupal is in use, as there have been changes to that to fix the update.php issue. See:
> 0 votes

# Answer
The problem was trying to update from 8.0 to 8.6 directly. Update each minor version sequentially from 8.0 to 8.6 and then to 8.6.10. That will work.
> 0 votes

---
Tags: updating
---


# Question
Title: Is it a security issue to put CSRF token in drupal settings?
I have an application where I created a REST resource to update a field on the user object to store bookmarked items.

When you do a post request to a rest resource you are required to use a header with X-CSRF-Token.

You can get this by making a call to "/session/token". But I'm wondering if it's OK, if you have a "bookmarks" widget on all pages to include the token in drupal settings.

Or is this some kind of security issue?

Is it better to make a call through javascript to get the token, rather than have it in the drupal settings?

Or as long as you're logged in, having the csrf token in drupal settings is not a problem?

```
/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$vars) {

  // Add CSRF token to page for authenticated users.  Token
  // is required by rest resources on POST requests.
  if ($vars['logged_in']) {

    $route = \Drupal::routeMatch()->getRouteObject();
    $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

    if (!$is_admin) {
      $vars['#attached']['drupalSettings']['user']['csrf'] = \Drupal::csrfToken()->get(CsrfRequestHeaderAccessCheck::TOKEN_KEY);
    }
  }
}

```

# Answer
`Drupal.settings`, and other global variables, *will* be available to cross-origin scripts that happen to be injected (possibly maliciously) into the site. The same applies to any other part of the document body, like meta tags or JSON script tags.

Sensitive tokens should ideally be stored in a place that is restricted to same-origin scripts, which includes cookies and localstorage: https://stackoverflow.com/questions/34782493/difference-between-csrf-and-x-csrf-token

(This shouldn't normally be critical, because script injection shouldn't be possible in the first place, and is a severe vulnerability by itself. But it's probably still a good idea to rely on multiple layers of security.)
> 2 votes

---
Tags: 8
---


title: Migration not skipping a row

text:
# Question
Title: Migration not skipping a row
I have a talent for finding the hard issues. I have a custom migration class importing taxonomy terms. The class is an in-house customization, and we have it working happily on other sites. On my site, it is not working. There is a chance this is related to the data, which is coming from the client and possibly not clean. Here is my issue. I am implementing the public function prepareRow($current\_row) with the intent of skipping some rows that I know will cause trouble. Specifically, anything with a non-numeric id value.

1. I know the function is called, I see "Gojira!" appear
2. I know the value that is causing an error
3. The function is not being respected by the system.

Here is my function:

```
public function prepareRow($current_row) {
  $safe = FALSE;
  if(is_numeric($current_row->id)){
    $safe = TRUE;
    // problem value is $current_row->id == 'n'
  }
  if(!$safe) {
    print('Gojira!'); // this is seen in the migration ui
    //die();  // this is ignored
    return FALSE; // this is ignored
  }

  // allow parent to skip a row
  if (parent::prepareRow($current_row) === FALSE) {
    return FALSE;
  }
}

```

Here is the error I see on the migration ui page:

```
Migration failed ... General error: 1366 Incorrect integer value: 'n' for column 'sourceid1' at row 1

```

Please help.

# Answer
The hint that solved this was in the error message:

```
for column 'sourceid1'

```

This column is in the Migration class's map table, where it tries to make a record of what it has processed. The "fix" for this is to prevent the errant data from getting that far in the system. I am coding a custom getItem to do the filtering for this issue there.
> 0 votes

# Answer
Maybe it can help.

```
    // Row object containing the specific item just imported.
    $row = $event->getRow();

    if (!$row->needsUpdate()) {
      return;
    }

```
> 0 votes

---
Tags: 7, migrations
---


title: Send email after content update

text:
# Question
Title: Send email after content update
I have create a new content type with a field of **email**. In this field I put the email address of the person I want.

The case is: I want every time the node of this content type updated, to send an email to the address from the email field.

With Rules module I cannot find a proper way to make it work because Rules are on a very early point of development.

There is two problems with rules: 1st - I have create a simple action to send an email every time the node is updated. This is work fine. When I create a condition "Node is of type" and select only one content type the sending email action is still working for all content types.

2nd - I cannot find any proper method for what suppose to write to the reciptient field to send the email to the address from the email field.

Can any one help? Any thoughts?

# Answer
> 1 votes
First, use the -dev version of Rules.

Second, always use the "Show a message on the site" action for testing. This is a LOT easier to debug than "Send email". You can use tokens in the message to test that the values are what you expect them to be, then when you get the right values you can use the email action with those same tokens in your email.

Third, always clear your caches after making changes to a rule.

Fourth, the issue queue contains many complete examples you can use. For instance, here is an example of how to show a system message when an "article" type node is created (from https://www.drupal.org/project/rules/issues/2852342). Try this you will see that "Node is of Type" DOES work to restrict the type - the message will never be shown if you create a node that is not an article:

```
uuid: c1b8486c-a96b-4f53-903a-8a08cb85355d
langcode: en
status: true
dependencies: {  }
id: test_rule
label: 'Test rule'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: f8e466d6-51d6-41ea-93f1-34436470f3c3
  conditions:
    id: rules_and
    uuid: 7776a869-e0c6-4499-b09e-da727722213e
    conditions:
      -
        id: rules_condition
        uuid: 6bf893f5-7bcf-420c-9a62-7e1cb9a884f6
        context_values:
          types:
            - article
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: f0bcccfd-685f-4a74-a4fd-0d36b540037a
    actions:
      -
        id: rules_action
        uuid: ec599dbc-cb40-448b-b37b-129d956c2eb7
        context_values:
          message: '<b>Test rule triggered</b> {{ node.title }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message

```

And finally, here's a complete example for how to send e-mail to an address contained in a field value. This example assumes you have a node content type with machine name "email" which has a single-valued required field of type "email" named "field\_email".

```
uuid: bc3fb7fd-0cbd-416c-8b71-9d6b710eb0ce
langcode: en
status: true
dependencies: {  }
id: send_email_when_content_of_type_email_is_created
label: 'Send email when content of type "email" is created'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 265d153c-9ce9-4250-a1b7-b8670be7826c
  conditions:
    id: rules_and
    uuid: 4f570c4e-3558-4628-96dc-aebb7b6d9e65
    conditions:
      -
        id: rules_condition
        uuid: 8014e5b0-680d-46c3-94fc-0785022447ca
        context_values:
          types:
            - email
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: 25127564-6ab9-4587-b1b9-9336781aab9e
    actions:
      -
        id: rules_action
        uuid: 16f51441-39e8-4872-a3c2-e4e12a339f1e
        context_values:
          message: 'Email is {{ node.field_email.value }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: 2c636fe9-9b9a-46b8-b930-81b9730f5ac2
        context_values:
          to:
            - '{{ node.field_email.value }}'
          subject: 'An Email node was created'
          message: 'An Email node was created'
          reply: ''
          language: ''
        context_mapping: {  }
        context_processors:
          to:
            rules_tokens: {  }
          subject:
            rules_tokens: {  }
          message:
            rules_tokens: {  }
          reply:
            rules_tokens: {  }
          language:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_send_email

```

If you import these Rules onto your site and inspect how they're constructed they will help you learn how to do this yourself.

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