1 field.crud.inc field_create_instance($instance)

Creates an instance of a field, binding it to a bundle.

Parameters

array $instance: A field instance definition array. The field_name, entity_type and bundle properties are required. Other properties, if omitted, will be given the following default values:

  • label: the field name
  • description: empty string
  • required: FALSE
  • default_value: NULL
  • default_value_function: NULL
  • settings: each omitted setting is given the default value specified in hook_field_info().
  • widget:
  • display: Settings for the 'default' display mode will be added if not present, and each display mode in the definition will be completed with the following default values:

    Display modes not present in the definition are left empty, and the field will not be displayed in this mode.

Return value

array: The $instance array with the id property filled in.

Throws

FieldException

See: Field API data structures.

See also

hook_field_schema_alter()

Related topics

File

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

Code

function field_create_instance($instance) {
  // Populate defaults.
  $instance += field_defaults_instance();

  // Ensure the field instance is unique within the bundle.
  // We only check for instances of active fields, since adding an instance of
  // a disabled field is not supported.
  $prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
  if (!empty($prior_instance)) {
    $message = t('Attempt to create an instance of field @field_name on bundle @bundle that already has an instance of that field.', array('@field_name' => $instance['field_name'], '@bundle' => $instance['bundle']));
    throw new FieldException($message);
  }

  // Give the instance a default label.
  if (strlen($instance['label']) === 0) {
    $instance['label'] = $instance['field_name'];
  }

  // Populate the instance default settings.
  $field = field_read_field($instance['field_name']);
  if (empty($field)) {
    $message = t('Attempted to create an instance of field @field_name, but that field does not exist.', array('@field_name' => $instance['field_name']));
    throw new FieldException($message);
  }
  $instance['settings'] += field_info_instance_settings($field['type']);

  // Validate the fully populated instance.
  field_validate_instance($instance, FALSE, TRUE);

  _field_write_instance($instance);

  // Clear caches
  field_cache_clear();

  // Invoke external hooks after the cache is cleared for API consistency.
  module_invoke_all('field_create_instance', $instance);
  token_cache_clear();

  return $instance;
}