Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Problem/Motivation
Currently the AddToCartForm::submitForm() calls parent::submitForm() which implies any class overriding the function should also call parent::submitForm(). When overriding with that assumption you end up in a situation where the commerce_cart submitForm() adds the product to the cart and then your new submitForm() adds the product to the cart resulting in duplicate product submission.
Current work around
My current workaround is to call the grandparent submitForm() directly in the new class which is a bit of php magic.
class CustomAddToCartForm extends AddToCartForm {
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
ContentEntityForm::submitForm($form, $form_state);
// Additional custom logic here.
$this->cartManager->addOrderItem($cart, $order_item, $form_state->get([
'settings',
'combine',
]));
}
}
Comments
Comment #2
bojanz CreditAttribution: bojanz at Centarro commentedWhat is your proposal for making submitForm() easier to extend?
Comment #3
bojanz CreditAttribution: bojanz at Centarro commentedWe now assign the return of $this->cartManager->addOrderItem to $this->entity, so the child method can check whether the item was already added to the cart.