You are here

function commerce_stock_create_instance in Commerce Stock 7

Creates a required instance of a stock 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.

2 calls to commerce_stock_create_instance()
commerce_stock_admin_form_submit in includes/commerce_stock.admin.inc
Add or remove the Stock field from product types.
commerce_stock_configure_product_type in ./commerce_stock.module
Ensures a stock field is present on a product type bundle.

File

./commerce_stock.module, line 405
Allow commerce products to have stock levels associated with their SKU

Code

function commerce_stock_create_instance($field_name, $field_type, $required, $entity_type, $bundle, $label, $description = NULL, $weight = 0) {

  // If a field type we know should exist isn't found, clear the Field cache.
  //  if (!field_info_field_types('commerce_stock')) {
  //    field_cache_clear();
  //  }
  // Look for or add the specified stock field to the requested entity bundle.
  $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' => $field_type,
      'cardinality' => 1,
      'entity_types' => array(
        $entity_type,
      ),
      'translatable' => FALSE,
      'locked' => FALSE,
    );
    if ($field_type == 'list_boolean') {
      $field['settings'] = array(
        'allowed_values' => array(
          0,
          1,
        ),
        'allowed_values_function' => '',
      );
    }
    $field = field_create_field($field);
  }
  if (empty($instance)) {
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => $label,
      'required' => $required,
      'settings' => array(),
      'display' => array(),
      'description' => $description,
      'default_value' => array(
        array(
          'value' => "0",
        ),
      ),
    );
    if ($field_type == 'list_boolean') {
      $instance['widget'] = array(
        'type' => 'options_onoff',
        'settings' => array(
          'display_label' => TRUE,
        ),
      );
    }
    $entity_info = entity_get_info($entity_type);

    // Spoof the default view mode so its display type is set.
    $entity_info['view modes']['default'] = array();
    field_create_instance($instance);
  }
}