# Question
Title: Why is my form only redirected sometimes?
I want to have a user register, and be redirected to a node create form. Here's how I'm doing it thus far.

# The setup

I have a route, `my_module.register` that is handled by `MyController::register()`. It returns the user register form, like so:

```
class MyController extends ControllerBase {
  public function register() {
    return $this->entityFormBuilder->getForm(User::create([]), 'register');
  }
}

```

I also have this service, `my_module.form_alter_service` (just pretend all the implied dependency injection is there):

```
class MyFormAlterService {

  public function registerFormAlter(array &$form, FormStateInterface $form_state) {
    if ($this->currentRouteMatch->getRouteName() == 'my_module.register') {
      $form['actions']['submit']['#submit'][] = [$this, 'redirectToAddNode'];
    }
  }

  public static function redirectToAddNode(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect(/* imagine a node form route here */);
  }

}

```

I have also implemented `hook_form_FORM_ID_alter()`:

```
function my_module_form_user_register_form_alter(array $form, FormStateInterface $form_state) {
  \Drupal::service('my_module.form_alter_service')->registerFormAlter($form, $form_state);
}

```

# The expected behavior

I fill out the user register form at `/my_module/register`, hit submit, and am taken to the desired node add form.

# What happens instead

I fill out the user register form at `/my_module/register` and end up on my user edit page.

*But then*, if I delete that user, clear the cache, and repeat the process with the exact same credentials, **it works as expected**.

# What I know

* I am getting debugging output from every part of the process, so I know each part is running.
* I am using the exact same pattern for the login form; identical code in the form alter, and that works great.
* I can also get debug output from `Drupal/user/EventSubscriber/AccessDeniedSubscriber::onException()` which redirects authenticated users who are visiting the `user.register` route to their edit page. So I know that's causing the unwanted redirect, when the unwanted redirect happens.
* I tried removing the `user.roles:authenticated` cache context from the form, and adding `user`, but that didn't seem to change things.

# The actual question(s)

Why is the form initially not respecting the redirect I set in the submit handler? Why does a cache clear change that behavior?

# Answer
The cause for the erratic behavior is probably the condition for the current route name in the form alter method. The form is not necessarily built in the same request as the custom controller, it could be served from cache or built in a POST request.

At the moment you have the condition for the route name because the controller invokes the default register form and the form alter doesn't know where it is called from. So you need to make the form distinguishable, for example by a different form handler, a field value in the new entity before you hand it over to the form builder or put the form alter code in a custom form class extending the core user form.

BTW why are you not redirecting by the destination query string you can set on the user register link, then you don't need code?
> 0 votes

---
Tags: 8, forms, routes, redirection
---


# Question
Title: Subdomain drupal sites cannot read domain cookies
I have set a cookie from domain (.example.co) and its .NET platform & reading those cookie from drupal site(test.example.co).

While retrieving it shows empty, I have used $\_COOKIE.

This link suggests it is possible, also we are setting domain name while creating cookies? Is it possible to use while retrieving cookies?

Also i have found this link, is that interrelated?

# Answer
Thanks all for you reply,

Finally reason has been found, since there is an DOT(.) in the cookie name set. It cannot be retrieved.

https://harrybailey.com/2009/04/dots-arent-allowed-in-php-cookie-names/
> 0 votes

# Answer
You need to provide an appropriate value for `$cookie_domain` in settings.php.

e.g.

```
$cookie_domain = 'example.co';

```

That will allow you to set/retrieve cookies from example.co on foo.example.co, and vice versa.
> 2 votes

# Answer
In order to use other subdomains' cookies, you need to set both site's cookie domain to .example.com.
> 0 votes

---
Tags: 7, cookies, subsites
---


title: Render form in template

text:
# Question
Title: Render form in template
I have made the following .tpl.php template:

```
<?php print drupal_render($element["term"]); ?>
<?php print drupal_render($element["search"]);?>
<?php print drupal_render($element["advanced_search"]);?>
<?php print drupal_render_children($element);?>

```

But the form tag is not generated, so the form cannot be submitted ... what am i doing wrong?

# Answer
You can add search box in a preprocess function in your template.php:

```
<?php
/*
 *  Preprocess page.tpl.php to inject the $search_box variable back into D7.
 */
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

```

Then you just need to print the variable in your page.tpl.php:

```
<?php print $search_box; ?>

```
> 6 votes

# Answer
1. You can add search box in a preprocess function in template.php of your theme:

```
function MYTHEME_preprocess_page(&$variables){
      $search_box = drupal_render(drupal_get_form('search_form'));
      $variables['search_box'] = $search_box;
    }

```
2. Then you just need to print the variable in your page.tpl.php:

```
<?php print $search_box; ?>

```

You could also use module\_invoke, but you shouldn't have php logic in template files:

```
  $block = module_invoke('search', 'block_view', 'search');
  print render($block);

```
> 2 votes

# Answer
I wish I had a better explanation, but if you're using a custom theme hook, make sure it doesn't match your form id. For example, if your form is "mymodule\_my\_form," don't name your theme hook "mymodule\_my\_form." I've run into issues rendering a form in a template because of this.
> 2 votes

# Answer
You just need to render complete form with individual fields.

Just change the last line of your template file with this one -

```
<?php print drupal_render_children($element['form']);?>

```
> 0 votes

# Answer
Find form\_id of the form you want to display. ( you may use Get Form ID module )

Then you can put any form in any place, example:

```
$form = drupal_get_form('YOUR_FORM_ID');
print drupal_render($form);

```
> 0 votes

# Answer
i had this issue, realized was printing `drupal_render($form)` in a fake html tag(some design time html left-over) hence no real form - removed it and there stood the real form staring at me.
> 0 votes

# Answer
This is the only solution now;

```
$form = drupal_get_form('custom_example_form', $adverts);
  print '<form id="'.$form['#id'].'" accept-charset="UTF-8" method="'.$form['#method'].'" action="'.$form['#action'].'">';
  print render($form['name']);
  print render($form['descriere']);
  print render($form['submit']);
  print render($form['form_id']);
  print render($form['form_build_id']);
  print '</form>';

```

See this https://drupal.stackexchange.com/a/111833/23593
> 0 votes

# Answer
```
$wnid = 5; //form id
$wnode = node_load($wnid); load the node id
$form = drupal_get_form('webform_client_form_' . $wnid, $wnode, array());
print render($form);

```

This will give you your webform.
> 0 votes

# Answer
My form was in an include file, mymodule/includes/mymodule.example\_form.inc, doing the following worked for me:

```
function mymodule_preprocess_main_page(&$variables) {
    module_load_include('inc', 'mymodule', 'includes/mymodule.example_form');
    $example_form = drupal_render(drupal_get_form('mymodule_example_form'));
    $variables['example_form'] = $example_form;
}

```

Then in template file, `<?php print $example_form; ?>`
> 0 votes

---
Tags: 7, forms, theming
---


# Question
Title: How to inject custom dependence in custom entity?
On Drupal 8, in a custom entity class, I'm trying to load a repository in the constructor to be able to use custom functions in the `preSave()`.

```
class MyEntity extends ContentEntityBase implements MyModuleInterface {

private $customStuff;

public function __construct(array $values, $entity_type, &$bundle = FALSE, $translations = []) {
        $this->customStuff = \Drupal::service('mymodule.mymodule_repository');
  }

```

(The service is defined in .services.yml in the correct module)

But I have the error :

The website encountered an unexpected error. Please try again later.Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager-\>getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php). Drupal\Core\Entity\EntityManager-\>getDefinition(NULL) (Line: 410)

How to inject custom dependence in custom entity ?

# Answer
> 1 votes
I forgot the take in account the inheritance of the parent \__construct().

Here is the solution :

```
  public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
    parent::__construct($values, $entity_type, $bundle, $translations);
    $this->customStuff = \Drupal::service('mymodule.mymodule_repository');
  }

```

# Answer
> 2 votes
> How to inject custom dependence in custom entity?

You cannot; per the Services and dependency injection documentation:

> **Note**: It's not possible to inject services to entity object. See this issue for more details.

You'll have to get the service from `\Drupal` directly.

# Answer
> 0 votes
Have you added the Entity annotations? E.g:

```
/**
 * Defines MyEntity entity.
 *
 * @ingroup my_entity
 *
 * @ContentEntityType(
 *   id = "my_entity",
 *   label = @Translation("My Entity"),
...
class MyEntity extends ContentEntityBase implements MyModuleInterface {
...

```

https://www.drupal.org/docs/8/api/entity-api/structure-of-an-entity-annotation

---
Tags: 8, entities
---


title: translate product type title

text:
# Question
Title: translate product type title
```
     I am working on a drupal commerce site which needs to be multilingual.

```

The problem I am facing is that I cant translate the title field of product types. For example if I create a new product type called "Fruits" I want to be able to translate that title to other languages enabled on my site. I did replace the default title with a title field using the Title module but I still cant find my "Fruits" string to translate. Thanks

# Answer
@redamakarem You should use "entity translation" module for translate, After installing this module you have to find "Multilingual support" option in your product type called fruits.

Then you have to select "Enabled via Entity translation" option under multilingual support.then u have to translate your title field.Hope this works.
> 0 votes

# Answer
You should use node to display the product since commerce doesnot provide a product display page.

Then by replacing the title for that content type allows you to translate the product title.

To create product node page while creating the product in commerce form you can make use of inline node form provided by using Inline entity form module
> 0 votes

---
Tags: commerce, i18n-l10n
---


# Question
Title: Allow .svg logo uploading in theme settings
How can I allow using .svg files for the logo field, in the theme settings?

# Answer
The logo field in the theme settings says it accepts `.svg` format but it actually does not. As per the error message that comes up only `png jpeg jpg jpe gif` extensions are allowed at the moment. Its a bug that is being worked on Unnecessary restrictions on logo format: Can't upload replacement SVG logo. Try any of the patches mentioned in the issue and report there if your issue is resolved.

Alternatively, for your theme (or custom theme) you can just put the logo.svg in the theme folder and modify the page.html.twig template file to use the .svg extension.
> 1 votes

