Hide Custom block if there is no block content Drupal 8

I had a situation when my custom block doesn’t have content and I don’t want to display the block at all, but rest of the block markup will be there in the DOM.  To avoid this situation you might like to render it programmatically, only when there is content in the block markup.

You can add these lines of code in your hook_preprocess or hook_preprocess_page, wherever you want.

$block = \Drupal\block\Entity\Block::load('BLOCK_MACHINE_NAME');
$block_content = \Drupal::entityTypeManager()
// this line is preety important, this helps making makrp visible in block object
$block_markup = \Drupal::service('renderer')->renderRoot($block_content);
$markup = $block_content['content']['#markup'];

Now you can check if the markup is not empty then set the variable else don’t.

if(isset($markup)) {
$variables['custom_block']  = $block_content

Now you can access this variable in your twig template file and render it conditionally

{% if custom_block %}
{% endif %}

Create a modal popup Drupal 8

This is the simplest way to create a popup in drupal 8. You don’t need any other contributed module to achieve this.

Actually, you just need to create URL similar to this one.

open in popup

This will open the content of hyperlink reference into the modal.

To create above hyperlink in form API, use the below code.

use Drupal\Core\Url;
$url = Url::fromRoute('entity.node.edit_form', ['node' => 23]);
$form['link'] = array(
  '#type' => 'link',
  '#title' => 'open in popup',
  '#url' => $url,
  '#attributes' => [
  'class' => ['use-ajax'],
  'data-dialog-type' => 'modal',

Create a link form api Drupal 8

use Drupal\Core\Url;
$nid = 23   // node id you want to open
$url = Url::fromRoute('entity.node.edit_form', ['node' => 23],['query' => ['key' => 'value']]);  //get the route name from module.routing.yml file
$form['link'] = array(
'#type' => 'link',
'#title' => 'open link',
'#url' => $url,

This will generate below html

<a href="/node/23/edit?key=value" data-drupal-selector="edit-link" id="edit-link">open link</a>

Trim Query Parameters From URL

There are several ways to solve this problem. These are the two most prominent way to achieve this.

1. Php way: Parse, trim and rebuild


2. Using preg_replce


First one is the easy way to do it and also do not require any external library.

On the other hand, the second one is bit lengthy but clean way to achieve it and also require an external library (pecl/http) to rebuild the URL which has been disassembled by parsing it.