sonata-admin - 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"
]
解决方案
我创建了一个将所选实体的 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);
}
推荐阅读
- c++ - 在 Windows 上,是否可以在不使用 PATH 环境变量的情况下让 dll 在另一个文件夹中查找依赖项?
- java - 哪些 java 集合接受添加空值?
- javascript - 使用这种 JavaScript 代码有什么缺点吗?
- javascript - 我不能在 Javascript 上使用 API,可能与 node.js 等有关
- azure - 如何将参数从 Azure 自动化 Runbook 传递到 Azure Datafactory 管道
- javascript - JavaScript 获取路径中的可用文件
- html - 子元素拒绝继承 Firefox 中的背景动画
- javascript - Electron defaultConfig 没有“app”参数
- c++ - if数组上的随机数
- javascript - 如何使用 rxjs 为集合加载附加数据