function field_update_instance

Updates an instance of a field.

Parameters

mixed $instance: Either the \Drupal\field\Plugin\Core\Entity\FieldInstance to update, or an associative array representing an instance structure. If the latter, the required keys and values are:

  • entity_type: The type of the entity the field is attached to.
  • bundle: The bundle this field belongs to.
  • field_name: The name of an existing field.

The other array elements represent properties of the instance, and all properties must be specified or their default values will be used (except internal-use properties, which are assigned automatically). To avoid losing the previously stored properties of the instance when making a change, first load the instance with field_info_instance(), then override the values you want to override, and finally save using this function. Example:

// Fetch an instance info array.
$instance_info = field_info_instance($entity_type, $field_name, $bundle_name);

// Change a single property in the instance definition.
$instance_info['definition']['required'] = TRUE;

// Write the changed definition back.
field_update_instance($instance_info['definition']);

Throws

Drupal\field\FieldException

Deprecated

as of Drupal 8.0. Use $instance->save().

See also

field_info_instance()

field_create_instance()

Related topics

17 calls to field_update_instance()
DatetimeFieldTest::testDefaultValue in drupal/core/modules/datetime/lib/Drupal/datetime/Tests/DatetimeFieldTest.php
Test default value functionality.
EditorSelectionTest::testText in drupal/core/modules/edit/lib/Drupal/edit/Tests/EditorSelectionTest.php
Tests a textual field, without/with text processing, with cardinality 1 and >1, always without a WYSIWYG editor present.
EntityFieldTest::assertComputedProperties in drupal/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
Executes the computed properties tests for the given entity type.
entity_reference_field_update_field in drupal/core/modules/entity_reference/entity_reference.module
Implements hook_field_update_field().
FieldAttachStorageTest::testFieldAttachSaveLoad in drupal/core/modules/field/lib/Drupal/field/Tests/FieldAttachStorageTest.php
Check field values insert, update and load.

... See full list

File

drupal/core/modules/field/field.crud.inc, line 244
Field CRUD API, handling field and field instance creation and deletion.

Code

function field_update_instance($instance) {

  // Module developers can still pass in an array of properties.
  if (is_array($instance)) {
    $instance_loaded = entity_load('field_instance', $instance['entity_type'] . '.' . $instance['bundle'] . '.' . $instance['field_name']);
    if (empty($instance_loaded)) {
      throw new FieldException('Attempt to update a non-existent instance.');
    }

    // Merge incoming values.
    foreach ($instance as $key => $value) {
      $instance_loaded[$key] = $value;
    }
    $instance = $instance_loaded;
  }
  $instance
    ->save();
}