Skip to main content

Simple Configuration API

The configuration API comes in two flavors - the (simple) Config API and the Configuration Entity API.

The key difference is that the Config API is the singleton use case.

A singleton is where there can be only a single instance of this configuration.

A good example would be the site's name.

The Configuration Entity API should store multiple configuration sets - for example, node types, views, vocabularies, and fields.

 

Building Forms Programmatically

Drupal provides a Form API in order to achieve consistency in its form processing and presentation while simplifying code and reducing the amount of HTML that a module must explicitly generate.

FormBuilder handles the low-level processing of forms such as rendering the necessary HTML, initial processing of incoming $_POST data, and delegating to your implementation of FormInterface to validate and process submitted data.

Drupal let you create your own custom middlewares

Middleware can be used to intercept and modify HTTP requests before they reach the application, allowing developers to inspect and filter the requests based on specific criteria. 

This can be useful for adding additional security measures, handling errors and exceptions, or modifying the request/response header.

Creating And Using URLs And Links Programmatically

When building a new module, you always get to the point where you want to use the routes you have been created, or other URLs, so if you find yourself always looking for how to print out a URL, this article is for you.

The difficulty is that finding or printing out a URL is very contextual and there is more than one way to get or use this information in Drupal. 

You might have a node object that you need to convert into a fully qualified path, or you want to print out the path of a route, each of which has different approaches.

Adding assets (CSS, JS) to a Drupal module via *.libraries.yml

In Drupal 8 and later versions, stylesheets (CSS) and JavaScript (JS), jQuery, React, and even Angular, are loaded through the same system for modules (code) and themes, for everything: asset libraries. 

Asset libraries can contain one or more CSS assets, one or more JS assets, and one or more JS settings.

Drupal uses a high-level principle: assets (CSS or JS) are only loaded if you tell Drupal it should load them. 

Drupal does not load all assets (CSS/JS) on all pages because this is bad for front-end performance.

 

How to code Entity/Node/Account Fields ? get, set and create

Retrieving field values in entities is fairly simple, but there are several ways to do this. 

Let's see how best to work with field values in custom code. 

You can always see the latest information on working with fields on the official website:

https://www.drupal.org/docs/8/api/entity-api/working-with-the-entity-api

 

In this article, we will look at examples of working with values. 

You don't have to remember how to code the fields work, just remember to return to this page. 

Sending JSON with Basic Authentication Credentials

To post JSON to a server with Basic Authentication credentials, you need to make an HTTP POST or PUT request, include the JSON in the body of the HTTP message, and pass the "Authorization: Basic [token]" HTTP header to the server. 
The [token] is a Base64 encoded string of user credentials in the form of a login:password string. 
In this POST JSON with a Basic Authentication Credentials Example, we send a POST request with JSON body and "Authorization: Basic [token]" header to the ReqBin echo URL. 

<script>
      var USERNAME="admi";
      var PASSWORD="chanud";

      var person = {
        firstName:"tester2",
        lastName:"drupal",
        userName:"tester2drupal",
        eMail:"teter2@drupalvip.com",
        pass1:"teter2drupal",
        passConfirm:"teter2drupal",
        role:"Affiliate" 
      };
      
      $.ajax({
        type: "POST",
        url: 'https://mydomain/api/route',
        dataType: 'json',
        headers: {
         "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
        },
        data: person,
        //data: JSON.stringify(person),
        success: function (data) {
          $("response").html(data.msg);
        },                
      });
    </script>

Custom controller with JSON response

how to create a custom controller with JSON response in Drupal 8.

this might work on Drupal 9 and 10, but I never tested it on these versions.

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class JsonApiArticlesController
 * @package Drupal\mymodule\Controller
 */
class JsonApiArticlesController {

  /**
   * @return JsonResponse
   */
  public function index() {
    return new JsonResponse([ 'data' => $this->getData(), 'method' => 'GET', 'status'=> 200]);
  }

  /**
   * @return array
   */
  public function getData() {

    $result=[];
    $query = \Drupal::entityQuery('node')
      ->condition('type', 'article')
      ->sort('title', 'DESC');
    $nodes_ids = $query->execute();
    if ($nodes_ids) {
      foreach ($nodes_ids as $node_id) {
        $node = \Drupal\node\Entity\Node::load($node_id);
        $result[] = [
          "id" => $node->id(),
          "title" => $node->getTitle(),
        ];
      }
    }
    return $result;
  }
}
use Symfony\Component\HttpFoundation\JsonResponse;

// if you know the data to send when creating the response
$response = new JsonResponse(['data' => 123]);

// if you don't know the data to send or if you want to customize the encoding options
$response = new JsonResponse();
// ...
// configure any custom encoding options (if needed, it must be called before "setData()")
//$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION);
$response->setData(['data' => 123]);

// if the data to send is already encoded in JSON
$response = JsonResponse::fromJsonString('{ "data": 123 }');