Symfony2 Forms - 如何在表单构建器中使用参数化构造函数

Sp3*_*gel 3 symfony

我正在学习使用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(),
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

我不应该使用构造函数参数来执行此操作吗?

谢谢

编辑: 回答下面

Sp3*_*gel 6

找到了解决方案:

查看控制器"createForm()"方法的API,我发现了一些从示例中看不出来的东西.似乎第二个参数不一定是一个对象:

**Parameters**
    string|FormTypeInterface     $type  The built type of the form
    mixed                        $data  The initial data for the form
    array                        $options   Options for the form 
Run Code Online (Sandbox Code Playgroud)

因此,您可以简单地使用适当的字段值传入一个数组,而不是传入实体的实例:

$data = array(
    'first' => 'John',
    'last' => 'Doe',
);
$form = $this->createFormBuilder($data)
    ->add('first','text')
    ->add('last', 'text')
    ->getForm();
Run Code Online (Sandbox Code Playgroud)

另一个选项(可能更好)是在表单类中创建一个空数据集作为默认选项.这里这里的解释

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());
    }
    //.........
}
Run Code Online (Sandbox Code Playgroud)

希望这可以节省别人的头脑.

  • 如果仅传递静态字符串,则很容易。如何将变量传递给员工的构造函数? (2认同)