Drupal Problems and Solutions

DrupalABC aims to provide solutions to programming problems faced by Drupal developers. Start learning by reading some of the latest problems below. You can also learn website building in Drupal 9 by reading the website building guide.

How to load a form in a block in Drupal 8

You can use the following block code to load a form in a block in Drupal 8.


namespace Drupal\example_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

 * Provides a 'ExmpleFormBlock' block.
 * @Block(
 *  id = "ExampleFormBlock",
 *  admin_label = @Translation("Example Form Block"),
 * )
class ExampleFormBlock extends BlockBase {

   * {@inheritdoc}
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\example_module\Form\ExampleForm');


Example Form is the class of form which has to be displayed in the block. You can also use core and contributed provided forms.


How to fetch all the terms of a vocabulary in Drupal 8?

Since taxonomy term is an entity all the Terms for a specific vocabulary can be fetched using following entity query.

$query = \Drupal::entityQuery('taxonomy_term')->condition('vid', 'YOUR_VOCABULARY');
$result = $query->execute();
foreach ($result as $key => $value) {
      $result[$key] = Term::load($value)->getName();

$result can used for getting key value array of TID and Term Name.

How to attach JS library in a view in Drupal 8?

JS library to a view can be attached using hook_views_pre_render(). Use the following code to achieve it:

 * Implements hook_views_pre_render().
function your_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'YOUR_VIEW_ID' && $view->current_display == 'YOUR_VIEW_DISPLAY') {
    $view->element['#attached']['library'][] = 'your_module/your_library';

How to remove a field from views output in Drupal 8

You can use hook_views_pre_render and change the value of the field in the following way. In this, I have removed field_image from 2nd row in the view. 

function your_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() == "view_id") {
      foreach ($view->result as $key => $value) {
        if($key == 1 ) {
            $value->_entity->set('field_image', ['target_id' => 0]);


How to attach jQuery in Drupal 8 Controller

jQuery file can be added to the controller in the following way:

In the controller, file make sure that library defined in libraries.yml is returned along with the markup,

return [
      '#type' => 'markup',
      '#markup' => '<div id="my_js_application"></div>',
      '#attached' => ['library' => ['example_module/example_library']]

In the libraries.yml, the example_library has to be defined.

  version: 1.x
    js/myapp.js: {}

    - core/jquery


Now in myapp.js use the following syntax :

(function ($, Drupal) {

}(jQuery, Drupal));