2

How can add-to-cart form be customized using hook_form_alter. Or better yet can layouts like display suite or panels be applied to the add to cart form using hook_form_alter? I have custom line item types that I would like to show using some kind add_to_cart form regions in 2 or 3 stacked columns.

2
  • If you're wanting to change the presentation, then this is why you use product display nodes, to give you that flexibility.
    – nvahalik
    Nov 9, 2015 at 21:08
  • product display nodes cannot fields in add to cart form, it can access the whole add to cart form. This makes for a very messy UI as add to cart form can have multiple fields that are not organized in layouts Nov 9, 2015 at 22:08

2 Answers 2

1

You can use this snippet to customize the add to cart form:

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // Your form modifications go here.
  }
}

The $form_id changes based on the product that is in it, so you have to check for the string at the beginning of the $form_id variable.

You can theme it and/or change markup in the form like you would a regular form.

4
  • Thank you for this, I did find this, but beyond this is where I am having a tough time. For example how do i get a 2 column stacked layout in this or how to integrate layouts from Display Suite or Panels? Nov 10, 2015 at 1:51
  • This goes beyond the type of help you'll be able to get on Drupal SE. You'll need to use the classes and other elements your theme provides to you accomplish this.
    – nvahalik
    Nov 10, 2015 at 2:37
  • @nvahalik Your snippet is great, but where/how do you implement this code? Is there a link to a site to explain how to implement Kickstart v2 hooks? For example, where do you put the hook to only fire when the add-to-cart form is used? Do you put the hook in another event hook? Then where do you put the code for the even hook? Jul 27, 2016 at 15:07
  • @RobertAchmann You'd implement it in your module. Take a look at this: drupal.org/node/1419390
    – nvahalik
    Jul 27, 2016 at 15:28
0

For future reference better solution is there:

function wallsociety_form_commerce_order_item_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
 if ($form_state->getBuildInfo()['callback_object'] instanceof \Drupal\commerce_cart\Form\AddToCartFormInterface) {
   dsm($form);
 }
}

I chaged to hook commerce_order_item_add_to_cart as mentioned not working. People find this answear when searching for Drupal 9/10/11 Source: https://www.drupal.org/project/commerce/issues/2933154#comment-13885788

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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