M
M
Maxim Lagoysky2019-07-16 10:03:21
symfony
Maxim Lagoysky, 2019-07-16 10:03:21

How to dynamically add a field to a form?

Good afternoon everyone, there is such a problem, there is a select on the form, I hang the PRE_SUBMIT event on it, when I select something in the select, an adjax request is sent, the PRE_SUBMIT event fires and, depending on the selection in the select, I add a field to the page, until that moment everything is fine, but if I try to save the forms, then it will start swearing that an extra field has appeared in the form and they say that it is necessary to set a setting to allow them, in fact, the question is, is it possible to do something so that the form understands that dynamic fields have been added (they have the mapped = setting false) and therefore they are simply in the children property. Plus, I have such a moment that these fields can be initially on the page and in this situation they end up in children, and if they are added dynamically, they fly to extra_data, which I don’t really like.
The code is as conditional as possible, but with the preservation of the main points.

Main form

$builder->add('addNewRowFields', ChoiceType::class, array(
            'multiple' => false,
            'expanded' => false,
            'choices' => array(
                'Select' => false,
                'Значени1' => '1',
                'Значени2' => '2',
                'Значени3' => '3',
                'Значени4' => '4'
            ),
            'mapped' => false,
        ));

$builder->get('addNewRowFields')->addEventSubscriber(new AddRowFields());


Event subscriber

public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SUBMIT => 'addFields');
    }

    public function addFields(FormEvent $event)
    {
        //тут условие на то что пришло из selecta
        $form = $event->getForm();
        $form->getParent()->add('lead', InvoiceLead::class, array(
                    'label' => false,
                    'mapped' => false,
                ));
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2019-07-16
@prototype_denis

Fields must be added before the data is mapped, not before the form is submitted.
Replace event with PRE_SET_DATA

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question