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