2个实体1形成Symfony 3

时间:2017-05-27 19:47:54

标签: symfony doctrine

熟悉symfony,直到我发现自己处于中间位置。

我有两个实体:用户和帐户。

每个用户都有一系列帐户,例如Google帐户,Facebook帐号等。用户位于一个表中,帐户位于不同的表中。显然,帐户是根据用户的ID获取的。

如何将两个实体合并为一个表单,以便我可以获取,创建,编辑和/或删除条目?

我的用户实体:

use statements here
...
private $id;
private $fullname;
private $accounts;

public function __construct(){
 $this->accounts = new ArrayCollection();
}    
//setters and getters...

我的帐户实体:

use statements here
...
private $id;
private $user_id; //id in user entity
private $service; //i.e google account
private $username;
private $password;

//setters and getters...

我的用户表单:

class UserType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
...
    $builder
        ->add('id',HiddenType::class)
        ->add('FullName',TextType::class)
        ->add('accounts'.,CollectionType::class,[
             'entry_type' => AccountType::class
         ])
 ...
 public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\User'
    ));
}

帐户表单

class AccountType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
...
    $builder
        ->add('id',HiddenType::class)
        ->add('accountname',TextType::class) //i.e Google Account
        ->add('username',TextType::class)
        ->add('password',TextType::class)
 ...
 public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Account'
    ));
}

我的控制器:

...      
 @Route("/users/{id}/edit")
...
public function EditAction(Request $request, User $user){
...
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
...
...
return $this->render("/pages/users/edit.html.twig",
  ["form"=>$form->createView()]
);

根本没有错误,但表单没有显示帐户实体的任何字段。

i,e,. {{ form_row(accounts.username) }}

任何想法或帮助或指向正确的方向都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

你需要调用另一个形式的表单,调用它的Type:

 $builder
    ->add('id',HiddenType::class)
    ->add('FullName',TextType::class)
    ->add('accounts', 'collection', array(
            'type' => new AccountType(), 
            'allow_add' => true,))

答案 1 :(得分:0)

答案其实很简单。我只需要在$ accounts属性中添加适当的注释。

/**
* @ORM\ManyToMany(targetEntity="Account")
*
private $accounts;   

感谢您的所有投入。整个脚本现在正在运行