如何在Symfony2表单类型的集合内动态添加集合 [英] How to dynamically add's collections within collections in Symfony2 form types
问题描述
我在symfony2中有3种表单类型
I have 3 form types in symfony2
FaultType,它是所有下一个集合的父级
FaultType which is the parent of all next collections
<?php
namespace My\FaultBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class FaultType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('title')
->add('steps', 'collection', array(
'type' => new StepType(),
'allow_add' => true,
'prototype' => true,
'by_reference' => false,
))
->add('created')
->add('updated')
;
}
public function getDefaultOptions()
{
return array(
'data_class' => 'My\FaultBundle\Entity\Fault'
);
}
public function getName()
{
return 'my_fault_fault';
}
}
StepType:
<?php
namespace My\FaultBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class StepType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('body')
->add('photos', 'collection', array(
'type' => new PhotoType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
))
;
}
public function getDefaultOptions()
{
return array(
'data_class' => 'My\FaultBundle\Entity\Step'
);
}
public function getName()
{
return 'my_fault_step';
}
}
和最后一个PhotoType:
and the last PhotoType:
<?php
namespace My\FaultBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class PhotoType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('filename')
;
}
public function getDefaultOptions()
{
return array(
'data_class' => 'My\FaultBundle\Entity\Photo'
);
}
public function getName()
{
return 'my_fault_photo';
}
}
I found excelent article link about prototype, and with one nested form type is very good, but I have a problem when a want to get this to work with third nest mean PhotoType... Photos are in collection of Steps, which is collection of Fault..., how can I achive dynamically add/remove photos for steps with this example...?
推荐答案
我制作了一个JS代码段,可以在此处提供帮助.您只需要添加两个按钮[添加新内容,最后删除]. https://gist.github.com/juanmf/10483041
I made a JS snippet that can be of help here. you just have to add two buttons [add new, delete last]. https://gist.github.com/juanmf/10483041
它可以处理递归/嵌套的原型.它与中介程序(与Symfony事件分派器相同)结合在一起,使您可以将生成的控件绑定到事件.如果您不需要调解员,请删除以下几行:
it can handle recursive/nested prototypes. It's coupled with a mediator (same as Symfony event Dispatcher) that allows you to bind generated controls to events. If you dont need the mediator delete these lines:
docdigital.mediatorInstance.send(
docdigital.constants.mediator.messages.clonePrototype_prototypeAdded,
$clone
);
这篇关于如何在Symfony2表单类型的集合内动态添加集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!