Creating and saving an entity
In this recipe, we will define a route to create a new article. The route will be for an HTTP POST
request sending JSON to specify the article’s title and body text.
How to do it…
- Create a
store
method in theArticleController
controller in your module that will receive the incoming request object:<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class ArticleController extends ControllerBase {
public function store(Request $request):
JsonResponse {
}
}
We need the request object so that we can retrieve the JSON provided in the request payload.
- Next, we will convert the request’s content from JSON to a PHP array using Drupal’s JSON serialization utility class:
public function store(Request $request):
...