1

want to change a few things with the hook they provide. The form id is commerce-cart-add-to-cart-form-626 and the submission button ID is edit-submit.

I created a module (jch_test) which contains the following code.

function jch_test_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $line_item = $form_state['line_item'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE]  [0]['product_id']);
  if ($product->type == 'product') {
    $form['submit']['#value'] = t('Test');
  }
}

The module loads, but the hook isn't invoked. What am I doing wrong?

3
  • try this: function jch_test_form_alter($form, $form_state, $form_id){ drupal_set_message($form_id); } and now you will see the correct form ID as a drupal message so you can continue with the form. My best guessing is that your form ID in hook_form_FORM_ID_alter() is wrong.
    – AKS
    Commented Sep 25, 2012 at 22:39
  • code looks correct to me. Don't forget to clear your cache.
    – nmc
    Commented Sep 25, 2012 at 23:40
  • 3
    Also worth noting is $form_state['default_product'] holds the product currently selected on the Add to Cart form. Commented Jun 28, 2013 at 20:23

2 Answers 2

2

Try something like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}

You can use the $form_id and/or $current_product to make custom alterations for a specific product(s) and/or product type(s).

Flush Drupal's caches so your custom form alteration hook will be recognized.

Note, I'd also like to point out that once a user changes a value on the add to cart form, and the form is reloaded via AJAX, MY_MODULE_form_commerce_cart_add_to_cart_form_alter() will be called again, which is good.

However, it appears the $form_state['default_product']->language value may only be present the first time the page is loaded. Once the form is reloaded via AJAX, the language value may be empty in this hook, so watch out if your code is depending on it being there!

0

You can try

$form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value'] = t('Test');

Not the answer you're looking for? Browse other questions tagged or ask your own question.