3

I have created a new form mode (in the UI at admin/structure/display-modes) for a custom entity (form mode is entitled apply) and added apply to the form handler classes in the entity class.

The form is built and returned in a Controller, and specifies the form mode.

$form = $this->entityFormBuilder()->getForm($entity, 'apply');

Now I would like to be able to determine from a hook_form_alter whether this form is being displayed using the apply form mode, but I cannot work out how that is available from $form or $form_state.

2 Answers 2

6

You can try EntityFormInterface::getOperation:

function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state) {
  // only continue if this is for form mode "apply"
  if ($form_state->getFormObject()->getOperation() !== 'apply') {
    return;
  }

  // do stuff

}
4

The accepted answer doesn't check form mode, but it checks the operation instead. To validate on form mode, you can use something like this:

function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\Core\Entity\Entity\EntityFormDisplay $formDisplay */
  $formDisplay = $form_state->getStorage()['form_display'];
  
  // Only continue if this is for form mode "apply".
  if ($formDisplay->getMode() !== 'apply') {
    return;
  }

  // do stuff

}
1
  • The second parameter of getForm($entity, 'apply') specifies the operation. For entity forms operation and form mode are identical. This is defined in the entity class as form handler, as explained at the beginning of the question.
    – 4uk4
    Commented Mar 24, 2022 at 16:57

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.