首页 > 解决方案 > Sonata Block Bundle 编辑表单不保存 EntityType

问题描述

这是我的街区,

当我保存标题存储购买文章为空时,错误在哪里?

class ArticleBlock extends AbstractAdminBlockService
{


    /**
     * {@inheritdoc}
     */
    public function configureSettings(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'article' => null,
            'title' => null,
            'template' => '@MeaArticleBundle/Sonata/Templates/article_block.html.twig',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
    {
        $formMapper->add('settings', ImmutableArrayType::class, [
            'keys' => [
                ['article', EntityType::class , [
                    'class' => Article::class,
                    'required' => true,
                    'property' => 'title',
                    'label' => 'Article',
                ]],
                ['title', TextType::class, [
                    'label' => 'form.label_title',
                    'required' => false,
                ]],
            ],
            'translation_domain' => 'SonataBlockBundle',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
    {
        //var_dump($block);

        $errorElement
            ->with('article[article]')
            ->assertNotNull([])
            ->assertNotBlank()
            ->end()
            ->with('title[title]')
            ->assertNotNull([])
            ->assertNotBlank()
//            ->assertLength(['max' => 50])
            ->end();
    }

    /**
     * {@inheritdoc}
     */
    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        // merge settings
        $settings = $blockContext->getSettings();

        var_dump([$blockContext,$settings]);

我保存后得到

 "use_cache" => true
    "extra_cache_keys" => array:2 [▶]
    "attr" => []
    "template" => "@MeaArticleBundle/Sonata/Templates/article_block.html.twig"
    "ttl" => 86400
    "manager" => "snapshot"
    "page_id" => 1
    "article" => []
    "title" => "test2"
  ]

标签: sonata-adminsonata

解决方案


我创建了一个将所选实体的 id 映射到数组的方法:

    private function mapTestimonialsToIds(array $testimonials): array
    {
        $ids = [];
        /** @var Testimonial $testimonial */
        foreach ($testimonials as $testimonial) {
            $ids[] = $testimonial->getId();
        }

        return $ids;
    }

我在 prePersists 和 preUpdate 方法中都调用了这个方法,并在这种情况下将它设置为我的块推荐设置作为值。

然后,在执行方法上,我使用保存的 id 获取所有实体,并将这些找到的实体返回到我的模板。

    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        return $this->renderResponse($blockContext->getTemplate(), [
            'testimonials' => $this->testimonialRepository->findByIds($blockContext->getSetting('testimonials')),
            'block' => $blockContext->getBlock(),
        ], $response);
    }

推荐阅读