好的。您需要做的是监听 preSubmit 表单事件,然后通过将提交的值添加到您的选择元素来基本接受提交的值。
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-submitted-data
==================================================== =====
我没有查看您的粘贴箱,但这是一个似乎对我有用的示例。这是一个简单的性别选择列表,我在其中添加了另一个选项客户端。preSubmit 监听器只是简单地将默认的性别选择选项替换为包含已提交内容的选项。您应该能够添加数据转换的东西并且一切顺利。
namespace Cerad\Bundle\TournBundle\Form\Type\Test;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class DynamicFormType extends AbstractType
{
public function getName() { return 'cerad_tourn_test_dynamic'; }
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('gender', 'choice', array(
'choices' => array('m' => 'Male', 'f' => 'Female'),
'required' => false,
));
$builder->addEventSubscriber(new DynamicFormListener($builder->getFormFactory()));
}
}
class DynamicFormListener implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_SUBMIT => 'preSubmit',
FormEvents::PRE_SET_DATA => 'preSetData',
);
}
public function preSetData(FormEvent $event)
{
// Don't need
return;
}
public function preSubmit(FormEvent $event)
{
$data = $event->getData();
$gender = $data['gender'];
if (!$gender) return; // If nothing was actually chosen
$form = $event->getForm();
/* =================================================
* All we need to do is to replace the choice with one containing the $gender value
* Once this is done $form->isValid() will pass
*
* I did attempt to just add the option to the existing gender choice
* but could not see how to do it.
* $genderForm = form->get('gender'); // Returns a Form object
* $genderForm->addNewOptionToChoicesList ???
*
* Might want to look up 'whatever' but that only comes into play
* if the form fails validation and you paas it back to the user
* You could also use client side javascript to replace 'whatever' with the correct value
*/
$form->add($this->factory->createNamed('gender','choice', null, array(
'choices' => array($gender => 'whatever'),
'required' => false,
'auto_initialize' => false,
)));
return;
}
}