You are here

function i18n_commerce_product_form_commerce_product_ui_product_form_alter in Internationalization for commerce product 7

Implements hook_form_FORM_ID_alter().

File

./i18n_commerce_product.forms.inc, line 11
Internationalization (i18n) module - Commerce product handling.

Code

function i18n_commerce_product_form_commerce_product_ui_product_form_alter(&$form, &$form_state) {
  global $language;

  // Pre-fill fields from translation source.
  $commerce_product = $form['#entity'];
  if (isset($_GET['target']) && isset($_GET['translation'])) {
    $commerce_product->language = $_GET['target'];
    if ($source_product = commerce_product_load($_GET['translation'])) {
      foreach (element_children($form) as $field_name) {
        if (!empty($source_product->{$field_name})) {
          if (!is_array($source_product->{$field_name})) {
            $form[$field_name]['#default_value'] = $source_product->{$field_name};
          }
          elseif (!empty($source_product->{$field_name}[LANGUAGE_NONE][0])) {
            foreach ($source_product->{$field_name}[LANGUAGE_NONE][0] as $key => $value) {
              if (isset($form[$field_name][LANGUAGE_NONE][0][$key])) {
                if ($key == 'amount') {
                  $value = number_format($value / 100, 2);
                }
                $form[$field_name][LANGUAGE_NONE][0][$key]['#default_value'] = $value;
              }
            }
          }
        }
      }
    }
  }

  // Make field language editable on commerce product form.
  if (!empty($form['language']) && $form['language']['#type'] != 'select') {
    $languages = language_list();
    foreach ($languages as $langcode => $lang) {
      if (!$lang->enabled) {
        unset($languages[$langcode]);
      }
      else {
        $languages[$langcode] = $lang->name;
      }
    }
    $form['language'] = array(
      '#type' => 'select',
      '#title' => t('Language'),
      '#options' => $languages,
      '#disabled' => !empty($commerce_product->language),
      '#weight' => 1,
      '#default_value' => !empty($commerce_product->language) ? $commerce_product->language : $language->language,
    );
  }
  $tproduct_id = isset($_GET['translation']) ? $_GET['translation'] : NULL;
  if (!empty($form['#entity']->tproduct_id)) {
    $tproduct_id = $form['#entity']->tproduct_id;
  }

  // Add tproduct_id field.
  $form['tproduct_id'] = array(
    '#type' => 'value',
    '#value' => $tproduct_id,
  );

  // Override validation handler.
  $pos = array_search('commerce_product_product_form_validate', $form['#validate']);
  if ($pos !== FALSE) {
    $form['#validate'][$pos] = 'i18n_commerce_product_product_form_validate';
  }

  // Override submit handler.
  $pos = array_search('commerce_product_product_form_submit', $form['actions']['submit']['#submit']);
  if ($pos !== FALSE) {
    $form['#validate'][$pos] = 'i18n_commerce_product_product_form_submit';
  }
}