【发布时间】:2015-01-16 10:11:43
【问题描述】:
有没有办法在 PRE_SUBMIT eventListner 的表单中向集合字段添加元素?
我有这个(form1):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file',
'file',
array(
'data_class' => null,
'mapped' => false, //il campo non è mappato (il file non è blob ma sta su filesistem)
//'constraints' => new NotBlank(),
'render_required_asterisk' => true,
)
)
->add('name',
'text',
array(
'label' => 'Nome documento',
'required' => true,
'render_required_asterisk' => true,
'mapped' => 'name'
)
)
->add('document_category',
'entity',
array(
'property' => 'name', //valore da visualizzare nel form
'mapped' => 'document_category',
'class' => 'docliteBundle:Document\documentCategory', //Classe da dove deve prendere i dati
'multiple' => false, //E' possibile la selezione di un solo campo
'expanded' => false, //Per rendere un campo select
'empty_value' => 'Selezionare una categoria documento', //questo sarà impostato all'inizio ed identifica la voce vuoto
'label' => 'Categoria documento', //label del campo
'required' => true, //la selezione del campo è obbligatoria
'render_required_asterisk' => true, //visualizza asterisco di campo obbligatorio
)
)
->add('attributes_rel',
'collection',
array(
'type' => new documentAttributeRelType(),
'label' => false,
'mapped' => 'attributes_rel',
'allow_add' => true,
'show_legend' => false,
'allow_delete' => true,
)
);
documentAttributeRelType (form2):
$builder
->add('dynamic_attribute',
'entity',
array(
'property' => 'name',
'class' => 'docliteBundle:Document\dynamicAttribute',
'mapped' => 'dynamic_attribute',
'multiple' => false,
'expanded' => false,
'label' => 'Attributo',
'required' => true,
'constraints' => new NotBlank(),
)
)
->add('value',
'choice',
array(
'mapped' => 'value',
)
)
;
在Form1中定义了Listner:
$builder->get('attributes_rel')->addEventListener(
FormEvents::PRE_SUBMIT,
function(FormEvent $event){
$data = $event->getData();
$rel = array();
$rel['dynamic_attribute'] = '1';
array_push($data, $rel);
$event->setData($data);
});
但是这个添加元素没有被映射,也没有出现在视图中:
{% for attribute in form.attributes_rel %}
<div data-attribute_row>
{{ form_row(attribute.dynamic_attribute) }}
{{ form_row(attribute.value) }}
</div>
{% endfor %}
【问题讨论】:
-
是的,而且您似乎已经知道您需要 PRE_SUBMIT 事件,我猜您实际上遇到了更具体的问题?阅读symfony.com/doc/current/components/form/… 更实用的方法,请查看:symfony.com/doc/current/cookbook/form/… 如果您仍有问题,请在您的问题中更具体。
-
没错,表单有一个字段集合,由一个实体和一个值组成。 Pre_submit 事件将向该集合添加一个元素。正如您在下面的示例中看到的,如果您在数组中手动添加元素,则会发生: PRE_SUBMIT 事件正确添加了第三个元素 SUBMIT 事件未映射到第三个元素,因此我在表单中看不到它。我不知道我是否清楚。问我你是否有疑虑。感谢您有空。
-
我终于解决了!!!!!!要在 eventLister 中设置 fileld 集合,必须在 PRE_SUBMIT 中设置数据,但不能在实体中设置,直接在视图中使用: $builder->addEventListener( FormEvents::PRE_SUBMIT, function(FormEvent $event){ $d = $event->getData (); $d['attributes_rel'] = array( array('dynamic_attribute'=>2), array('dynamic_attribute'=>3), array('dynamic_attribute'=>1), ); $event->setData ($d); });