Home > other >  Dynamic form modification for CollectionField in EasyAdmin
Dynamic form modification for CollectionField in EasyAdmin

Time:02-10

Purpose

I want to create a simple CMS based on EasyAdmin 4, where a user can build articles made of different content types, f.e. wysiwygs, galleries, quotations and others. It kind of works, but lacks a dynamic (ajax) approach for it.

Current code

I am building my FormType using this approach. For simplicity, there are just 2 types of content - wysiwyg and horizontal line.

In CRUD controller, there is this:

public function configureFields(string $pageName): iterable
{
    return [
        TextField::new('title'),
        CollectionField::new('content')
            ->setEntryType(ArticleContentType::class),
    ];
}

And in ArticleContentType, there is this:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('type', ChoiceType::class, [
            'choices' => [
                'WYSIWYG Editor' => 'wysiwyg',
                'Horizontal line' => 'horizontal_line',
            ],
        ])
    ;

    $formModifier = function (FormInterface $form, $data = null) {
        if (is_array($data) && $data['type'] === 'wysiwyg') {
            $form->add('wysiwyg', TextareaType::class);
        }
    };

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($formModifier) {
            $data = $event->getData();
            $formModifier($event->getForm(), $data);
        }
    );

    $builder->get('type')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifier) {
            $type = $event->getForm()->getData();
            $formModifier($event->getForm()->getParent(), $type);
        }
    );
}

The problem

Solution above works, but only after saving an article (it shows wysiwyg when I select a WYSIWYG Editor option). Now I need to use some JavaScript to add the wysiwyg without saving/refreshing the article. I tried (as in the mentioned documentation) something like this:

fetch(document.getElementById('new-Article-form').action, {
  method: "POST",
  body: new FormData(document.getElementById('new-Article-form')),
}).then((r) => r.text())

but it fails in EasyAdmins's AbstractCrudController (Undefined array key "ea").

Is there anyone who managed to do this? Can somebody point me in the right direction?

Thank you.

CodePudding user response:

  •  Tags:  
  • Related