[英]Symfony2 Data transformer on a Choice field type
我將逐步介紹如何使用數據轉換器
問題是,如果要使用“選擇”類型執行該操作怎么辦? 我使用jQuery動態填充了哪些?
我測試了他們提供的示例(沒有創建自定義類型。),它可以與文本字段類型100%兼容,但是一旦我將其更改為choice並給其空的選擇,它就無法使用,是否必須頁面加載后,我用jQuery填充選項嗎?
例
模型 [使用加載了查詢構建器和實體字段類型的模型實體進行選擇...]
Number [起初為空,當模型更改時,我向該模型的AJAX請求]
如果我將Number保留為文本字段,並且手動輸入一個有效的數字(查看數據庫),它將起作用,但是如果我將其留給jQuery和Choice類型,則它將返回一個帶有模型無效值的格式錯誤。
在這兩種情況下,我都要在處理表單之前執行print_r($ request-> request),並且在兩種情況下,它都會提交Number => 1(在此示例中是正確的),但是當它的類型為Choice時,某種程度上它不會轉換數據,但是當它的文本。
這是jQuery如何為Number選擇框填充數據的方式:
<option value=”1”>1234ABCDEFG</option>
順便說一句,我正在使用ID進行轉換,該ID將是所選選項的值。
好。 您需要做的是監聽preSubmit表單事件,然后通過將提交的值添加到choice元素中來基本上接受提交的值。
================================================== =====
我沒有看您的粘貼容器,但以下示例似乎對我有用。 這是一個簡單的性別選擇列表,我在其中添加了另一個選項客戶端。 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.