I'm in the need for a extra validation on an existing drupal commerce form (commerce_cart_add_to_cart_form_##), strangely the validation function is not called on the first form submit, but on the 2nd submit and all the submits after the 2nd. There are multiple commerce_cart_add_to_cart_forms on a single page.

Here's my module code:

function val_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'commerce_cart_add_to_cart_form_') !== false) {
        $form['#validate'][] = 'val_commerce_cart_add_to_cart_form_validate';

function val_commerce_cart_add_to_cart_form_validate($form, &$form_state) {
    dpm('validating function called');
    form_set_error('quantity', t("ERROR"));

Any Ideas? And, as a second question: there are different $from_ids (commerce_cart_add_to_cart_form_##) that will all need the same validation. Is there a way to call them all other than I did?



I added your code to a quick dummy function, tested it, and the it seems to be working fine. I created a dummy item, added it to my cart, and the that produced a print out like:

enter image description here

I also added a watchdog() call to the validate function and that confirmed the validation was being called when it should be. I'm not sure if maybe you have something else interfering with your form alter or possibly your dpm is printing out late (I know it can happen with themes, not sure with modules), but you might want to try using watch dog to see if the validation form isn't being called when it should.

|improve this answer|||||
  • Can the reason be that there are more than one add to cart form on the page? – marcmueller Apr 20 '15 at 18:58
  • I doubt it, but does the validation form get called the first time if you try hitting it from a page with just one add to cart form on it (like on a node?) – Jance Apr 20 '15 at 19:05
  • sorry, could have done that before.. just tested and still the same problem. I think at least the form_set_error must be shown even if the dpm is printed late? whats happening is: first submit doesn't add the product to cart, no error. second submit: error +dpm shown, no product added. maybe a problem with form_set_error? – marcmueller Apr 20 '15 at 19:29
  • some more info: i'm rendering the add_to_cart forms on a node.tpl.php and using a custom module to validate those forms. Here: drupal.stackexchange.com/questions/18690/… i read that this can cause problems. – marcmueller Apr 20 '15 at 19:35
  • Are you calling drupal_get_form() from your template? – Jance Apr 20 '15 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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