function EntityResource::replaceRelationshipData

Same name in other branches
  1. 9 core/modules/jsonapi/src/Controller/EntityResource.php \Drupal\jsonapi\Controller\EntityResource::replaceRelationshipData()
  2. 8.9.x core/modules/jsonapi/src/Controller/EntityResource.php \Drupal\jsonapi\Controller\EntityResource::replaceRelationshipData()
  3. 11.x core/modules/jsonapi/src/Controller/EntityResource.php \Drupal\jsonapi\Controller\EntityResource::replaceRelationshipData()

Updates the relationship of an entity.

Parameters

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The base JSON:API resource type for the request to be served.

\Drupal\Core\Entity\EntityInterface $entity: The requested entity.

string $related: The related field name.

\Symfony\Component\HttpFoundation\Request $request: The request object.

Return value

\Drupal\jsonapi\ResourceResponse The response.

Throws

\Drupal\Core\Entity\EntityStorageException Thrown when the underlying entity cannot be saved.

\Drupal\jsonapi\Exception\UnprocessableHttpEntityException Thrown when the updated entity does not pass validation.

File

core/modules/jsonapi/src/Controller/EntityResource.php, line 686

Class

EntityResource
Process all entity requests.

Namespace

Drupal\jsonapi\Controller

Code

public function replaceRelationshipData(ResourceType $resource_type, EntityInterface $entity, $related, Request $request) {
    
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $resource_identifiers */
    $resource_identifiers = $this->deserialize($resource_type, $request, ResourceIdentifier::class, $related);
    $internal_relationship_field_name = $resource_type->getInternalName($related);
    // According to the specification, PATCH works a little bit different if the
    // relationship is to-one or to-many.
    
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
    $field_list = $entity->{$internal_relationship_field_name};
    $field_definition = $field_list->getFieldDefinition();
    $is_multiple = $field_definition->getFieldStorageDefinition()
        ->isMultiple();
    $method = $is_multiple ? 'doPatchMultipleRelationship' : 'doPatchIndividualRelationship';
    $this->{$method}($entity, $resource_identifiers, $field_definition);
    $this->validate($entity);
    $entity->save();
    $requires_response = static::relationshipResponseRequiresBody($resource_identifiers, ResourceIdentifier::toResourceIdentifiersWithArityRequired($field_list));
    return $this->getRelationship($resource_type, $entity, $related, $request, $requires_response ? 200 : 204);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.