【发布时间】:2013-03-14 18:09:21
【问题描述】:
我最近一直在尝试使用 Symfony 2 表单,这对于简单的表单非常有用。
但是 - 用于选择框或类似的东西 - 我经常需要表单中的关联实体列表。在几篇博文和 Symfony 文档中,他们提出了类似的建议……
//BlogPostType implements FormTypeInterface
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', null, array(
'property' => 'name',
'query_builder' => function(EntityRepository $er) use($options) {
return $er->createQueryBuilder('category')->orderBy('category.name', 'ASC');
}
);
}
由于我非常关注域驱动设计,尤其是关注点分离,我发现很难相信在 Symfony 中将关联实体绑定到自定义表单类型的唯一选择是通过查询它在自定义表单类型中。
在我看来,这违反了 SoC,因为不应查询表单。 这样,表单总是采用相同的实体,但不是表单应该选择显示哪些实体...
要求表单构建器构建表单的控制器应该将关联的对象注入到自定义表单类型构造函数中......
//BlogPostType implements FormTypeInterface
public function __construct(array $categories) {
$this->categories = $categories;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', null, array(
'property' => 'name',
'choices' => $this->categories
);
}
有人知道如何实现吗?
【问题讨论】:
标签: php oop symfony domain-driven-design modular-design