【问题标题】:Dynamic form modification for CollectionField in EasyAdminEasyAdmin中CollectionField的动态表单修改
【发布时间】:2022-09-30 00:00:06
【问题描述】:

目的

我想创建一个基于 EasyAdmin 4 的简单 CMS,用户可以在其中构建由不同内容类型组成的文章,例如所见即所得,画廊,报价和其他。它有点工作,但缺乏动态(ajax)方法。

当前代码

我正在使用 this approach 构建我的 FormType。为简单起见,只有两种类型的内容——所见即所得和水平线。

在 CRUD 控制器中,有这样的:

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

在 ArticleContentType 中,有这样的:

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);
        }
    );
}

问题

上述解决方案有效,但仅在保存文章后(当我选择 WYSIWYG 编辑器选项时,它显示所见即所得)。现在我需要使用一些 JavaScript 来添加所见即所得,而无需保存/刷新文章。我试过(如在提到的文档中)这样的事情:

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

但它在 EasyAdmins\'s AbstractCrudController (未定义的数组键 \"ea\") 中失败。

有没有人设法做到这一点?有人可以指出我正确的方向吗?

谢谢你。

    标签: javascript php symfony symfony-forms easyadmin


    【解决方案1】:

    已经很久了,也许这个答案不再相关,但我还是把它留在这里。

    你使用了错误的事件POST_SUBMIT

    预提交需要

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多