Do you want to know how to Drupal?

Let's Drupal

How to extract entity id from autocomplete string in Drupal?

When we use autocomplete field, the submitted value will look something like this "Title of the entity (10)". To extract the current entity id from this string we can use helper function extractEntityIdFromAutocompleteInput  from EntityAutocomplete

$autocomplete_data = 'Title of the entity (10)';
$entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($autocomplete_data);

 


How to display / place a block based on route in Drupal?

By default Drupal provides and option to set visibility of block based on path, but quite often it is not what actually want.

To solve this issue we can use a small, but a very useful module Route condition. This module provides condition plugin, which will display the block based on routes. Basically it works the same way as Pages condition plugin. So, I believe you will not find any issues configure it.
 


How prepopulate values on a form from request in Drupal?

Let's imagine we have a node with field category and we want to create a link in the view and pass a category in the request ?field_category=1. Unfortunately, it will not like this by default. Fortunately, we have a solution! We need a module prepopulated and pass a parameter a special way:

1) For entity reference fields

http://yourdoamain.com/node/add/page?edit[field_category][widget][0][target_id]=1

2) Normal fields

http://yourdoamain.com/node/add/page?edit[field_body][widget][0][value]=Something

How to get a route by URI in Drupal?

If you have a basic path we can get route using router.no_access_checks service. Keep in my you have to have a leading slash

$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');

In case you have URL object we can get route from it like this

$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());