Responds to entity POST requests and saves the new entity.
mixed $id: Ignored. A new entity is created with a new ID.
\Drupal\Core\Entity\EntityInterface $entity: The entity.
\Drupal\rest\ResourceResponse The HTTP response object.
\Symfony\Component\HttpKernel\Exception\HttpException
public function post($id, EntityInterface $entity) {
if (!$entity
->access('create')) {
throw new AccessDeniedHttpException();
}
$definition = $this
->getPluginDefinition();
// Verify that the deserialized entity is of the type that we expect to
// prevent security issues.
if ($entity
->entityType() != $definition['entity_type']) {
throw new BadRequestHttpException(t('Invalid entity type'));
}
// POSTed entities must not have an ID set, because we always want to create
// new entities here.
if (!$entity
->isNew()) {
throw new BadRequestHttpException(t('Only new entities can be created'));
}
foreach ($entity as $field_name => $field) {
if (!$field
->access('create')) {
throw new AccessDeniedHttpException(t('Access denied on creating field @field.', array(
'@field' => $field_name,
)));
}
}
try {
$entity
->save();
watchdog('rest', 'Created entity %type with ID %id.', array(
'%type' => $entity
->entityType(),
'%id' => $entity
->id(),
));
$url = url(strtr($this->pluginId, ':', '/') . '/' . $entity
->id(), array(
'absolute' => TRUE,
));
// 201 Created responses have an empty body.
return new ResourceResponse(NULL, 201, array(
'Location' => $url,
));
} catch (EntityStorageException $e) {
throw new HttpException(500, t('Internal Server Error'), $e);
}
}