public function EntityResource::post

Responds to entity POST requests and saves the new entity.

Parameters

mixed $id: Ignored. A new entity is created with a new ID.

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

Return value

\Drupal\rest\ResourceResponse The HTTP response object.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException

File

drupal/core/modules/rest/lib/Drupal/rest/Plugin/rest/resource/EntityResource.php, line 74
Definition of Drupal\rest\Plugin\rest\resource\EntityResource.

Class

EntityResource
Represents entities as resources.

Namespace

Drupal\rest\Plugin\rest\resource

Code

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);
  }
}