我想修改一个带有内容值的表单:我尝试使用“PRE_BIND”事件,但如果表单不是第一次发送,这将不起作用。我有这个 :
<?php
namespace YOU\CommercantBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LivraisonChoixType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event) use ($builder)
{
$form = $event->getForm();
$data = $event->getData();
if ((int)$data['pays'] > 0) {
$form->remove('livreur');
$pays = $data['pays'];
$form->add('livreur','entity',array(
'property' =>'name',
'class' => 'YOUAdminBundle:Livreur',
'label' => 'Livreur :',
'query_builder' => function($er) use ($pays){
return $er->createQueryBuilder('c')
->join('c.pays', 'p')
->andWhere('p.id= :pays')
->addOrderBy('c.name', 'ASC')
->setParameter('pays', $pays);
},
)
);
}
});
$builder
->add('pays','pays',array('label'=>'Destination :'))
->add('livreur','entity',array(
'property' =>'name',
'class' => 'YOUAdminBundle:Livreur',
'label' => 'Livreur :',
'query_builder' => function($er) {
return $er->createQueryBuilder('c')
->join('c.pays', 'p')
->andWhere('p.id= :pays')
->addOrderBy('c.name', 'ASC')
->setParameter('pays', 0);
},
)
)
->add('prix','number',array('required'=>true,'label' => 'Frais :'))
->add('prix2','number',array('required'=>false,'label' => 'Frais en second article :'))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'YOU\CommercantBundle\Entity\LivraisonChoix',
));
}
public function getName()
{
return 'you_commercantbundle_livraisonchoixtype';
}
}
由此表单类型调用:
<?php
namespace YOU\CommercantBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LivraisonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name','text',array('required'=>true,'label'=>'Nom :'))
->add('choix','collection',array(
'type'=>new LivraisonChoixType(),
'options'=>array('attr'=>array('class'=>'livreur-collection')),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'YOU\CommercantBundle\Entity\Livraison'
));
}
public function getName()
{
return 'you_commercantbundle_livraisontype';
}
}
有人知道我怎样才能获得价值吗?