使用的RadioType
列表不是很容易的,這就是爲什麼每個人都建議你使用ChoiceType
其動態創建取決於選擇的數據陣列中的電臺列表。
當您創建FormTypeInterface
時,它必須以全局形式表示(通常)一個字段或一個子表單,因此每個字段名稱必須是唯一的以映射到相應的數據。
的buildForm
方法允許添加一些子領域中,你FormType
,在你的情況下,現場舉行了2個個子場的單選按鈕,每個人都有一個特定的名字,這是默認意圖,但要始終牢記全局數組數據,你想處理。
這裏是你的榜樣:
class MyCustomFormType extends \Symfony\Component\Form\AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('friend', RadioType::class, array(
'label' => 'Friend',
'required' => false
))
->add('guide', RadioType::class, array(
'label' => 'Guide',
'required' => false
));
}
public function getBlockPrefix
{
return 'my_custom';
}
// ...
}
所以這種形式的類型的數據應該是這樣的:
$myCustomFormData = array(
'friend' => $friendData,
'guide' => $guideData,
);
和嵌套在一個全球性的形式,這將是:
$formData = array(
'my_custom' => $myCustomFormData,
);
但你可以根據需要命名該字段:
// In a controller extending \Symfony\Bundle\FrameworkBundle\Controller\Controller
$form = $this->createFormBuilder()
->add('custom_field', MyCustomFormType::class)
->getForm();
// Then
$form->setData(array('custom_field' => $myCustomFormData));
注意,目前,因爲你映射「朋友」和「指南」數據RadioType
他們應該持有一個布爾值:
$myCustomFormData = array(
'friend' => true, // checked
'guide' => false, // unchecked
);
但你會如何取消選擇的值呢?
你應該有一個佔位符,要做到這一點,並處理它,而提交...
此外,更改名稱可以使用您的類型類的finishView
方法,它的FormView
(內置視圖來完成你的類型),表單本身和選項參數:
public function finishView(FormView $view, FormInterface $form, array $options)
{
$childName = $view->vars['full_name']; // "my_custom" by default
foreach ($view as $childView) {
$childView->vars['full_name'] = $childName;
}
}
但你還需要增加一個DataMapperInterface
找回提交值表單類型本身,而不是。
要做到這一點,您需要知道表單組件的工作原理,這並不容易。
簡單的方法
所以我跟其他的答案同意,你應該使用ChoiceType
把它弄出來的最箱。
我假設你的自定義窗體類型是如何選擇或者是「朋友」或「引導」,所以它看起來是這樣的:
$builder
->add('fellow', ChoiceType::class, array(
'choices' => array(
'I have a friend' => 'friend',
'I\'d like a guide' => 'guide',
),
'expanded' => true, // use a radio list instead of a select input
// ...
看一看the official docs
那麼你的數據看起來像:
$form->add('custom_field', MyCustomFormType::class);
$form->setData(array(
'custom_field' => 'friend',
));
當呈現「朋友」的選擇將被選中,你將能夠改變它爲「指導」。
爲choices
選項選擇數組需要標籤作爲鍵和選擇值值:
<div id="form_custom_field">
<input type="radio" name="form[custom_field]" value="friend" checked="checked">
<label>I have a friend</label>
<input type="radio" name="form[custom_field]" value="guide">
<label>I'd like a guide</label>
...
使用的選擇,擴大了真,多假。 ChoiceType :: class –
然後RadioType有什麼意義? –