---
Tags: 8
---


# Question
Title: Is there a simple way to notify users about new posts on the site?
I want my users to be able to "subscribe" to new content that is posted on my site.

I've looked at the Notifications and Subscriptions modules and they are just massive! I've also looked at Simplenews (which which has a *very* attractive name), but it seems targeted towards distribution of a custom newsletter and not sending out general notifications about new content posted on the site.

Is there simple a way to set up a *rule* (by means of the Rules module) to accomplish this?

# Answer
> 1 votes
You can also use the core Trigger/Actions couple for such an easy job. Here is what you do:

1. Through `/admin/config/system/actions`, create the action, namely "Send e-mail..." and click *Create*.
2. Fill in information such as e-mail address and message.
3. Enable the **Trigger** module.
4. Through `/admin/structure/trigger`, choose your action.

You are now good to go!

# Answer
> 4 votes
You may consider the Notify module, which is a lightweight framework for sending out periodic notifications about new site content to users and admins.

From the project page:

> The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.

# Answer
> 3 votes
You can do it using Rules.

1. Create a field (probably a checkbox) in user account settings to subscribe for notification.
2. Then create a rule condition using `hook_rules_condition_info()` to check whether he has subscribed or not.
3. Create a rule to send a email notification when a new node is saved and add your custom condition to it.

# Answer
> 0 votes
Depending on your needs, this can be done with Views. Create a View either as a block or as a page of the appropriate content type, sort, filter and change as desired. Once as a block for example, you can put it any number of pages to show the most recent content.

# Answer
> 0 votes
Have a look at the tutorial "How to use Rules to notify users about new or updated posts on a Drupal site?", which explains how to use the Message module for this, together with the Rules module. What follows is a summary of what's included in this tutorial.

> You could also use the Message module for this. So that you have the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).
>
> Here is a blueprint of what you'd need:
>
> 1. Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to nodes.
> 2. Create a rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in '*Which user related token(s) can be used to create a Rule for setting up a message type?*' for some examples.
> 3. Make sure to also add a Rules Action to pass any relevant tokens, via the Rules module, as *Replacement tokens* that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
> 4. Use Views to display the created messages in the format you prefer.

# Answer
> 0 votes
I am the maintainer of flag\_notify() (for Drupal 7). Using the great UI of flags() it can concentrate on the logic of the notifications that would be too long or impossible to implement with rules.

It has some nice feature as (1) you can set up default notification for new users sitewise, and then each user can set their own default when they post a content or comment, (2) it has integration with Organic Group (if present), (3) it considers notification from sub-comments (when comments are organised hierarchically) and (4) it has hooks() that allow to personalise the notification message or the logic of the notification (e.g. if you want to exclude something too frequent).

---
Tags: 7, rules, notifications
---


# Question
Title: How to link to a taxonomy term of a view?
I would like to add a link in my template to the view page "taxonomy term", for a term of taxonomy to partiluer.

For example, in my taxonomy "thing" I have the term "truc", and I would like the link redirect to the page of the term taxonomy "truc".

I tried `<a href="{{ path('view.taxonomy_term.page_1') }}">{{ 'Name'|t }}</a>` but of course it does not work because I do not know where to put the term in question (in example the term "truc").

Do you know how to do it ?

# Answer
Try this one

```
<a href="{{ path('entity.taxonomy_term.canonical', {'taxonomy_term' => term_id}) }}">{{ 'Name'|t }}</a>

```

Where term\_id is your taxonomy term id.
> 0 votes

---
Tags: views, 8, theming
---


# Question
Title: Firing ajax_callback on textfield after a minimum number of character
Ive created a textfield with an ajax callback with 'keyup' event.

In need the callback function to be fired only after a certain number of character ... I can control the number of character of the input in the callback function, but this is not the way I want it...

There's maybe a javascript way to avoid the callback to be fired before 5 character ?

My form field :

```
        $form['myitem'] = array(
          '#type' => 'textfield',
          '#size' => 6,
          '#maxlength' => 5,
          '#default_value' => '',
          '#name' => "my_name",
          '#disabled' => FALSE ,
            '#ajax' => array(
                'callback' => 'mymodule_mycallback_ajax_callback',
                'wrapper' => "mywrapper",
                'method' => 'replace',
                'event' => 'keyup',
                'progress' => array('message' => NULL),
            ),
        );

```

# Answer
> 3 votes
One option is to use a custom jQuery event, eg. something like "startajaxCall". Set $form\['my\_input'\]\['#ajax'\]\['event'\] = 'startajaxCall' and provide some JS to trigger your custom event after an appropriate number of keys is entered.

# Answer
> 1 votes
I also faced same challenge in one my project. Fixed it by below logic.

> // Update the event to change instead of keyup.

```
 'event' => 'change',

```

> // Add below js line.

```
  // Trigger ajax event on myitem only after 5th character typed.
  $('.myitem-class').on('keyup', function() {
    if ($(this).val().length == 5) {
      $(this).trigger('change');
    }
  });

```

---
Tags: forms, javascript
---


# Question
Title: Add an extra class to views exposed filter “select” if default option is selected
I have some views exposed filters and need to add an extra class "test" to each list if it has default option selected. I try to implement it using jquery with the following code:

```
function ($) {
$(document).ready(function () {
    $('.form-select option:eq(0)').prop('selected', true);
      $(".form-select").addClass("test").on('change', function() {
      var optionIndex = $(this).find('option:selected').index();
      $(this).toggleClass('test', optionIndex === 0);
   });
});
})(jQuery);

```

Question is how to make this code to act properly in Drupal 7? Currently it adds the "test" class to all the dropdown lists after the page load. But if you chose any not default value in any list the "test" classes of all lists (even where default option is selected) disappeared and never appeared again until the page reload.

# Answer
> 0 votes
Well, proper solution of my task is represented below:

```
(function ($) {
$(document).ajaxStop(function() {
    $("select").each(function() {
          var optionValue = $(this).find('option:selected').val();
          $(this).toggleClass('made_choice', optionValue !== 'All');
    });
  });
})(jQuery);

```

Once again I've proved to myself: if you want to do something in the best way - do it by your own. So, the first problem was script starting by .ready(function()). It is wrong in case of exposed filters and AJAX loading procedure. You should start it by .ajaxStop(function()) to be able to fire the script every time you have chosen new value of exposed filter. The second problem is that in case of two and more exposed filters on the form indexes of their options starting from 0 in the first used filter and finishing with the index of last option in last filter widget. Thus, you can not say that (optionIndex === 0) for every default value in each filter widget. So it will be more proper way in such case to check whether the option:selected has value 'All' or not.

# Answer
> 0 votes
Change the selector and class name to your needs, but this should work.

```
(function ($) {

  $("select")
    .change(function() {
      if ($(this).val() === $(this).find('option[selected]').val()) {
        $(this).addClass('default-value-selected');
      }
      else {
        $(this).removeClass('default-value-selected');
      }
    })
    .trigger("change");

})(jQuery);

```

---
Tags: javascript, views
---


# Question
Title: Display both sort icons on sortable table columns
I'm using Drupal's theme table function to build a custom table.

All of the columns on my table are sortable. I would like to visually indicate that they are sortable by putting both an ascending and descending sort icon in the column header.

To indicate which sort is active, I would like to show only one icon, corresponding to the current sort (ascending or descending).

Here's what I have:

Here's what I want:

How can I accomplish this?

So far, the closest I've gotten is overriding `theme_tablesort_indicator()`, but this will only let me override the icon for the active sort. (Docs here)

# Answer
> 0 votes
I used some jQuery and CSS to accomplish this:

``

# Answer
> 0 votes
I figured out a hacky way to do what I want...

```
function mytheme_preprocess_table(&$variables) {
  foreach ($variables['header'] as $key => $header) {
    if (!isset($header['sort'])) {
      $header['data'] .= theme('image', array('path' => 'misc/arrow-desc.png', 'width' => 13, 'height' => 13, 'alt' => t('sort descending'), 'title' => t('sort descending')));
      $header['data'] .= theme('image', array('path' => 'misc/arrow-asc.png', 'width' => 13, 'height' => 13, 'alt' => t('sort ascending'), 'title' => t('sort ascending')));
    }
    $variables['header'][$key] = $header;
  }
}

```

The downside to this solution is that it will apply to unsortable columns as well as sortable columns.

Also, this solution affects the link title that is generated for the column header. It will contain the markup for the arrows as well as "sort by $data".

Clearly this isn't a good solution, but it's the best I've got at the moment.

---
Tags: 7, theming
---


title: Lazy load with inline images

text:
# Question
Title: Lazy load with inline images
It looks like all popular lazyload modules only work with Images. I would like to get lazyload to work on my inline images (images inserted with Media/FCKEditor).

Do any modules support this? Or is there another way?

# Answer
> 0 votes
*I realize this is an old question, but I think this may help others with the same issue.*

I recently contributed a module to Drupal community for lazy-loading inline images (and iframes). Once the module is installed, the filter needs to be enabled in desired text-formats.

It requires no changes to the existing content.

**Lazy-load**
https://www.drupal.org/project/lazy

---
Tags: media
---


# Question
Title: How to set alias pattern of node's source alias?
When I translate a node I want that node's path alias to be like it's source node's path alias.

So in the url pattern for the translation nodes I use the token:

> \[node:source:url:path\]

which according to this thread should be fine. But, it actually generates the alias "/node-402-0", although the source node has a path like "/welcome".

I have the feeling that in the token module the wrong language is being looked into.

Am I missing something?

# Answer
> 0 votes
I *think* you can set the alias to not be translated in the the content language settings (Admin-\>Config-\>Regional-\>content language.

Under each content type there should be a url alias option. Unchecking this should make the alias the same for all languages.

---
Tags: 8, path-aliases, tokens
---


title: How do I find available public methods?

text:
# Question
Title: How do I find available public methods?
I'm finding that the biggest problem in working with Drupal 8 is I can't get the data I need. Drupal 8 wants me to use public methods rather than manually drilling down thru an object. The problem is, I can't figure out a consistent way for getting a list of available methods! (they magically exist, and I feel like I'm just supposed to know about them).=

