我有一个应用程序,裁判可以在其中注册不同的比赛。对于每场比赛,我都需要提出不同的问题。所以我将问题移到了一个 yaml 文件中,并添加了足够的信息,以便我可以动态地创建表单元素。所以基本上我会:
# tourn.yml
tourns:
opencup:
desc: "USSF Open Cup 2013 - Decatur, Alabama - April 12, 13, 14"
plan:
lodgingNights:
Fri:
type: radio
label: Lodging Friday Night
date: '2013-04-12'
choices: [No: No, Yes: Yes]
default: No
Sat:
type: radio
label: Lodging Saturday Night
date: '2013-04-13'
choices: [No: No, Yes: Yes]
default: No
availabilityDays:
Fri:
type: select
label: Availability Friday
date: '2013-04-12'
default: None
choices:
None: None
Evening: Kickoff 5PM
Not Sure: Not Sure
etc
因此计划数组最终被传递给计划子表单,该子表单又创建了所有单独的表单元素。然后我有一个单一的计划实体,它只将所有单独的选择存储在一个数组数据库列中。似乎工作正常。
==================================================== ======================
评论要求提供更多代码。这是我的“动态”PlanFormType”
class PlanFormType extends AbstractType
{
protected $metaData = null;
public function getName() { return 'cerad_tourn_person_plan'; }
public function setMetaData($data) { $this->metaData = $data; }
public function getMetaData( ) { return $this->metaData; }
public function buildForm(FormBuilderInterface $builder, array $options)
{
$items = $this->getMetaData();
foreach($items as $name => $item)
{
$isChoice = false;
switch($item['type'])
{
case 'radio':
$isChoice = true;
$expanded = true;
$multiple = false;
$attr = array('class' => 'radio-medium');
break;
case 'select':
$isChoice = true;
$expanded = false;
$multiple = false;
$attr = array();
break;
case 'text':
$attr = array();
if (isset($item['size'])) $attr['size'] = $item['size'];
$builder->add($name,'text',array(
'label' => $item['label'],
'required' => false,
'attr' => $attr,
));
break;
}
if ($isChoice)
{
$builder->add($name,'choice',array(
'label' => $item['label'],
'required' => false,
'empty_value' => false,
'choices' => $item['choices'],
'expanded' => $expanded,
'multiple' => $multiple,
'attr' => $attr,
));
}
}
}
}