function field_attach_insert

Save field data for a new entity.

The passed-in entity must already contain its id and (if applicable) revision id attributes. Default values (if any) will be saved for fields not present in the $entity.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity with fields to save.

Return value

Default values (if any) will be added to the $entity parameter for fields it leaves unspecified.

Related topics

14 calls to field_attach_insert()
CrudTest::testDeleteField in drupal/core/modules/field/lib/Drupal/field/Tests/CrudTest.php
Test the deletion of a field.
CrudTest::testUpdateField in drupal/core/modules/field/lib/Drupal/field/Tests/CrudTest.php
Test updating a field.
FieldAttachOtherTest::testFieldAttachCache in drupal/core/modules/field/lib/Drupal/field/Tests/FieldAttachOtherTest.php
Test field cache.
FieldAttachStorageTest::testEntityCreateRenameBundle in drupal/core/modules/field/lib/Drupal/field/Tests/FieldAttachStorageTest.php
Test entity_bundle_create() and entity_bundle_rename().
FieldAttachStorageTest::testEntityDeleteBundle in drupal/core/modules/field/lib/Drupal/field/Tests/FieldAttachStorageTest.php
Test entity_bundle_delete().

... See full list

File

drupal/core/modules/field/field.attach.inc, line 1186
Field attach API, allowing entities (nodes, users, ...) to be 'fieldable'.

Code

function field_attach_insert(EntityInterface $entity) {

  // Ensure we are working with a BC mode entity.
  $entity = $entity
    ->getBCEntity();
  _field_invoke('insert', $entity);

  // Let any module insert field data before the storage engine, accumulating
  // saved fields along the way.
  $skip_fields = array();
  foreach (module_implements('field_storage_pre_insert') as $module) {
    $function = $module . '_field_storage_pre_insert';
    $function($entity, $skip_fields);
  }

  // Collect the storage backends used by the remaining fields in the entities.
  $storages = array();
  foreach (field_info_instances($entity
    ->entityType(), $entity
    ->bundle()) as $instance) {
    $field = field_info_field_by_id($instance['field_id']);
    $field_id = $field['uuid'];
    $field_name = $field['field_name'];
    if (!empty($entity->{$field_name})) {

      // Collect the storage backend if the field has not been written yet.
      if (!isset($skip_fields[$field_id])) {
        $storages[$field['storage']['type']][$field_id] = $field_id;
      }
    }
  }

  // Field storage backends save any remaining unsaved fields.
  foreach ($storages as $storage => $fields) {
    $storage_info = field_info_storage_types($storage);
    module_invoke($storage_info['module'], 'field_storage_write', $entity, FIELD_STORAGE_INSERT, $fields);
  }

  // Let other modules act on inserting the entity.
  module_invoke_all('field_attach_insert', $entity);
}