多亏了这个帮助,我可以创建一个带有可变标签的表单。现在我想创建一个此类表单的集合,但我做不到。
准确地说:我有一个 MyField 类:
class MyField {
protected label;
protected userAnswer;
public function setLabel($label){...}
public function getLabel(){...}
public function setUserAnswer($answer){...}
public function getUserAnswer(){...}
}
我还有一个 MyFieldType 类:
class MyFieldType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$myField = $options['myField'];
$builder->add('userAnswer', 'text', array('label' => $myField->getLabel()));
}
public function getDefaultOptions(array $options){
return array('data_class' => '...\MyField',
'myField' => null);
}
}
并且,在控制器中:
public function MyAction(Request $request){
...
$myField = new MyField();
...
$form = $this->createForme(new MyFieldType(), $myField, array('myField' => $myField));
...
}
综上所述,字段标签是 $myField->label。
现在我想用几个 MyFields 创建一个表单:我有一个 MyForm 类
class MyForm {
protected myFields; // array of MyField
public function setMyFields...
public function getMyFields...
public function addAField...
}
而且我仍然希望字段标签为 $myField->label。那么,我该如何定义 MyFormType ?
我尝试了类似的东西:
class MyFormType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options){
$myFields = $options['myFields'];
$builder->add('myFields', 'collection',
array('type' => new MyFieldType(),
'options' => array('myField' => $myFields[0])));
}
它可以工作(当然所有字段都有相同的标签,我不希望这样),但我不知道如何给每个 MyFieldType 自己的 MyField ...
任何想法 ?