You are here

function commerce_option_form_alter in Commerce Product Option 7.2

Implements hook_form_alter().

Here we modify the add to cart form.

File

./commerce_option.module, line 519

Code

function commerce_option_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === FALSE) {
    return;
  }

  // Get the current product. Is added in the cart module.
  if (isset($form_state['default_product'])) {
    $product_id = $form_state['default_product']->product_id;
  }
  elseif (isset($form_state['default_product_id'])) {
    $product_id = $form_state['default_product_id'];
  }
  elseif (isset($form_state['products'])) {
    $current_product = reset($form_state['products']);
    $product_id = $current_product->product_id;
  }
  else {
    return;
  }
  $current_product = commerce_product_load($product_id);
  $someFieldIsAdded = FALSE;

  // Iterates the fields of this product. We search for entity reference fields
  // to a commerce option set.
  foreach ($current_product as $field_name => $field) {
    $field_info = field_info_field($field_name);
    if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
      continue;
    }

    // Do not display our options if this field has been marked as an attribute field.
    $field_instance_info = field_info_instance('commerce_product', $field_name, $current_product->type);
    if ($field_instance_info['commerce_cart_settings']['attribute_field']) {
      return;
    }
    $lang_code = field_language('commerce_product', $current_product, $field_name);
    if (!isset($field[$lang_code])) {
      continue;
    }

    // Init the fields' form elements.
    $form[$field_name] = array(
      '#tree' => TRUE,
    );

    // Create a new blank option set.
    foreach ($field[$lang_code] as $key => $data) {
      $option_set = commerce_option_set_load($data['target_id']);
      $values = array(
        'set_id' => $option_set->set_id,
      );
      $option = commerce_option_new($values);
      $form_state['commerce_option'][$field_name][$key]['option'] = $option;
      $form[$field_name][$key] = array(
        '#parents' => array(
          $field_name,
          $key,
        ),
      );
      field_attach_form('commerce_option', $option, $form[$field_name][$key], $form_state);
      $someFieldIsAdded = TRUE;
    }
  }

  // If we've modified the form to contain commerce options, add a submit
  // handler to save our values.
  if ($someFieldIsAdded) {
    $form['#submit'][] = 'commerce_option_add_to_cart_submit';
  }
}