function hook_field_update_forbid

Forbid a field update from occurring.

Any module may forbid any update for any reason. For example, the field's storage module might forbid an update if it would change the storage schema while data for the field exists. A field type module might forbid an update if it would change existing data's semantics, or if there are external dependencies on field settings that cannot be updated.

To forbid the update from occurring, throw a Drupal\field\FieldUpdateForbiddenException.

Parameters

$field: The field as it will be post-update.

$prior_field: The field as it is pre-update.

$has_data: Whether any data already exists for this field.

Related topics

3 functions implement hook_field_update_forbid()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

field_sql_storage_field_update_forbid in drupal/core/modules/field_sql_storage/field_sql_storage.module
Implements hook_field_update_forbid().
field_test_field_update_forbid in drupal/core/modules/field/tests/modules/field_test/field_test.field.inc
Implements hook_field_update_forbid().
options_field_update_forbid in drupal/core/modules/options/options.module
Implements hook_field_update_forbid().
1 invocation of hook_field_update_forbid()
Field::saveUpdated in drupal/core/modules/field/lib/Drupal/field/Plugin/Core/Entity/Field.php
Saves an updated field definition.

File

drupal/core/modules/field/field.api.php, line 1869

Code

function hook_field_update_forbid($field, $prior_field, $has_data) {

  // A 'list' field stores integer keys mapped to display values. If
  // the new field will have fewer values, and any data exists for the
  // abandoned keys, the field will have no way to display them. So,
  // forbid such an update.
  if ($has_data && count($field['settings']['allowed_values']) < count($prior_field['settings']['allowed_values'])) {

    // Identify the keys that will be lost.
    $lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($prior_field['settings']['allowed_values']));

    // If any data exist for those keys, forbid the update.
    $query = new EntityFieldQuery();
    $found = $query
      ->fieldCondition($prior_field['field_name'], 'value', $lost_keys)
      ->range(0, 1)
      ->execute();
    if ($found) {
      throw new FieldUpdateForbiddenException("Cannot update a list field not to include keys with existing data");
    }
  }
}