0

In Drupal 9, I added a views_add_to_cart_form view mode to be able to render a product entity with only the Variations field formatted as add to cart form being displayed. That all works as expected, but I am trying to remove the quantity widget on the commerce add to cart form for that specific view display by using unset($form['quantity']);.

I am not sure if it is better to bring the view display information into a form_alter, or if it would be cleaner to get the form information in a hook_entity_view_display_alter.

I was trying something like this in the form alter, but felt like it was not at all the right way to go about it

$display = \Drupal::service('entity_display.repository')->getViewDisplay('commerce_product', 'simple_product', 'views_add_to_cart_form');
if (isset($display)) {
  unset($form['quantity']);
}

(I realize my if (isset($dsiplay)) { won't cut the mustard...)

It seems like it would be better to use hook_entity_view_display_alter and get the necessary $form stuff in there:

/**
 * Implements hook_entity_view_display_alter().
 */
function MY_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context) {
  if ($context['entity_type'] == 'commerce_product' && $context['view_mode'] == 'views_add_to_cart_form') {
    // Get access to the $form_id and unset($form['quantity']);
  }
}

So how do I get access to &$form, FormStateInterface &$form_state, $form_id stuff inside hook_entity_view_display_alter?

1 Answer 1

0

As a rule of thumb if the hook doesn't provide you the object you need, it means you are most likely at the appropriate place to execute your code.

Considering your question, I think you should be using hook_form_alter with $form_id === add_to_cart_form or something close to that. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.8.x)

Then you can do the unset there.

A better practice would be to give #access = FALSE instead of unsetting the element $form['quantity']['#access] = FALSE;

Your Answer

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

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