Форма редактирования блока 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"
  ]

person Developer    schedule 04.08.2018    source источник


Ответы (1)


Я создал метод, который сопоставляет идентификаторы выбранных объектов с массивом:

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

        return $ids;
    }

и я вызываю этот метод как в методах prePersists, так и в методах preUpdate и устанавливаю его в качестве значения в моем блоке отзывов в этом случае.

Затем в методе выполнения я извлекаю все объекты, используя сохраненные идентификаторы, и возвращаю эти найденные объекты в свой шаблон.

    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        return $this->renderResponse($blockContext->getTemplate(), [
            'testimonials' => $this->testimonialRepository->findByIds($blockContext->getSetting('testimonials')),
            'block' => $blockContext->getBlock(),
        ], $response);
    }
person rubenj    schedule 25.06.2019
comment
Я вызываю этот метод как в prePersists, так и в preUpdate для класса ArticleBlock extends AbstractAdminBlockService ? - person Developer; 01.04.2021
comment
Да, в самом деле! Здесь все данные собираются и помещаются в ключ настроек отзыва. - person rubenj; 06.04.2021