For this example, let's say I have a content type with a video field. I need to get the raw URL of the video file in that field.

So I'd start with a node id ($nid), and somehow I have to figure out how to load the node. This isn't too bad because there's lots of examples. So I do something like `$node = \Drupal\node\Entity\Node::load($nid);`.

So far so good. Then I need to get the value of my video field (field\_main\_video). This took me FOREVER to figure out because there's conflicting documentation around the 'net. Finally I figured out I'd have to do something like this (because it is a multivalue item):

```
$video = \Drupal\node\Entity\Node::load($nid)->field_main_video->getValue();

```

...then loop thru the array etc. Using kint didn't help me find this, either. Because, for example, if I `kint($node)` and look under methods, I don't see getValue() as an item there. Still not terrible, because there were enough examples around to figure it out.

As I go deeper, though, what I didn't know (this is the important part) was that rather than getting the video field entity id, then loading the entity, then finding the "uri" field in the entity, etc (like I would in D7): There was a method that lets me get the URI all in this same line of code!

```
$url = \Drupal\node\Entity\Node::load($nid)->field_main_video->entity->getFileUri();

```

**But how could I possibly have known this getFileUri() existed?** I happened to stumble upon it in a blog post. This truly DOES make getting a URI easier than in D7...but only if you know (magically) what methods exist for each 'level' of an object.

In the end, with this example I'm asking: **How do you find all public methods for each level of an object in a way that's easy to read and understand?** Note that it seems there should be a drupal-centric (ie. devel module) way of doing this rather than manually searching api.drupal.org or using something IDE specific?

# Answer
> 15 votes
Content entities are different from most other things in that they often do *not* have methods and proper interfaces, at least not for configurable fields.

In case of content entities and fields, public methods is not really what you actually want to know, what you want is to know about fields and properties. And only when you get to an entity again through a reference then the methods matter.

For an overview, I always refer to the great Entity API Cheat Sheet.

Content entities have a fixed structure, Entity \> Field (FieldItemList) \> FieldItem -\> Property. A property is either scalar or a reference to something else, e.g. another entity, a language object, a date object, ...

For a few specified examples, some useful snippets:

```
// List of fields that an entity has, the field definitions also have a lot of information like the type.
array_keys($entity->getFieldDefinitions())

// Use get() instead of the magic __get() on the entity level then you at least get some type hints.
$entity->get('field_name').

// Get the list of properties a certain field has, use array_keys() again for just the names, but the definitions also have the type and if it's computed or not.
$entity->getFieldDefinition('field_name')->getFieldStorageDefinition()->getPropertyDefinitions()

// Most field types have value property, but e.g. entity references have target_id and the computed entity. as you found. File and Image fields have additional properties like title/alt/description.
$entity->get('field_name')->value
$entity->get('field_name')->target_id
$entity->get('field_name')->entity

// Note that get('value') is not the same as ->value on the field item level, get() returns a typed data object, get('value')->getValue() is the same as ->value.

// When not specified, the delta 0 is assumed (all fields are a list internally, even something like the node id), you can use array access or the delta to access another delta, make sure it exists.
$entity->get('field_name')[1]->value
$entity->get('field_name')->get(1)->value

// When you have an entity reference, you can get the entity type and class like this:
$entity->get('field_name')->entity->getEntityTypeId()
$entity->get('field_name')->entity->getEntityType()->getClass()
// or
get_class($entity->get('field_name')->entity)

// From there you can look up the interface and type hint against that, to a) make sure you have a valid, loadable reference and get type hints in an IDE:
$file = $entity->get('field_name')->entity;
if ($file instanceof \Drupal\file\FileInterface) {
  $file->getFileUri();
}

```

# Answer
> 7 votes
Well, I found myself using quite often the combination of `var_dump(get_class_methods($object))` to have a list of available methods for the given class.

I also look quite often into `api.drupal.org` for further details.

# Answer
> 5 votes
Not sure if that will completely answer your question but what helps me a lot is using the diagrams feature in PhpStorm.

For example showing the hierarchy

You have options to show also method names

I hope this helps you in a way.

# Answer
> 1 votes
You can use the PHP get\_class\_methods function. The example below users a file upload:

```
$image = $form_state->getValue('image_field_name_from_form');
$file = File::load( $image[0] );
$file->setPermanent();
$file->save();

$methods = [];
foreach (get_class_methods($file) as $method) {
        $methods[] = $method;
}
print_r($methods);

```

This will add all methods available to the object $file into your $methods array, which you can print and then see all methods available. This is valid for any objects in PHP, not just Drupal.

# Answer
> 0 votes
You're already very close.

First, let's look at the definition of the method: https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/function/File%3A%3AgetFileUri/8.2.x

From here, we can see the class this is part of, and there is a link to it:

```
Class

File
Defines the file entity class.

```

Clicking through takes us to: https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/class/File/8.2.x

In your IDE, you could also search for the `\Drupal\file\Entity\File` class. One way to be sure this is the correct class is to look at the annotation:

```
@ContentEntityType(
  id = "file",
  label = @Translation("File"),
  handlers = {
    "storage" = "Drupal\file\FileStorage",
    "storage_schema" = "Drupal\file\FileStorageSchema",
    "access" = "Drupal\file\FileAccessControlHandler",
    "views_data" = "Drupal\file\FileViewsData",
  },
  base_table = "file_managed",
  entity_keys = {
    "id" = "fid",
    "label" = "filename",
    "langcode" = "langcode",
    "uuid" = "uuid"
  }
)

```

Notice the `id` — it is `file`. Presumably, if debugging, you could look at the contents of `field_main_video->entity` and you would see this ID somewhere. Then you just search for it in your IDE. Usually, though, one knows enough about the entity types one is using to guess one's way to the right class (after which one could verify that the annotation contains the correct ID).

In this particular case, I also know that `File` is *probably* a class that extends `ContentEntityBase`, since it's more like database content (a content entity) than configuration (a configuration entity). So when I see my assumptions confirms, that helps me know I have found the right class.

So, in short: your IDE, strategic `debug()` statements, and some guesswork are the best ways to discover Drupal 8.

P.S. Change records can also be helpful. They are at https://www.drupal.org/list-changes/drupal

---
Tags: 8, entities
---


# Question
Title: Existing orders with deleted coupon throw EntityMetadataWrapperException
My users have been placing orders on my website with a coupon code that now no longer exists. Any orders that previously used the coupon/discount 'freeshipping' are now throwing me the following error when I try to edit them (change their status):

> EntityMetadataWrapperException: Missing data values. in EntityMetadataWrapper-\>value() (line 83 of /sites/all/modules/entity/includes/entity.wrapper.inc)

Is there any way to fix this? I need to be able to edit those orders and change their status from pending to processing. I had a look at this discussion, but it doesn't seem like a solid solution was found.

# Answer
If time is a factor you could just create a new coupon that matches the machine name of the old one.

Then when you are ready to fix them, first edit the orders to remove the coupons from them.once all are removed, then delete the coupon.
> 1 votes

---
Tags: 7
---


# Question
Title: Ubuntu crontab is not triggering when site is in maintenance mode and also revert to online
I am using the *Ultimate cron* module and I have set the main Drupal cron task in crontab to run every 5 minutes.

I have put my site in maintenance mode. Drupal cron tasks are not running when site is in maintenance mode, and it is not resuming its operation when I changed the site back to online.

Please suggest.

# Answer
> 0 votes
When the site is in maintenance mode it makes sense that regular cron tasks are halted. For example email notifications about new content should not be sent if you are working with content in maintenance mode - unless you want users to go to a site down page.

If you manually trigger the cron to run after disabling maintenance mode it should restart the jobs.

---
Tags: cron
---


# Question
Title: Mainteance Mode Causes CSS to be removed
I am getting my site ready for an update, but whenever I put my site in maintenance mode, all it does is remove all the CSS and images from the site and just shows the content.

Does anybody know what is happening?

# Answer
> 0 votes
Create a maintenance template file and place it in your theme folder. It's probably using a parent theme maintenance template or just the regular core one.

---
Tags: 7, theming
---


title: Fancy insert stopped working

text:
# Question
Title: Fancy insert stopped working
Does anyone have an issue with the fancy insert module, not actually inserting the image on click recently?

It looks like the javascript in the fancy insert was hooking into the insert button by traversing up from each image thumbnail.

```
// Click on Insert button when an image is clicked
      $('#' + value + ' img').bind('click', function (e) {
        $(this).parent().next().find(".insert-button").trigger("click");
      });

```

I can't see any obvious reason why this would have stopped functioning with updates.

So my question is, has anyone else run into this issue with the latest Drupal core updates? At first I thought it was a lack of unique id on each imagefield, but after reviewing the code again I don't think that is the case.

At any rate am looking for anyone who may have run into this and found a fix.

# Answer
> 0 votes
The issue is caused by the `insert` module. The latest version (1.4) switched from using `click` to `mousedown` events, in this issue https://www.drupal.org/node/2295507

