保存/嵌入关联的表单类型

时间:2013-09-20 11:01:34

标签: symfony symfony-forms

我有2个实体UserMember

User包含所有相关的正常内容(用户名,密码,电子邮件)

Member还有其他一些字段,包括First NameLast NameAge

我正在尝试创建新的Member并显示包含User字段和Member字段的表单。

我目前有以下内容:

user.php的

$protected $username;
$protected $email;


/**
* @ORM\OneToMany(targetEntity="BM\UserBundle\Entity\Member", mappedBy="user")
*/
protected $member;

Member.php

 /**
 * @ORM\ManyToOne(targetEntity="BM\UserBundle\Entity\User", inversedBy="member")
 */
 protected $user;

我也有两种表单类型:

MemberType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('user', new UserType())
        ->add('firstname')
        ->add('lastname')
        ->add('age')
    ;
}

public function getDefaultOptions(array $options)
{
    return array(
        'data_class' => 'BM\UserBundle\Entity\User'
    );
}

UserType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('username')
        ->add('email')
        ->add('password')
    ;
}


public function getName()
{
    return 'user';
}

当我刷新呈现表单的页面时,出现以下错误:

  

捕获致命错误:传递给BM \ UserBundle \ Entity \ Member :: setUser()的参数1必须是BM \ UserBundle \ Entity \ User的实例,给定数组,在/ var / www / proj / vendor /中调用第345行的symfony / symfony / src / Symfony / Component / PropertyAccess / PropertyAccessor.php,在/var/www/proj/src/BM/UserBundle/Entity/Member.php第259行中定义

第259行是:

public function setUser(\BM\UserBundle\Entity\User $user = null)

我是以正确的方式接近这个吗?

编辑:

MemberController.php

$member = new Member();
    $form = $this->createForm(new MemberType(), $member);

    if($request->isMethod('post')) {
        $form->submit($request);
        if ($form->isValid()) {

            $em->persist($member);
            $em->flush();

            $request->getSession()->getFlashBag()->add('success', 'Member has been saved');
        } else {
             $request->getSession()->getFlashBag()->add('error', 'Could not save the member');
        }

    }

1 个答案:

答案 0 :(得分:0)

尝试这种方式

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('user', new UserType())
        ->add('firstname')
        ->add('lastname')
        ->add('age')
    ;
}

public function setDefaultOptions(array $options)
{
    return array(
        'data_class' => 'BM\UserBundle\Entity\Member'
    );
}


# UserType.php #

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('username')
        ->add('email')
        ->add('password')
    ;
}

public function setDefaultOptions(array $options)
{
    return array(
        'data_class' => 'BM\UserBundle\Entity\User'
    );
}

查看文档:{​​{3}}