我正在为过滤后的实体集合显示一个 html 表,我想在每一行中显示一个复选框,作为表单的一部分,将选定的实体添加到 session 变量中。
我在想每个复选框都应该有实体 id 作为它的值,我将从表单字段数据中获取一个 id 数组(好吧,所以该值应该是对实体的间接引用,但为了简单)。
我尝试使用单个实体类型字段创建表单类型,映射到实体的 id 属性并嵌入到另一个具有集合类型字段的表单类型中。
class FooEntitySelectByIdentityType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('foo_id', 'entity', array(
'required' => false,
'class' => 'MeMyBundle:FooEntity',
'property' => 'id',
'multiple' => true,
'expanded' => true
));
}
# ...
和
class FooEntitySelectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('identity', 'collection', array(
'type' => new FooEntitySelectByIdentityType,
'options' => array(
'required' => false,
'multiple' => true,
'expanded' => true,
'attr' => array('class' => 'foo')
),
));
}
# ...
并且在 Controller 中,使用实体集合作为初始数据创建表单
$form = $this
->createForm(
new \Me\MyBundle\Form\Type\FooEntitySelectionType,
$collection_of_foo
)
->createView()
;
呈现表单时,身份字段只有一个标签,但没有小部件。
甚至可以以这种特殊方式使用实体和集合类型字段吗?
如果是这样,我可能做错了什么?
最佳答案
我想这会回答你的问题。
忘记 FooEntitySelectionType
.添加 property_path
字段选项到 FooEntitySelectByIdentityType
并设置 data_class
选项 null
:
class FooEntitySelectByIdentityType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('foo_id', 'entity', array(
'required' => false,
'class' => 'MeMyBundle:FooEntity',
'property' => 'id',
'property_path' => '[id]', # in square brackets!
'multiple' => true,
'expanded' => true
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
'csrf_protection' => false
));
}
# ...
并在您的 Controller 中,构建
FooEntitySelectByIdentityType
:$form = $this
->createForm(
new \Me\MyBundle\Form\Type\FooEntitySelectByIdentityType,
$collection_of_foo
)
->createView()
;
然后在接收 POSTed 数据的 Controller 操作中:
$form = $this
->createForm(new \Me\MyBundle\Form\Type\FooEntitySelectByIdentityType)
;
$form->bind($request);
if ($form->isValid()) {
$data = $form->getData();
$ids = array();
foreach ($data['foo_id'] as $entity) {
$ids[] = $entity->getId();
}
$request->getSession()->set('admin/foo_list/batch', $ids);
}
最后,在你的 Twig 模板中:
{# ... #}
{% for entity in foo_entity_collection %}
{# ... #}
{{ form_widget(form.foo_id[entity.id]) }}
{# ... #}
关于symfony - 为学说集合中的每个实体构建一个具有复选框的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638794/