Score:0

How to get access to a $form in hook_entity_view_display_alter?

cn flag

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?

Score:0
in flag

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;

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.