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

3
我正在学习使用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(),
        ));
    }
}

我不应该使用构造函数参数来做这件事吗?谢谢。
编辑:下面有答案。
1个回答

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 

因此,您不必传递实体的实例,只需传递一个带有相应字段值的数组:

$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());
    }
    //.........
}

希望这能帮助其他人省去一些困惑。

2
如果只传递静态字符串,那很容易。如何将变量传递给“Employee”的构造函数? - Mike Doe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接