Skip to main content

Symfony

Displaying 1 - 8 of 8

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 }');

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.

How to keep your session data

Sometimes you need to temporarily store information per same user, which means handling his session data, in previous version of drupal it was easy and more like handling it in PHP programming, but with drupal 8, since the desire was to do everything in OOP strategy it changed.

This article will review some of the options to handle session date which are available on drupal8.

First lets remember how it was done with drupal7: using the $_SESSION in module file during the hooking implementation

In Drupal 8 there's two services to handle session data:

How to share Drupal content via Facebook with correct images

When you share a post of your drupal site on facebook, it will automatically detect the images of your node for you to choose.

But sometimes, it does not detect any images, or the detected images are not what you want. 

You can always upload the main image manually. That's fine, because you are the owner of the site, you know which ones to choose. However, if your readers share that piece of content and it has an ugly image, it does not look attracting at all.