Drupal Problems and Solutions

DrupalABC aims to provide solution to programming problems faced by Drupal developers.Start learning by reading some of the latest problems below-

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: {}

What should be the NGINX settings for Drupal 7 website

Following NGINX server block can be used to run Drupal 7.

server {
        server_name YOURWEBSITENAME;
        root /var/www/html/drupal7;

        index index.php;

        location = /favicon.ico {
                log_not_found off;
                access_log off;

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;

How to add content between view rows using twig in Drupal 8?

There is sometimes a situation in which you have to theme each and every element displayed in a different way. There isn't any twig to override in case you need overriding till row level. To solve this problem can you can use for loop and iterate using row variable.

{% for row in rows %}

  {% if loop.index == 1 %}

    <!-- Do Some Changes -->

  {% endif %}

  {% if loop.index == 2 %}

    <!-- Do Some Changes --> 

  {% endif %}

{% endfor %}

How to fetch Drupal node data in Angular JS

Angular JS can be used for creating a headless Drupal website. To fetch a node data in angular you have to first expose nodes data by enabling REST related modules provided by Drupal 8 core. Once that has been done, you simply have to send an HTTP get a request from Angular to got JSON data of Drupal node.

Here is the angular JS code to achieve that 


$http.get("http://exampledrupalwebsite.com/node/1?_format=json") .then(function(response) { $scope.node_data = response.data; });

How to enable CORS in Drupal 8

Most of the Drupal websites are getting converted to Headless applications. Most important configuration to achieve that is by enabling CORS in Drupal. If CORS is not enabled your headless app will not be able to fetch data from Drupal. To do that : 

1. Copy default.services.yml and create file services.yml.

2. Go to the last configuration in the file i.e CORS settings. Modify it in this way to allow cross-origin requests.

   # Configure Cross-Site HTTP requests (CORS).

   # Read https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS