Symfony2 change Form data_class from events

I have 3 objects with discriminator,

Product, ProductOneandProductTwo

they have only one form ProductType, because they share most of their properties, data_classassigned Appbundle\Entity\Product, but I want to change to a POST_SUBMITrelated entity, because depending on one property, an object can be ProductOneeither ProductTwo.

I cannot extend the types of forms, and I do not want to create n types of forms, only one with events, I do not think it is possible, but I would like to.

I know that I can change properties, etc., but not related to FormData, in this case, since I said that it is an instance Product, and it should be ProductOneeitherProductTwo

$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
    $data = $event->getData(); // This form is Product
    $form = $event->getForm();

    if(strpos(strtolower($data->getCategory()->getName()), 'foo')) {
        // Here it must be ProductOne
    } elseif(strpos(strtolower($data->getCategory()->getName()), 'bar')) {
        // Here it must be ProductTwo
    } else {
        // ...
    }
});
+4

Source: https://habr.com/ru/post/1620102/


All Articles