奏鸣曲块捆绑编辑表格不保存EntityType

时间:2018-08-04 11:38:58

标签: sonata-admin sonata

这是我的街区

当我保存-存储标题时,购买商品为空,错误在哪里?

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"
  ]

1 个答案:

答案 0 :(得分:0)

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

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

        return $ids;
    }

然后在prePersists和preUpdate方法中都调用此方法,并在这种情况下将此值设置为我的模块推荐设置。

然后,在execute方法上,我使用保存的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);
    }