1.20.x field.api.php hook_field_update_forbid($field, $prior_field, $has_data)

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 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

File

modules/field/field.api.php, line 2536
Hooks provided by the Field module.

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