The patch submitted here (https://www.drupal.org/project/fancy\_insert/issues/2955599#comment-12571625) should solve your issue, it basically switches from triggering `click` to triggering `mousedown` events as a way to connect to the `insert` module's functionality.

Here is the code change for reference:

```
diff --git a/fancy_insert.js b/fancy_insert.js
index 8325c96..0b99824 100644
--- a/fancy_insert.js
+++ b/fancy_insert.js
@@ -21,7 +21,7 @@ Drupal.behaviors.fancy_insert = {
-            $(this).parent().next().find(".insert-button").trigger("click");
+            $(this).parent().next().find(".insert-button").trigger("mousedown");

```

Good luck!

---
Tags: 7, forms, javascript, media
---


title: How to debug page caching?

text:
# Question
Title: How to debug page caching?
I've got a page which returns `X-Drupal-Dynamic-Cache: UNCACHEABLE`, I've got a suspicion that this is related to a view that is embedded in the page. Though, this made me wonder; is there any way to see what invalidated actually the page cache?

# Answer
> 4 votes
As suggested in the answer from CG Monroe, enabling the header will show you what contexts you have, a user or session cache context can for example disable caching as well as a max-age 0.

Tracking down exactly where they are coming from can be tricky, I usually debug on the merge methods of the Cache class with a breakpoint set on having the problematic context/age. Certain filters/sorts or so (e.g. a random sort) can cause this, but so can certain block conditions (there is actually a known issue with that, see https://www.drupal.org/project/drupal/issues/2521956).

# Answer
> 7 votes
The X-Drupal-Cache-Tags header should help with this. Here's how to enable it from this doc:

> You can debug cacheable responses (responses that implement this interface, which may be cached by Page Cache or Dynamic Page Cache) by setting the http.response.debug\_cacheability\_headers container parameter to true, in your services.yml. Followed by a container rebuild, which is necessary when changing a container parameter.
>
> That will cause Drupal to send X-Drupal-Cache-Tags and X-Drupal-Cache-Contexts headers.

---
Tags: 8, caching
---


# Question
Title: Running PHPUnit test from CLI and debug in PhpStorm: Remote file path '/directory/path/-' is not mapped to any file in project
I'm trying to execute a PHPUnit test via the CLI to debug in via PhpStorm, being on a Ubuntu 16.04 operating system. It's a KernelTestBase unit test for Drupal 8. The normal execution of the test - without PhpStorm and Xdebug - works. The problem appears, when I have XDebug switched on. I'm executing it that way from the terminal:

> peter@computer ~/Websites/pbt-d8 $ vendor/bin/phpunit -c modules/permissions\_by\_term modules/permissions\_by\_term/tests/src/Kernel/SelectTermTest.php

If XDebug is switched on, PhpStorm shows me a weird "Remote file path error":

> Remote file path '/home/peter/Websites/pbt-d8/-' is not mapped to any file path in project

I have also attached a screenshot of the debug window:

What confuses me here, is the "-" character at the end of the path. I have not specified this character anywhere.

I have no idea what I should define here as a path mapping within PhpStorm:

My phpunit.xml file (which is located at modules/permissions\_by\_term/phpunit.xml) looks like follows:

```
<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">
  <php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="mysql://root:password@localhost/pbt-d8"/>
    <env name="SIMPLETEST_BASE_URL" value="http://pbt-d8"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/home/peter/d8-tests"/>
    <env name="PHP_IDE_CONFIG" value="serverName=pbt-d8"/>
    <env name="XDEBUG_CONFIG" value="remote_enable=1 remote_mode=req remote_port=9000 remote_host=127.0.0.1 remote_connect_back=0"/>
  </php>
</phpunit>

```

Do you know what's wrong here? Do I need any specific XDebug configuration to fix this issue here?

# Answer
You can disable "Force break at first line when no path mapping specified" in "Debug" settings and this error goes away. While execution is paused, you can see that the break is happening in a secondary callback that is called with `-` as an argument (See `$_SERVER['argv'][0]`).

This doesn't happen with purely unit tests because there isn't a secondary callback but `BrowserTestBase`. `KernelTestBase` must be working simillarly to `BrowserTestBase`.
> 1 votes

# Answer
There was a bug within my code. I have forced the debugger to stop via xdebug\_break(); and found out that the issue was at the first line of my code.
> 0 votes

---
Tags: testing
---


# Question
Title: Any way to override view_mode in twig directly?
For some reasons, I need to render a content twice, the first one in default view mode, the second one with thumbnail view mode.

In field--paragraph--field-slide--gallery.html.twig I tried to use the following code, however, got a fatal error.

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

{% for item in items %}
  {% set item.content['#view_mode'] = 'thumbnail' %}
  {{ item.content }}
{% endfor %}

```

Any another idea to get the similar output?

# Answer
> 1 votes
The fatal error is because Twig `set` is not able to manipulate arrays. This is only possible by using `merge` and then only on the top level of the array.

So first get the sub array where the key is placed and then merge the array key:

```
{% set item_content = item.content %}
{% set item_content = item_content|merge({'#view_mode': 'thumbnail'}) %}
{{ item_content }}

```

But I doubt that after you've solved the Twig issue this will work, because of how entities are rendered and cached. So you might have more success with Twig Tweak.

---
Tags: theming
---


title: Add webform answers

text:
# Question
Title: Add webform answers
I have a likert on a webform with the options *strongly agree*, *disagree*, *neutral*, *agree*, and *disagree*. I want to assign each option a weight, then multiply the number of users responses in each particular category. I haven't found any module currently available for Drupal 8 that does this.

How can I hard code this into the webform submission, and what language would I have to use? I am completely new in Drupal with a background in Python.

# Answer
> 0 votes
You might have to create a custom element and/or alter the submission using a custom PHP module.

I recommend checking out Webform Analysis module

---
Tags: 8, webforms
---


title: Inline Validation Messages with Webform

text:
# Question
Title: Inline Validation Messages with Webform
Sorry if this has been asked before (although I've been looking and haven't found quite what I'm looking for).

It's not currently possible to present the server-side validated messages (specifically required fields) inline on forms built with webform, is it? If not, is is something that I could realistically code myself? Looking at this ticket:

https://www.drupal.org/project/webform/issues/2889272

The line: "Form validation messages will not be moved because contrib modules and theme expect this information to be displayed in specific region." Makes me wonder if it would even be possible.

Be nice, this is my first question on here.

Thanks.

# Answer
> 0 votes
Drupal core includes the Inline Form Errors module which will move required validation messages below each element. Issue #2889272 was specifically about where the main message container, with the "X errors have been found" text, should be placed on a page.

I also recommend checking out the Clientside Validation module. Here is a short video showing how to improve webform client-side validation.

---
Tags: forms, webforms
---


# Question
Title: How am I supposed to upgrade a site to latest core version?
I tried to update a Drupal 7 site to the latest version. The old Drush update doesn't work and it throws an error about a unknown engine type output format.

I tried to delete the web folder, extract Drupal 8 files, change the database connection settings to use the old database, and call update.php. It doesn't work, and it throws errors about MySQL encoding.

I tried to install Drush 9 to upgrade core, but it keeps complaining about the composer.json file.

I tried to install Drush 8, but it shows more errors.

How am I supposed to update an old Drupal installation to latest core version?

# Answer
> 1 votes
From Drupal documentation :

> Strictly speaking, 'updating' refers to taking your site from one 'minor' version to another, as for example, from Drupal 7 version d7.1, to d7.2; or from Drupal 8 version d8.0.0 to d8.1.3, etc.

Which means upgrade can be done only to minor version.

If you want to change the whole version for example moving from Drupal 7 to Drupal 8 you need to migrate your site, and this normally involved a data migration and restructuring, Also changing and reviewing your custom modules code.

See Upgrading from Drupal 6 or 7 to Drupal 8

---
Tags: 8, upgrading
---


title: Get current country pathPrefix

text:
# Question
Title: Get current country pathPrefix
How can I get current country pathPrefix in D8 ?

I know `drupalSettings.path.pathPrefix` gives that in JS, but how can I get it in preprocess hook ?

Following gives only the path alias, but without pathPrefix.

```
\Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid[0]);

```

# Answer
You can call PathProcessorManager::processOutbound() for the internal path and you get the path alias and the prefix at the same time:

```
$options = ['prefix' => ''];
$path = \Drupal::service('path_processor_manager')->processOutbound('/node/1', $options);
$prefix = $options['prefix'];

```
> 0 votes

---
Tags: 8, path-aliases
---


title: Drupal Gardens like website

text:
# Question
Title: Drupal Gardens like website
I actually would like to start a website in which users can register and each registered user will get a subdomain. Each subdomain will be a drupal installation. I can share the files between installations and keep different databases for each of them (or table prefixes). I checked Drupal multisite, but it is mostly for the administrator who is maintaining the website. I need this functionality for the users as it is there in drupal gardens. I also checked Aegir and seems like its also for admin only. Basically I need the kind of functionality that Wordpress multiste plugin has have. Anyone know any drupal module which will allow the creation of multiple sudomain based websites on the fly ?

BTW, I am new to Drupal so my assumptions may not correct. It will be helpful if someone can guide me in right direction.

# Answer
> 2 votes
You can use Domain access module.

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:
>
> > * example.com
> > * one.example.com
> > * two.example.com
> > * my.example.com

# Answer
> 0 votes
Domain Access module allows you to run multiple sites from a shared database... but if you just want multiple sites with their own database you don't need any modules. You just need a wildcard in your dns settings... so if your domain is happycoder.com create an A record of \*.happycoder.com and then you can create anything.happycoder.com.

# Answer
> 0 votes
While Aegir might be a tool for admins, it has a signup feature to let normal people create sites. These can then take full advantage of Drupal's multi-site capabilities. Having a better isolation in a separate database per site.

---
Tags: 7, multi-sites, aegir
---


# Question
Title: How to embed existing website in my Drupal 8 site?
I have a site I created with Drupal 8, lets say http://falzon.xyz/.
Elsewhere, I have a site created with Jekyll, a bunch of static pages linked to each other visible http://www.elina-noe.eu/).
I'd like to "embed" the static site as a "subsite" of falzon.xyz, i.e. accessible as http://falzon.xyz/elina-noe/, by 'simply' putting all its files in a subfolder of the D8 site.
How can I do that?

# Answer
> 3 votes
Creating a subfolder inside your `docroot` folder such as `docroot/elina-noe` should suffice.

Put all the subsite files into this folder and if there is a `index.html` you can access your subsite just by visiting the subfolder `http://falzon.xyz/elina-noe/`

---
Tags: 8, subsites
---


# Question
Title: How to replace the button when the user is not authenticated?
I copied the twig file of my nodes into my theme.

On my nodes there is a flag displayed, but only authenticated users can see it.

Here is my code :

```
<div class="bs-field-like-link">
  {{ content.flag_like_group }}
</div>

```

How to replace the flag for unauthenticated users by :

```
<div class="bs-field-like-link">
  <a class="btn btn-success" href="/user/login"><i class="far fa-heart fa-1x"></i> J'aime</a>
</div>

```

# Answer
> 1 votes
You can use predefined `logged_in` variable.

```
{% if logged_in %}
  <div class="bs-field-like-link">
    {{ content.flag_like_group }}
  </div>
{% else %}
  <div class="bs-field-like-link">
    <a class="btn btn-success" href="/user/login"><i class="far fa-heart fa-1x"></i> J'aime</a>
  </div>
{% endif %}

```

---
Tags: 8, theming
---


# Question
Title: Externally Requesting Browser Test Created URL for Relaxed Replication
I am trying to write a browser test for for a workspace replication via relaxed web services using the multiversion, replication and relaxed modules. For this purpose I set up an external Drupal installation as a content repository to clone from.

The content repository is installed locally and is reachable as I have tested it with an other Drupal instance as a replication target.

My problem is that the Drupal instance created by the browser test always gives me a 404 error once I try to reach it like follows:

```
\Doctrine\CouchDB\CouchDBClient::create([
      'url' => 'http://replication_user:password@browsertest.url/relaxed/live',
      'port' => 80,
 ])->getDatabaseInfo('live');

```

The local url and WorkspacePointers are set up correctly and the rest resources are also active. I even have a custom Drupal profile which activates all needed services and writes all configs for this functionality to work and it is being used by dozens of sites, but using relaxed replication in a test (even with the working profile) seems impossible…

# Answer
I found the answer. To target the current test instance in a request one needs to set the http client user agent header to `drupal_generate_test_ua(drupal_valid_test_ua())`.
> 0 votes

---
Tags: 8, routes, testing
---


# Question
Title: How to get custom role ID from Drupal UI?
Really simple, where I can I look up the custom roles and their role id's?

# Answer
> 1 votes
On the `People > Roles` (`admin/people/roles`) page you can hover over the Edit links or click on them to see what the machine-readable name is, that is the role ID.

For example in Drupal 8 you get three Roles built in with these Role IDs: `anonymous`, `authenticated`, `administrator`.

In Drupal 7 you can do the same to look them up, only the path and the wording are a little bit different (`People > Permissions > Roles`, `admin/people/permissions/roles`).

In Drupal 8 Role IDs are now machine-readable strings while in Drupal 7 and below they were integers (numbers).

### D8

```
$user->roles = array(
  'authenticated' => 'Authenticated user',
  'administrator' => 'Administrator',
  'site_editor' => 'Site editor',
);

```

### D7

```
$user->roles = array(
  2 => 'authenticated user',
  3 => 'administrator',
  4 => 'site editor',
);

```

# Answer
> 1 votes
Not what I was looking for, but if you inspect the Roles Drop Drop on the People Page then the array has the ID in it.

---
Tags: users
---


# Question
Title: Taxonomy term not displayed in the current language
My setup is simple:

A content type "film" with a taxonomy field "Type of film".

The content type "film" is translatable, but not the field "type of film" (same type for all languages): only the entity type "Type of film" is translatable.

If I display a film with an English interface, I will get "Comedy" as the type of the film and in French, I will get "Comedie".

If I create a view showing the films teasers, I will have Comedy/Comedie depending if I ask to display French or English films.

Until this point, everything runs fine...

But, as all the films are **not** translated, I would like to have Comedie if it is a French interface (http://domain/fr) even if the teaser is displaying an English (not translated) film.

In the view, I have used

**FILTER CRITERIA**: Content: Default translation (= True)

**LANGUAGE**: Rendering Language:Interface text language selected for page

In the Manage display of the film's teaser, I choose "label" to display my taxonomy field... without any option to display it into the current language (now it is displayed into the content type language)

**EDIT TO ADD**:

Following the advise from @Berdir, I have created a new formatter: `/my_module/src/Plugin/Field/FieldFormatter/CurrentLanguageLabelFormatter.php`

```
<?php

namespace Drupal\artprod\Plugin\Field\FieldFormatter;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\TranslatableInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter;

/**
 * Plugin implementation of the 'current language label' formatter.
 *
 * @FieldFormatter(
 *   id = "current_language_label",
 *   label = @Translation("Current Language Label"),
 *   description = @Translation("Display the label of the referenced entities using the language of the page."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class CurrentLanguageLabelFormatter extends EntityReferenceLabelFormatter {

    protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items,$langcode) {
        $entities = [];

        foreach ($items as $delta => $item) {
            // Ignore items where no entity could be loaded in prepareView().
            if (!empty($item->_loaded)) {
                $entity = $item->entity;

                // Set the entity in the current language for display.
                // HERE IS THE CHANGE
                if ($entity instanceof TranslatableInterface) {
                    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
                    $entity = \Drupal::entityManager()->getTranslationFromContext($entity, $language);
                }

                 $access = $this->checkAccess($entity);
                // Add the access result's cacheability, ::view() needs it.
                $item->_accessCacheability = CacheableMetadata::createFromObject($access);
                if ($access->isAllowed()) {
                    // Add the referring item, in case the formatter needs it.
                    $entity->_referringItem = $items[$delta];
                    $entities[$delta] = $entity;
                }
            }
        }

        return $entities;
    }
}

```

In the annotation, I have changed the `id` and the `description`

In the class body, I have copied the `function getEntitiesToView` from the class `EntityReferenceFormatterBase` except that I changed the chunk of code which is translating the entity.

After restarting Apache and clearing the cache, I could select this overrided formatter for my taxonomy field.... AND the label are now displayed in the current language (vs language of the parent entity)

# Answer
> 1 votes
The language of the parent entity is passed to entity formatters and they respect that when displaying referenced entities.

If you want to override that, you can for example provide your own entity formatter plugin that overriddes \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView() and ignores the passed in $langcode. There is no configuration for that.

Since you probably want the entity label to be displayed, you should subclass `\Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter`.

Alternatively, you can also do something in preprocess/twig.

---
Tags: 8, taxonomy-terms, i18n-l10n
---


# Question
Title: Feeds import should delete non-existent nodes and not insert new nodes
Use case: Drupal 7 Importing nodes from an XML source. Every Wednesday 18 PM: run import and add new nodes. Every hour: run import and delete non-existent nodes AND do NOT add new nodes.

I'd appreciate some help since after a lot of testing and searching I'm still not getting this to work properly.

I'm using two importers: one to import (no problems) but I can't get the second one to delete any nodes.

EDIT: Sometimes trying to formulate the question for someone else, pops up new ideas! Could the problem be that you simply can not use two feeds for one content type?

# Answer
Short answer: importing nodes and deleting nodes no longer included in the feed needs to happen with the same importer.

Long answer:

When performing an import, Feeds indexes the imported items in the feeds\_item table. Each item in this table belongs to a specific importer and - in case the importer was attached to a content type - also to a specific feed node.

When the importer is configured to clean up items that are no longer in the feed, it loads all item ID's into memory for that specific importer (and feed node) at the start of the import. During the import, Feeds crosses of each item from the clean list that it has seen. At the end of the import, it cleans up the items that remained on the clean list.

When you use one importer to import a list of items, these items are then owned by that importer. When you then run a second importer for the same content type, it will own none of the items that were created/updated with the first importer at the start of the import. If the second importer doesn't own any of the items, there is nothing to delete after the import.

Note: ownership of items can be "transferred" from one importer to another. For example: items that were originally created by importer 1 and later updated by importer 2 are then owned by importer 2. If importer 1 updates them later, importer 1 owns them again. So using two importers to update the same content makes the "delete non-existent" feature unpredictable.
> 0 votes

---
Tags: feeds
---


title: Altering User Registration Message

text:
# Question
Title: Altering User Registration Message
I need to take control over and change the flash notification a user gets when they register, but administrator approval is required.

I want to alter this...
"Thank you for applying for an account. Your account is currently pending approval by the site administrator. In the meantime, a welcome message with further instructions has been sent to your email address"

https://api.drupal.org/api/drupal/core%21modules%21user%21src%21RegisterForm.php/function/RegisterForm%3A%3Asave/8.2.x

It states...
**'Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.'**

1. I'm trying to figure out what the Drupal 8 way of doing this is.
2. Should I be trying to "alter" the message with a hook?
3. Should I be overriding a service? (though from my understanding this is not service).
4. Should I be extending this?
5. Or is there some other best practice way of overriding this?

I'm learning Drupal 8. So I'm not entirely sure the "right" way to handle this particular case.

# Answer
> 1 votes
Brandon's answer is good for altering the email messages.

If you are looking to alter the status message that pops up afterwards, I found this answer helpful: https://stackoverflow.com/a/38797543/963866

# Answer
> 0 votes
Email notification settings (not status messages) are configuration. Visit yourdrupalsite.com/admin/config/people/accounts

This also lives in the configuration object user.mail. If you export your site configuration you can see its value in user.mail.yml.

Drush cli tool can get this configuration entity with the following command `drush cget user.mail`

---
Tags: 8
---


# Question
Title: Overriding system.site.uuid with an environment variable
I have a need to have separate sites behave as if they are clones of each other; that is, they each need to have the same site UUID.

Due to the environment I am operating in, I am unable to change the site UUID via `drush config:edit` once the site is installed as I have no SSH access to the environment. Likewise, the only way I can create a new site in this environment is to upload the files, create an empty database and then run the install script. This creates a new site, with a new UUID, and therefore is no longer a clone. Once sites are installed in the environment, my only way of interacting with them is through the administration UI.

Any site I create in this environment will have the same code base; it is not a matter of messing things up by importing the wrong config.

I can import the same database into the new site once it is installed using Backup and Migrate, thereby changing the UUID (I assume). However, this does not quite solve the problem because it may be the case that I need to create sites via scripts in our continuous integration system.

My initial solution is to add a line in `settings.php` to override the configuration item in question, ie:

`$config['system.site']['uuid'] = 'this is the site uuid';`

However, when I export the configuration, the override value is not respected and configuration is exported using the original value. I can test this by exporting the configuration from a clone and trying to import it. If the UUID was being overridden 'fully', then I would expect the configuration import to fail.

Ideally, I would like to set the site UUID through an environment variable or service, so any site with access to the variable or service would be able to use the same UUID, and therefore be considered clones.

Has anyone had any success with something similar?

# Answer
In the end, it was a matter of getting Drush to work on the remote environment.

I was also able to build a small module to update the site UUID of an existing site, however we didn't end up using it. The code for that is available at this repository.

Essentially, this boils down to running something like this:

```
\Drupal::configFactory()
    ->getEditable('system.site')
    ->set('uuid', $uuid)
    ->save(TRUE);

```

Where `$uuid` is whatever the UUID you want, whether this is generated manually or loaded from a service.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How to add some custom text after a taxonomy field in panels?
I have a taxonomy field called cvtype.

This cvtype is containing several names like \- Standard \- Complete

I can add this to a Panel by adding content \> node. I would like to add the letters CV behind each term in this panel.

How to do this in D7?

# Answer
You can achieve this by using `display suite` to add a prefix:

* Download & enable the module Display Suite (if not already installed) https://www.drupal.org/project/ds
* Go to `<my_url>/admin/structure/ds/settings`
* Enable export field templates
* Edit your cvtype taxonomy and click on the Manage Display tab
* Choose the one column layout (and save) -\> display the name field, click the gears icon & add the prefix
> 0 votes

---
Tags: 7, taxonomy-terms, panels
---


title: How to convert cUrl code to drupal way?

text:
# Question
Title: How to convert cUrl code to drupal way?
I have below code

```
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
curl_close($ch);

```

In Drupal 8 way we can use

```
$client = \Drupal::httpClient();

$response = $client->request('GET', $url, [
  // To add
]);

```

Not sure how to pass needed parameters/convert it to drupal way.

**\[UPDATE\]**

```
$uri = 'http://domain.com';

$client = \Drupal::httpClient();

$actual_uri = NULL;
$response = $client->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, \Psr\Http\Message\UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);

dump($response);
exit;

```

# Answer
The only special thing I see there is getting the effective URL, which is actually something that was specifically added back to Guzzle 6 for Drupal: https://github.com/guzzle/guzzle/issues/1166

See \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher::fetch:

```
  /** @var \Psr\Http\Message\UriInterface $actual_uri */
  $actual_uri = NULL;
  $response = $this->httpClientFactory->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);

```
> 4 votes

---
Tags: 8
---


# Question
Title: Drupal 8 status code set 301 instead of 302 for urls with out lang code
I have an article with url alias '/gettting-started' and it is translated in several languages.

Lang codes for other languages is set like the following.

For German:*de-de*, English: *en-us*.

In 'admin/config/regional/language/detection' Detection and selection languages, priority is set to 'URL' then 'Browser'.

My browser locale set to German first,so when i try to visit the article with the `/getting-started`, it is redirected to `/de-de/getting-started` with the status 301.

The status code 301 is creating the problem for me as the response is cached at varnish cache (for 301 response codes).

The other user, with English as priority in Browser language visits `/getting-started` redirects to `/de-de/getting-started`

So, instead of sending 301, how can i send 302 redirect for urls without language code as a prefix.

# Answer
That redirect isn't a drupal standard feature, it is done by the redirect.module.

It is currently using the default response header of the redirect configuration in `\Drupal\redirect\EventSubscriber\RouteNormalizerRequestSubscriber::onKernelRequestRedirect()`. That is a bit weird as that is the default for new manually created redirects which usually should be cached.

I think there is an issue in the redirect module to change that to a different configuration or always using 302, if not, feel free to create one.
> 1 votes

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


# Question
Title: How to display the rendered entity of the "compact" display of the user account in the profile?
I have a site with Drupal 8 and I want to customize the templates of my pages.

I use the Profile module.

How to display the rendered entity of the "compact" display of the user account in the profile ?

This is the template to customize the profile page.

```
{#
/**
 * @file
 *
 * Default theme implementation for profiles.
 *
 * Available variables:
 * - content: Items for the content of the profile.
 *   Use 'content' to print them all, or print a subset such as
 *   'content.title'. Use the following code to exclude the
 *   printing of a given child element:
 *   @code
 *   {{ content|without('title') }}
 *   @endcode
 * - attributes: HTML attributes for the wrapper.
 * - profile: The profile object.
 * - url: The profile URL, if available.
 *
 * @ingroup themeable
 */
#}
<div{{ attributes.addClass('profile--personnel--teaser') }}>

  <div class="views-row">

      {{ ??? RENDERED ENTITY USER COMPACT ??? }}

  </div>

</div>

```

**UPDATE**

```
<div{{ attributes.addClass('profile--personnel--teaser') }}>

  <div class="row">

    <div class="bs-field-type">
      {{ profile.type.entity.label }}
    </div>

    <div class="bs-field-image">
      {{ drupal_entity('user', profile.uid.target_id, 'compact') }}
    </div>

    <h3 class="bs-field-title">
      {{ profile.getOwner().name.value }}
    </h3>

    <div class="bs-field-status">
    </div>

    <div class="bs-field-sex">
      {{ content.field_personnel_sexe }}
    </div>

    <div class="bs-field-age">
      {{ content.field_personnel_naissance }}
    </div>

    <div class="bs-field-address">
      {{ content.field_personnel_adresse }}
    </div>

    <div class="bs-field-contact">
      <a class="btn btn-success" href="/messenger#new">
        <i class="fas fa-comment fa-lg"></i> Envoyer un message
      </a>
    </div>

    <div class="bs-field-more">
      Voir son profil
    </div>

    <div class="bs-field-link">
      <a href="{{ url }}" title="{{ content.title.value }}"></a>
    </div>

  </div>

</div>

```

# Answer
> 0 votes
If you want to render a view mode you will need to wirte a `MY_MODULE_preprocess_HOOK()` and pass it to the TWIG

**OR**

you can install the Twig tweak module and then you can render by specifying the view mode in the TWIG page itself

```
{{ drupal_entity('user', profile.uid.target_id, 'compact') }}

```

# Answer
> 1 votes
If I understand your question correctly, you want to change the view mode when a user's profile page is displayed. I recommend to put this kind of logic in a module, not in your theme. One way to do this, is by implementing the `hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context)`:

```
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'user') {
    $view_mode = 'compact';
  }
}

```

---
Tags: 8, theming, users
---


# Question
Title: From showcase website to e-commerce website
I have a big Drupal 7 showcase website, that needs to evolve in a e-commerce website. I know Drupal e-commerce but I don't know if it's ("easily") possible to upgrade a content type to a "product" content type that can be added to a shopping cart?

# Answer
In order to do that, here is what I did : \- install Drupal Commerce \- create the product (name, ref and price) \- and add the product reference field to the existing product

If that can help...
> 0 votes

---
Tags: commerce
---


# Question
Title: Render an image that is located inside a Paragraph that is inside an Entity Reference
I'm working with Drupal 8.

I have a content type called Lawyer.

This content type has an Entity reference called Firm.

In Firm (which is another content type) I have a Paragraph with an image field in it.

I need to render this image inside node--lawyer.html.twig

I have tried several ways to do it but I can't make it work. Any help?

# Answer
> 3 votes
Assumming a `firm` content type has `field_paragraph` which holds `field_image` of 1 image

for comparison to get *firm name* in twig file you will use

```
{{node.field_firm.entity.title.value}}

```

for *firm paragraph image field value*

```
{{node.field_firm.entity.field_paragraph.entity.field_image.entity.uri.value}}

```

To get the rendered image

```
{%
  set firm_image = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.field_firm.entity.field_paragraph.entity.field_image.entity.uri.value,
    '#attributes': { class: 'yourclass' },
  }
%}
{{firm_image}}

```

**Alternative** way to get referenced entity fields

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


# Question
Title: How to migrate files together with additional fields
In my Drupal 8.4 installation I use the module File Entity. In the module are defined a few additional fields: 'author', 'title', 'alt',... My migration works. The files are imported, but the additional fields are after the import empty.

The complete YML (modules\my\_migration\_module\config\install\migrate\_plus.migration.files.yml) looks like:

```
langcode: en
status: true
id: files
migration_group: import_xml
label: 'Import the test XML file'
source:
  plugin: url
  data_fetcher_plugin: file
  urls: 'http://example.org/test.xml'
  data_parser_plugin: xml
  item_selector: /imports/files
  fields:
    -
      name: id
      label: ID
      selector: ./@id
    -
      name: title
      label: Title
      selector: ./@title
    -
      name: alt
      label: Alt
      selector: ./@alt
    -
      name: author
      label: Author
      selector: ./@author
    -
      name: filename
      label: Filename
      selector: ./@filename
    -
      name: uri
      label: URI
      selector: ./@uri
    -
      name: target
      label: Target
      selector: ./@target
  keys:
    - id
  ids:
    id:
      type: string
process:
  field_alt: alt
  field_title: title
  field_author: author
  filename: filename
  uri:
    plugin: download
    source:
      - uri
      - target
destination:
  plugin: 'entity:file'
  source_path_property: uri
  destination_path_property: target
template: null

```

E.g. for the field title I have tried:

```
field_title: title
title: title
field_title/field_title_value: title
field_title/field_title_value: title
field_title/field_title: title
file__field_titel/field_title_value: title
file__field_titel/field_title: title

```

I have found a solution for a similar problem in Drupal 7: How to migrate fields attached to files? I'm not sure, how can I implement this in Drupal 8.

# Answer
> 1 votes
The YML code is correct. But there is an issue in Drupal core: https://www.drupal.org/project/drupal/issues/2822545

There is also a patch. I have tested the patch and it works: https://www.drupal.org/files/issues/2822545-cannot\_update\_file\_properties-6.patch

The patch can be installed with Composer:

```
{
    ...
    "require": {
        "cweagans/composer-patches": "~1.0",
        "drupal/core": "8.4.6",
        ...
    },
    ...
    "extra": {
        "patches": {
           "drupal/core": {
             "Solve the issue when migrating files with additional fields": "https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch"
            }
        }
    }
}

```

---
Tags: 8, files, migrations
---


# Question
Title: How to collect and publish input from user, using webform and views?
I want to build a form, with a lot of fields that can collect data from a lot of users. than, I want to have the option to play with this data and publish it through views (with sorting options).

How to do that (general steps)?

This is what it tried so far:

I built a new content type, with a few specific fields, that allow me to publish all the data in a lot of ways through views. but, I don't know how to make a form from this content type and these fields, in order to allow anonymous and other users to insert data.

and if I use webform module, I can collect data from users, but I don't know how to publish this data through views (if this possible at all).

# Answer
> 1 votes
For web-form refer to the link http://www.cmsquickstart.com/blog/build-styled-user-feedback-form-webform-drupal-7

And for view you can create node pages and give the permissions to the user to be able to create the node page....

# Answer
> 1 votes
Achieving that can be reached in many ways, I would divide it to the following steps:

**Steps are:**

1. Collect data.
2. Manipulate data.
3. Outpting the data.

There is a lot of ways to collect data, I disagree with using node for that, You want to collect data only, you don't need any features of the node itself.

I will also avoid webform module because it will its own fields (not core fields) and it's a bit more complicated to display the data with the right handlers in views.

I would recommend here entityform module, You can build form easily and have your data stored.

Manipulating the data can be done by using standard entity hooks or directly using Views Bulk Operations (VBO)

The publish option is simply boolean field where its checked or not, and filter that in your view to show only entities which marked as published.

Using views you can easily output your data (Filtered with publish field)

# Answer
> 0 votes
Did you look at entityforms or webform\_entity?

From entityform:

> The Entityforms module enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields.

From webform\_entity:

> This module exposes webform submissions as a fieldable entity on behalf of webform and optionally provides a bundle for each of the content types for which webform functionality is enabled. This allows you to configure fields on a base form that are appended to the fields for the webform for that individual node and these fields can be exposed to views.

These 2 modules are very similar.

# Answer
> 0 votes
Add a new content type form collecting information from user. Set the permission for create content by anonymous user. Then using the view you can display the content.

---
Tags: views, forms, webforms
---


# Question
Title: The database connection is not serializable
I'm getting this error. The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection

I'm using Lightning 2.1.6. I set up a media upload field on my page content type using reference to content/ reference media. It also uses the media browser to upload images. This field allows a single image upload. I get the error when you try to upload an image. And the image doesn't get added. If i allow multiple upload instead of single the error goes away. Also If I disable the "Interface Translation" module the error goes away and the images can be uploaded.

# Answer
I experienced this issue after manually deleting some translated configuration files. From then on I was not able to successfully config import anymore without being interrupted with the fatal error from your question.

I then tried to run config import after uninstalling `locale`, which worked but have also deleted lots of translation from the database. Bad.

I could restore the configs in question and then remove them from the UI before exporting them again. Boring.

So I deleted the original configuration objects from an update function (and thereby also deleted the translations), and afterwards run configuration import again, where the original configs then got restored automatically (as their files still existed) WITHOUT translation.

```
/**
 * Remove unwanted translations.
 */
function MYMODULE_update_8005(&$sandbox) {

  $configs = [
    'image.style.crop_thumbnail',
    'views.view.user_admin_people',
  ];

  foreach ($configs as $config) {
    Drupal::configFactory()->getEditable($config)->delete();
  }
}

```

---

EDIT: Only shortly after I had the same problem again. Again it was a missing config (I deleted manually, don't do that) and took me hours to find out which one exactly. This time it was `menu_item_extras` which required `menu_item_extras.utility.yml`. Actually I uninstalled `menu_item_extras` but maybe `menu_item_extras` can't be uninstalled that simply. But that's a different issue.

What's left to conclude now is: **Did you manually delete some config files prior to getting this error?**
> 1 votes

---
Tags: 8
---


# Question
Title: How to trigger an event when node is saved?
I am trying to execute a piece of code when a node is saved. I am using `hook_node_update`, but it's never triggered when updating a node. Here is my code:

```
function custom_node_update(Drupal Core Entity EntityInterface $node) {
 // Logs a notice
 \Drupal::logger('custom')->notice("entity was updated");
}

```

What is wrong with my code?

# Answer
The parameter passed to code had syntax error.

The correct code will be

```
function custom_node_update(Drupal\Core\Entity\EntityInterface $node) {
  // Logs a notice
  \Drupal::logger('custom')->notice("entity was updated");
}

```
> 1 votes

# Answer
First of all you should look at using hook\_entity\_update. Also, is that code in a module called "custom"? And is that module enabled? Last thing ... the parameter should look something like this `\Drupal\Core\Entity\EntityInterface $entity`. You are missing slashes.
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Drush 9.2 - not working well / not installing with Composer
I am using Ubuntu 17.10 running Apache 2.4 on a Vultr instance. Using virtual host for my.example.com website. Installed Drupal 8.5.1 per recommended Drupal-Composer/Drupal-Project. Apache docroot points to the "web" folder containing Drupal core (ie, where Drupal's update.php lives, among other things). The project root folder is one level up, containing the composer.json file.

File permissions: the project root folder itself is owned by user:www-data; same for Drupal root (web, and below). Drupal status is fine. It looks like Composer installed the /vendor folder \[in the project root\] as user:user.

I have seen so many errors, it's hard to know where to start. So far I have not discovered any underlying logic to them. The goal is simple: to get Drush working on my install, which is nothing special. Even on Windows, I can get Drush half-working.

1. After the install, Drush was at least recognizing its own existence. (At one point, I had the drush.phar helper globally installed, per the instructions from that website.) But "drush status" was claiming that it couldn't find Drupal -- even with the -uri flag, and even with the alias set up in example.site.yml contained in /project-root/drush/sites.

Drush status was looking at *something* that pointed to a deleted docroot folder, but I couldn't find the relevant config, and the only possibility was a path entry in that section of the composer.json file. Which I fixed, but that didn't help Drush.

2. Per the Drush docs, I tried running the drush command from Drupal root, pointing to /vendor/bin; and also in the /vendor/drush/drush folder. Getting permission denied in all cases. \[Why? I'm the user running the command, in folders that I own as the user! Does Drush need www-data group permission?\]

Adding a path command to ~/.profile \[the Ubuntu file for .bash\_profile\] didn't help.

3. The permission denied error was in addition to the error re "command not found" -- when I'm in the very folder where I *know* the command file is located. I tried "chmod +x" on both the /vendor/bin version of drush, and the vendor/drush/drush/ version \[just the "drush" single word file, not the "drush.php" file\], but that didn't solve the problem. I reverted those back.

\[And why is the folder structure so convoluted? Why the middle /drush?\]

4. So, then, I thought that maybe it was a Drupal-Composer issue. So composer did allow for removal of drush/drush. And I deleted all the left-behind drush folders in my user home and in the project folder.
5. Went to re-install Drush using Composer, per the Drush install docs: "composer require drush/drush"

Which fails for me. The main culprit seems to be a symfony/var-dumper conflict \[many versions\] with symfony/http-kernel \[many versions\] -- it's several screens full of the attempted reconciliation, with this conclusion:

* Can only install one of: symfony/var-dumper\[v3.4.8, v4.0.8\].
* Installation request for symfony/var-dumper (locked at v4.0.8) -\> satisfiable by symfony/var-dumper\[v4.0.8\].

updating for symfony/http-kernel (with dependencies): nothing to update

updating for symfony/var-dumper (with dependencies): nothing to update

In composer.lock, the entry for SHK does have a "conflict" parameter that mentions SVD. But I don't know how to fix that \[if that is in fact the source of the "lock" statement above\].

I run a simple website, so probably don't need Drush to move to D8 -- except that others seem to get it working and find it helpful -- and I'd like to join that club.

# Answer
Thanks for the replies. Managed to get things working:

1. I created a new folder (drushtest), and ran composer init to create a drush-only project (myname/drush). Init runs an interactive series of question to create a valid composer.json (with only require: drush/drush \[and a version constraint\]).
2. Ran Composer to install, and it pulled down Drush and its dependencies.
3. Then went to remote server, and copied to /vendor/bin, the two drush files, and to /vendor, the various folders that were in my Drush-only install versus what was already on the remote folder.
4. Deleted the existing composer.lock. In require section of composer.json, added drush/drush: ^9.2 \[with appropriate quote marks\], and ran composer update. Which worked fine. \[I still don't understand the effect of .lock on .json, but I guess we're all learning in the new Drupal 8 way.\]
5. To keep things still simple, went to my Drupal folder (web), and (per Drush docs) ran Drush: "../vendor/bin/drush" -- the first time this generated a shell error re no permission. So ran that again under sudo, and got a no command error. Third time lucky, applied "chmod u+x" to that path-file, and Drush sprang to life, and even identified the correct Drupal installation (with all associated info that one expects when Drush is working) without an alias file. Hurrah!
6. More on file permissions: for ../vendor/bin/drush, added the x flag to the group (permissions are now 754), and can run that command without sudo (under my user name). Which I still find odd, in that my user is the owner (with rwx), and the user:group info is: user:user. But I'm quite new to Linux.
7. File permissions, again: With the above, commands like drush status worked, but running (as the user) drush cc (or cr) gave an error that pointed to another file permissions issue. (Sudo could run those commands OK, but it would be weird to use sudo for some drush commands and not for others -- and who could remember.) Which traced to: in the /home/user folder, there is a hidden .drush folder \[with a factory subfolder containing a bunch of php command files\]. The install process had set ownership of that to root:root. There is more than one way to handle this, but for now I changed ownership (chown) to user:user, and that at least allows drush cr to work.
> 2 votes

---
Tags: drush, composer
---


# Question
Title: Function to check for value prior to using getValue?
I'm trying to write a function that takes into account both regular text fields and entity references and checks for a value prior to using getValue() to assign it to a variable.

```
   function checkUserFieldAvailability($fieldName, $assignedName){
      if (!$user->get($fieldName)->isEmpty()) {
        ${$assignedName} = $user->get($fieldName)->first()->getValue()['target_id'];
      }
      else {
        ${$assignedName} = "";
      }
    }

```

Something like this... Is there an easy way to make it account for both entity references that are assigned like this...

```
$name = $user->get('field_firstname')->first()->getValue()['target_id'];

```

and regular text fields which are assigned like this.

```
$email = $user->get('mail')->getValue();

```

Basically i'm trying to confirm all the fields I'm making assignments too in fact first have a value (to avoid errors) and if not assing an empty string.

# Answer
I think you are looking for the main property of the field:

```
if ($item = $user->get($fieldName)->first()) {
  $string = $item->{$item->mainPropertyName()};
}
else {
  $string = '';
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Add ability to add bundles to an entity that does not currently have bundles?
If you have a custom entity that does not create bundles, is it possible to modify it to allow new bundles to be created?

# Answer
> 0 votes
Possible yes, although not trivial. Not having a bundle means internally, Drupal exposes a default bundle that has the same name as the entity type. So the by far easiest approach would be to create a bundle entity type, create a default bundle with the same id (possibly only in the update path for existing sites) and then allow to create additional ones.

What's hard is changing the bundle of an entity type, that's not officially supported. file\_entity does it for the file entity type, you can have a look at its entity class and the methods it overrides the detect the file type and based on that, sets the bundle.

---
Tags: 8, entities
---


# Question
Title: how to get the original entity on hook_entity_presave?
i actually need it for the content\_moderation\_state entity

```
 function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() !== 'content_moderation_state' ) {
    return;
}
$moderation_state = $entity->get('moderation_state')->getString();

 //code to get the original entity moderation state

```

# Answer
> 20 votes
Use `$entity->original` to get the original entity:

```
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity->getEntityTypeId() !== 'content_moderation_state' ) {
    return;
  }

  $moderation_state = $entity->get('moderation_state')->getString();

  //code to get the original entity moderation state
  $moderation_state_original = $entity->original->get('moderation_state')->getString();

```

# Answer
> 10 votes
If for some reason the `original` property isn't available(in my case in the save() method of a custom content entity) you can get it as

```
$entityOriginal = \Drupal::entityTypeManager()
  ->getStorage('my_entity')
  ->loadUnchanged($entity->id());

```

---
Tags: entities
---


# Question
Title: Drupal migration api: set custom plugin as source in «process» section
I migrated nodes including metatags from D7 to D8. As soon as metatags are not field in D7 I do not have it as common source in d7\_node plugin. Of course, I can extend this plugin with my own and make join with metatag database table. But this variant seems for me not ideal. As I understand I can't execute any db queries inside process plugins, so I need to feed my custom source plugin result to a metatag field in a process section of my migration config. How can I do it and is it possible?

# Answer
> 0 votes
Yes, it is possible to migrate fields but I don't know Metatags.There is an existing issue in Metatags for creating a migration, it may be of help. https://www.drupal.org/project/metatag/issues/2563649

---
Tags: migrations
---


# Question
Title: How to display the rendered entity of the user's profile with comments?
I installed the modules "Twig tweak" and "Profile"

In the comment twig, I want to display the rendered entity of the profile ("personnel" type and "teaser" display). I tried this :

```
{{ drupal_entity('profile', comment.uid.target_id, 'teaser') }}

```

But it does not work.

The goal is to view the author's profile, not are user account.

```
{#
/**
 * @file
 * Default theme implementation for comments.
 *
 * Available variables:
 * - author: Comment author. Can be a link or plain text.
 * - content: The content-related items for the comment display. Use
 *   {{ content }} to print them all, or print a subset such as
 *   {{ content.field_example }}. Use the following code to temporarily suppress
 *   the printing of a given child element:
 *   @code
 *   {{ content|without('field_example') }}
 *   @endcode
 * - created: Formatted date and time for when the comment was created.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.created' variable.
 * - changed: Formatted date and time for when the comment was last changed.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.changed' variable.
 * - permalink: Comment permalink.
 * - submitted: Submission information created from author and created
 *   during template_preprocess_comment().
 * - user_picture: The comment author's profile picture.
 * - status: Comment status. Possible values are:
 *   unpublished, published, or preview.
 * - title: Comment title, linked to the comment.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class may contain one or more of the following classes:
 *   - comment: The current template type; for instance, 'theming hook'.
 *   - by-anonymous: Comment by an unregistered user.
 *   - by-{entity-type}-author: Comment by the author of the parent entity,
 *     eg. by-node-author.
 *   - preview: When previewing a new or edited comment.
 *   The following applies only to viewers who are registered users:
 *   - unpublished: An unpublished comment visible only to administrators.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - content_attributes: List of classes for the styling of the comment content.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - threaded: A flag indicating whether the comments are threaded or not.
 *
 * These variables are provided to give context about the parent comment (if
 * any):
 * - comment_parent: Full parent comment entity (if any).
 * - parent_author: Equivalent to author for the parent comment.
 * - parent_created: Equivalent to created for the parent comment.
 * - parent_changed: Equivalent to changed for the parent comment.
 * - parent_title: Equivalent to title for the parent comment.
 * - parent_permalink: Equivalent to permalink for the parent comment.
 * - parent: A text string of parent comment submission information created from
 *   'parent_author' and 'parent_created' during template_preprocess_comment().
 *   This information is presented to help screen readers follow lengthy
 *   discussion threads. You can hide this from sighted users using the class
 *   visually-hidden.
 *
 * These two variables are provided for context:
 * - comment: Full comment object.
 * - entity: Entity the comments are attached to.
 *
 * @see template_preprocess_comment()
 *
 * @ingroup themeable
 */
#}

<article{{ attributes.addClass('js-comment comment--field-article-commentaire') }}>

  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bs-region-comment">

    <div class="col-xs-3 col-sm-3 col-md-2 col-lg-2 bs-left">
      {{ drupal_entity('profile', comment.uid.target_id, 'teaser') }}
      {{ created }}
    </div>

    <div class="col-xs-9 col-sm-9 col-md-10 col-lg-10 bs-right">
     {{ content.field_article_commentaire }}
     {{ content.links }}
     {{ content.flag_report_comment }}
    </div>

  </div>

</article>

```

On the "compact" view of the user, a profile field appears.

How to display in twig, the url of the profile?

I want the image and the user name to point to his profile (not to his account).

# Answer
> 1 votes
*If I understand you correctly.* You can render profile entity using `Twig tweak`

```
{{ drupal_entity('profile', comment.uid.entity.personal_profile.target_id) }}

```

> **FYI :** The first Parameter for drupal\_entity function is the **entity type**, Then **id** of the entity, then **view mode**. See `TwigExtension.php` file in `twig_tweak/src` folder

```
public function drupalEntity($entity_type, $id = NULL, $view_mode = NULL, $langcode = NULL, $check_access = TRUE)

```

> Its better to install Devel module and then you can use `kint()` for debugging the variables

---
Tags: 8, theming, users
---


# Question
Title: Way to remove the Override Title form option in Panel component config?
I am making a Panel Component, in D7, and do not want to show the title. I can just not render out the title on the page - that's fine - but I'd also like to remove the form fields that allow you to enter in the title.

Would anyone know how to do this? I cannot find any info out there.

# Answer
The function responsible for the overriding title:

```
/**
 * Add the default FAPI elements to the content type configuration form.
 */
function ctools_content_configure_form_defaults($form, &$form_state) {
  $plugin = $form_state['plugin'];
  $subtype = $form_state['subtype'];
  $contexts = isset($form_state['contexts']) ? $form_state['contexts'] : NULL;
  $conf = $form_state['conf'];

  $add_submit = FALSE;
  if (!empty($subtype['required context']) && is_array($contexts)) {
    $form['context'] = ctools_context_selector($contexts, $subtype['required context'], isset($conf['context']) ? $conf['context'] : array());
    $add_submit = TRUE;
  }

  ctools_include('dependent');

  // Unless we're not allowed to override the title on this content type, add this
  // gadget to all panes.
  if (empty($plugin['no title override']) && empty($subtype['no title override'])) {
    $form['aligner_start'] = array(
      '#markup' => '<div class="option-text-aligner clearfix">',
    );
    $form['override_title'] = array(
      '#type' => 'checkbox',
      '#default_value' => isset($conf['override_title']) ? $conf['override_title'] : '',
      '#title' => t('Override title'),
      '#id' => 'override-title-checkbox',
    );
    $form['override_title_text'] = array(
      '#type' => 'textfield',
      '#default_value' => isset($conf['override_title_text']) ? $conf['override_title_text'] : '',
      '#size' => 35,
      '#id' => 'override-title-textfield',
      '#dependency' => array('override-title-checkbox' => array(1)),
      '#dependency_type' => 'hidden',
    );
    $form['override_title_heading'] = array(
      '#type' => 'select',
      '#default_value' => isset($conf['override_title_heading']) ? $conf['override_title_heading'] : 'h2',
      '#options' => array(
        'h1' => t('h1'),
        'h2' => t('h2'),
        'h3' => t('h3'),
        'h4' => t('h4'),
        'h5' => t('h5'),
        'h6' => t('h6'),
        'div' => t('div'),
        'span' => t('span'),
      ),
      '#id' => 'override-title-heading',
      '#dependency' => array('override-title-checkbox' => array(1)),
      '#dependency_type' => 'hidden',
    );

    $form['aligner_stop'] = array(
      '#markup' => '</div>',
    );
    if (is_array($contexts)) {
      $form['override_title_markup'] = array(
        '#prefix' => '<div class="description">',
        '#suffix' => '</div>',
        '#markup' => t('You may use %keywords from contexts, as well as %title to contain the original title.'),
      );
    }
    $add_submit = TRUE;
  }

  if ($add_submit) {
    // '#submit' is already set up due to the wizard.
    $form['#submit'][] = 'ctools_content_configure_form_defaults_submit';
  }
  return $form;
}

```

states on line 513:

> // Unless we're not allowed to override the title on this content type, add this
> // gadget to all panes.

which means you could just add the following array members to the existing $plugin or $subtype:

```
  $plugin['no title override'] = TRUE;
  $subtype['no title override'] = TRUE;

```

and theoretically it should work.
> 1 votes

---
Tags: 7, panels
---