7.x field.api.php hook_field_create_instance($instance)

Act on a field instance being created.

This hook is invoked from field_create_instance() after the instance record is saved, so it cannot be used to modify the instance itself.

Parameters

$instance: The instance just created.

Related topics

1 invocation of hook_field_create_instance()
field_create_instance in modules/field/field.crud.inc
Creates an instance of a field, binding it to a bundle.

File

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

Code

function hook_field_create_instance($instance) {

  // @todo Needs function body.
}

Comments

alanom’s picture

This happens when the field instance is first created (e.g. after the manage fields page, before loading the first field settings page). This is before the instance settings form, so instance settings won't yet be defined.

To act after instance settings are defined, one option is hook_field_update_instance(). This is also called after the first create step, and also after saving settings, so if field instance settings are required, they need to be tested for.

brian_c’s picture

This is somewhat inaccurate... when this hook is called, there already exists a database record in `field_config_instance` with default instance settings for the bundle you're adding it to. So instance settings ARE defined by this point. This is because field_create_instance() calls _field_write_instance() (which populates defaults) before invoking this hook.

However (somewhat bizarrely), these settings are NOT populated into the $instance variable that is passed to this hook, which is probably where the confusion arises.

But it is definitely possible to modify initial instance settings using this hook, you just have to load & save them from disk yourself instead of simply modifying $instance within the hook.

Here for example, is a hook implementation that defaults all labels to "Hidden" for new fields:

// implementation of hook_field_create_instance()
// sets all labels to Hidden for new fields
function MODULENAME_field_create_instance($instance){
  // fetch the instance info
  $instance_info = field_info_instance(
    $instance['entity_type'],
    $instance['field_name'],
    $instance['bundle']
  );

  // set label in each display to hidden
  foreach( $instance_info['display'] as &$display ){
    $display['label'] = 'hidden';
  }
  
  // save back to disk
  field_update_instance($instance_info);
}