public function EntityResource::createRelationship in JSON:API 8
Adds a relationship to a to-many relationship.
Parameters
\Drupal\Core\Entity\EntityInterface $entity: The requested entity.
string $related_field: The related field name.
mixed $parsed_field_list: The entity reference field list of items to add, or a response object in case of error.
\Symfony\Component\HttpFoundation\Request $request: The request object.
Return value
\Drupal\jsonapi\ResourceResponse The response.
Throws
\Drupal\Core\Entity\EntityStorageException
File
- src/
Controller/ EntityResource.php, line 585
Class
- EntityResource
- Process all entity requests.
Namespace
Drupal\jsonapi\ControllerCode
public function createRelationship(EntityInterface $entity, $related_field, $parsed_field_list, Request $request) {
$related_field = $this->resourceType
->getInternalName($related_field);
/* @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $parsed_field_list */
$this
->relationshipAccess($entity, 'update', $related_field);
if ($parsed_field_list instanceof Response) {
// This usually means that there was an error, so there is no point on
// processing further.
return $parsed_field_list;
}
// According to the specification, you are only allowed to POST to a
// relationship if it is a to-many relationship.
/* @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $field_list */
$field_list = $entity->{$related_field};
$is_multiple = $field_list
->getFieldDefinition()
->getFieldStorageDefinition()
->isMultiple();
if (!$is_multiple) {
throw new ConflictHttpException(sprintf('You can only POST to to-many relationships. %s is a to-one relationship.', $related_field));
}
$field_access = $field_list
->access('edit', NULL, TRUE);
if (!$field_access
->isAllowed()) {
$field_name = $field_list
->getName();
throw new EntityAccessDeniedHttpException($entity, $field_access, '/data/relationships/' . $field_name, sprintf('The current user is not allowed to PATCH the selected field (%s).', $field_name));
}
$original_field_list = clone $field_list;
// Time to save the relationship.
foreach ($parsed_field_list as $field_item) {
$field_list
->appendItem($field_item
->getValue());
}
$this
->validate($entity);
$entity
->save();
$status = static::relationshipArityIsAffected($original_field_list, $field_list) ? 200 : 204;
return $this
->getRelationship($entity, $related_field, $request, $status);
}