You are here

function commerce_product_reference_create_instance in Commerce Core 7

Creates a required, locked instance of a product reference field on the specified bundle.

Parameters

$field_name: The name of the field; if it already exists, a new instance of the existing field will be created. For fields governed by the Commerce modules, this should begin with commerce_.

$entity_type: The type of entity the field instance will be attached to.

$bundle: The bundle name of the entity the field instance will be attached to.

$label: The label of the field instance.

$weight: The default weight of the field instance widget and display.

1 call to commerce_product_reference_create_instance()
commerce_product_line_item_configuration in modules/product_reference/commerce_product_reference.module
Ensures the product line item type contains a product reference field.

File

modules/product_reference/commerce_product_reference.module, line 1186
Defines a field type for referencing products from other entities.

Code

function commerce_product_reference_create_instance($field_name, $entity_type, $bundle, $label, $weight = 0) {

  // Look for or add the specified field to the requested entity bundle.
  commerce_activate_field($field_name);
  field_cache_clear();
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  if (empty($field)) {
    $field = array(
      'field_name' => $field_name,
      'type' => 'commerce_product_reference',
      'cardinality' => 1,
      'entity_types' => array(
        $entity_type,
      ),
      'translatable' => FALSE,
      'locked' => TRUE,
    );
    $field = field_create_field($field);
  }
  if (empty($instance)) {
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => $label,
      'required' => TRUE,
      'settings' => array(),
      'widget' => array(
        'type' => 'commerce_product_reference_autocomplete',
        'weight' => $weight,
      ),
      'display' => array(
        'display' => array(
          'label' => 'hidden',
          'weight' => $weight,
        ),
      ),
    );
    field_create_instance($instance);
  }
}