1

I am searching a way to overwrite the NodeForm to get a class per bundle.

Actually EntityForm manages the form for all entities. NodeForm extends it and manages the forms for all nodes.

I wrote a CustomNodeForm replacing NodeForm behaviour for all nodes.

/**
 * Implements hook_entity_type_build().
 */
function ftvisi_main_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('default', CustomNodeForm::class);
}

Now I'd like to get a class per bundle extending that CustomNodeForm but I feel like I am not able to do it.

CustomNodeForm might instantiate a form for each bundle - but I don't like that approach and we still just have one constructor which can leads to problems such as:

"OK my first bundle form needs this service, and my second bundle form needs another one, should I inject the full container itself and then use services on the fly ?" => Pretty bad idea, I know.

Anyway, if CustomNodeForm instantiates other classes itself, it will be hard to mock and test. So I definitively don't like that approach.

I then thought about using the form modes, but same problem: a form mode can be used on any node type, so we still don't have a class per bundle and we still have only one constructor for all forms using that form mode.

Any idea to help?

1 Answer 1

0

AFAIK forms are tied to operations at entity-type level, so you don't have any hook to only alter the form for a particular bundle. Since what you want is to inject certain services for a given bundle what you can do is to implement a chain of responsability pattern through service collectors. This allows you to inject only the service collector to your form and delegate to the collection to evaluate which service should apply for your given bundle. And finally the resolved service is the one that would concentrate the responsability. I could provide you with a deep example but could take some time, let me know if a code sample still needed.

UPDATE

This will be the solution in a near future, since sub-classing is the feature you are referring.

2
  • The future you were refering to is available in drupal 9.3.0 :)
    – MacSim
    Dec 10, 2021 at 7:32
  • Yeah the future is now. On the past, this kind of architectural features took longer to get implemented. I saw the 9.3 release but haven't tried yet subclassing but I can assure you had this in wish-list for Santa :) so I'll be testing it soon.
    – d70rr3s
    Dec 11, 2021 at 17:04

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.