在Symfony2中使用相同的表单进行用户插入和更新


Using the same form for user insertion and update in Symfony2

我有用户,可以通过表单注册:姓名、姓氏、电子邮件、电话、密码、用户名。

注册用户可以更改:姓名、姓氏、电话

我的用户类型

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', 'text')
        ->add('lastname', 'text')
        ->add('email', 'email')
        ->add('phone', 'text')
        ->add('password', 'text')
        ->add('username', 'text');
}

我应该如何呈现不同的表格进行注册和更新?

唯一的区别是作为第二个属性传递给createForm方法的内容。如果您传递空实体,它将是添加新用户的表单。如果您传递带有用户实体填充数据的实体,它将是一个编辑表单。所以:

$yourNewUserForm = $this->createForm(new UserType(), new UserEntity());
$userEntity = $this->getDoctrine()->getRepository('YourBundle:User')->find(1);
$yourEditUserForm = $this->createForm(new UserType(), $userEntity);

注意:以上代码假设您在类中扩展Controller,并且您有可用的createFormgetDoctrine()方法,但请考虑这是否应该是控制器的一部分,或者应该将其移动到其他地方(这可能是一个更好的主意)