protected function FieldInstance::saveNew

Saves a new field instance definition.

Return value

SAVED_NEW if the definition was saved.

Throws

\Drupal\field\FieldException If the field instance definition is invalid.

\Drupal\Core\Entity\EntityStorageException In case of failures at the configuration storage level.

1 call to FieldInstance::saveNew()
FieldInstance::save in drupal/core/modules/field/lib/Drupal/field/Plugin/Core/Entity/FieldInstance.php
Overrides \Drupal\Core\Entity\Entity::save().

File

drupal/core/modules/field/lib/Drupal/field/Plugin/Core/Entity/FieldInstance.php, line 347
Contains \Drupal\field\Plugin\Core\Entity\FieldInstance.

Class

FieldInstance
Defines the Field instance entity.

Namespace

Drupal\field\Plugin\Core\Entity

Code

protected function saveNew() {
  $module_handler = \Drupal::moduleHandler();
  $instance_controller = \Drupal::entityManager()
    ->getStorageController($this->entityType);

  // Check that the field can be attached to this entity type.
  if (!empty($this->field->entity_types) && !in_array($this->entity_type, $this->field->entity_types)) {
    throw new FieldException(format_string('Attempt to create an instance of field @field_id on forbidden entity type @entity_type.', array(
      '@field_id' => $this->field->id,
      '@entity_type' => $this->entity_type,
    )));
  }

  // Assign the ID.
  $this->id = $this
    ->id();

  // Ensure the field instance is unique within the bundle.
  if ($prior_instance = current($instance_controller
    ->load(array(
    $this->id,
  )))) {
    throw new FieldException(format_string('Attempt to create an instance of field @field_id on bundle @bundle that already has an instance of that field.', array(
      '@field_id' => $this->field->id,
      '@bundle' => $this->bundle,
    )));
  }

  // Set the field UUID.
  $this->field_uuid = $this->field->uuid;

  // Ensure default values are present.
  $this
    ->prepareSave();

  // Save the configuration.
  $result = parent::save();
  field_cache_clear();

  // Invoke hook_field_create_instance() after the cache is cleared for API
  // consistency.
  $module_handler
    ->invokeAll('field_create_instance', array(
    $this,
  ));
  return $result;
}