Tags/topics: 
1
Answers
Vote up!
0
Vote down!

How should I disabled the Add to Cart button?

$form['submit']['#attributes']['disabled'] or $form['submit']['#disabled']?

If the product is enabled I've got $form['submit']['#disabled'] => FALSE with no $form['submit']['#attributes'].
If the product is disabled I see $form['submit']['#attributes']['disabled'] => "disabled" with no $form['submit']['#disabled'].

Asked by: ponies
on January 31, 2013

1 Answer

Vote up!
1
Vote down!

What you're seeing in the #attributes array directly corresponds to what will appear in the HTML of the button once rendered, but by default for disabled buttons that's being populated through the use of the #disabled property. The #disabled property is the normal way to prevent a button click via the Forms API, but that wouldn't prevent someone from fiddling with the HTML of the page and using it to submit a form anyways.

Accordingly, for the Add to Cart button, we set the disabled attribute in the #attributes array directly and add a validate handler when we want Add to Cart disabled. This means even if the customer figures out how to submit the form, it will still prevent the Add to Cart from happening:

See this code for disabled products in our Add to Cart form builder function:

<?php
$form
['submit'] = array(
 
'#type' => 'submit',
 
'#value' => t('Product not available'),
 
'#weight' => 50,
 
// Do not set #disabled in order not to prevent submission.
 
'#attributes' => array('disabled' => 'disabled'),
 
'#validate' => array('commerce_cart_add_to_cart_form_disabled_validate'),
);
?>
Ryan Szrama
Answer by: Ryan Szrama
Posted: Jan 31, 2013