D
D
Dima2018-06-11 13:26:52
symfony
Dima, 2018-06-11 13:26:52

How to get data after merging forms?

I describe my UploadImageType, which complements the form and, if the option allow_delete = true is set, adds a checkbox to the form to delete the file. As a result, when merging forms, I can’t get data from the fields where name is in this form s5b1e4d8c1d68b[file][file]

<input type="file" id="s5b1e4d8c1d68b_file_file" name="s5b1e4d8c1d68b[file][file]" accept="image/png,image/jpeg,image/jpg">
<input type="checkbox" id="s5b1e4d8c1d68b_file_isDelete" name="s5b1e4d8c1d68b[file][isDelete]" value="1">

// AuthorAdmin.php
protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('share.form_group.basic', ['class' => 'col-md-8', 'name' => false])
                ->add('file', UploadImageType::class, [
                    'label'             => 'author.fields.photo',
                    'mime_types'        => ['image/png', 'image/jpeg', 'image/jpg'],
                    'image_web_path'    => $this->getSubject()->getPhoto(),
                ])
        ;
    }

//UploadImageType.php
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file', FileType::class, [
            'required' => $options['required'],
            'label' => false,
            'attr' => $options['attr'],
            'property_path' => 'file',
        ]);

        if ($options['allow_delete']) {
            $this->buildDeleteField($builder, $options);
        };
    }

protected function buildDeleteField(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
            $form = $event->getForm();
            $object = $form->getParent()->getData();

            if (null === $object) {
                return;
            }

            $form->add('isDelete', CheckboxType::class, [
                'label' => $options['delete_label'] ?? 'admin.fields.file_is_delete',
                'mapped' => false,
                'required' => $options['required'],
            ]);
        });

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $form = $event->getForm();
            $object = $form->getParent()->getData();
            
            $delete = $form->has('isDelete') ? $form->get('isDelete')->getData() : false;
            if (!$delete) {
                return;
            }

            //delete file
        });
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question