3

I want to use a different form altogether from the defined edit form for a given bundle of an entity. I have found how to swap the form for every bundle of the entity here:

Override entity form handler

However I cannot figure out how to do this on a per-bundle basis. Does anyone have a method?

7
  • 1
    I remember looking for the same thing a while back and coming up empty. Looking at the code now (even in D11) there doesn't seem to be any hints that the entity form could be configurable per-bundle. You might have to make do with overriding the form class completely, and using the buildForm method to dispatch to other classes based on the bundle of the form object
    – Clive
    Commented Nov 29 at 21:51
  • Thanks Clive, I've been working at exactly that, but not finding nice solutions. I can get the form to load, but trying to use any submit handlers causes core form errors. I'll keep plugging away!
    – Jaypan
    Commented Nov 29 at 23:40
  • I was overthinking it. It was actually quite simple.
    – Jaypan
    Commented Nov 30 at 16:15
  • Isn't that always the way :) It would still be nice to have proper support for this, feels like it wouldn't take much to implement. A feature request may be brewing...
    – Clive
    Commented Dec 1 at 16:33
  • 1
    drupal.org/project/drupal/issues/3491100
    – Jaypan
    Commented Dec 2 at 16:41

1 Answer 1

3

I've found a solution, and it was surprisingly simple. The answer was to swap out the entire form in a hook form alter implementation.

/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id = [BUNDLE FORM ID]) {
    $form_entity = $form_state->getFormObject()->getEntity();
    $form = \Drupal::formBuilder()->getForm(FormClassToUseInstead::class, $form_entity);
  }
}

This works with ajax, and my form values are saving correctly.

-- Edit --

I'll note, this isn't ideal, as the original form is built before being swapped out. Ideally, core will provide a method of overriding the form by bundle. I have opened a feature request here:

https://www.drupal.org/project/drupal/issues/3491100

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.