我正在学习使用Symfony2,并且在阅读的文档中,所有与Symfony表单一起使用的实体都具有空构造函数,或者根本没有空构造函数。(例子)
http://symfony.com/doc/current/book/index.html第12章
http://symfony.com/doc/current/cookbook/doctrine/registration_form.html
我已经构造了参数化的构造函数,以便在创建时需要某些信息。看来,Symfony的方法是将执行工作留给验证过程,实质上是依靠元数据断言和数据库约束来确保对象被正确初始化,而放弃了构造函数来确保状态。
考虑:
Class Employee {
private $id;
private $first;
private $last;
public function __construct($first, $last)
{ .... }
}
...
class DefaultController extends Controller
{
public function newAction(Request $request)
{
$employee = new Employee(); // Obviously not going to work, KABOOM!
$form = $this->createFormBuilder($employee)
->add('last', 'text')
->add('first', 'text')
->add('save', 'submit')
->getForm();
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
}
我不应该使用构造函数参数来执行此操作吗?
谢谢
编辑:下面回答
找到了解决方案:
通过查看控制器的API“ createForm()”方法,我发现示例中的内容并不明显。似乎第二个参数不一定是对象:
**Parameters**
string|FormTypeInterface $type The built type of the form
mixed $data The initial data for the form
array $options Options for the form
因此,您不必传递Entity的实例,而只需传递具有适当字段值的Array即可:
$data = array(
'first' => 'John',
'last' => 'Doe',
);
$form = $this->createFormBuilder($data)
->add('first','text')
->add('last', 'text')
->getForm();
另一个选择(可能更好)是在表单类中创建一个空数据集作为默认选项。这里和这里的解释
class EmployeeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('first');
$builder->add('last');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'empty_data' => new Employee('John', 'Doe'),
));
}
//......
}
class EmployeeFormController extends Controller
{
public function newAction(Request $request)
{
$form = $this->createForm(new EmployeeType());
}
//.........
}
希望这可以省去别人的头。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句