Php 如何在一个表单中合并两个实体?

Php 如何在一个表单中合并两个实体?,php,symfony,Php,Symfony,我想在一种形式中使用两个实体,尽管使用了前面问题中类似的提示,但它不起作用。我有以下控制器: <?php namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Rou

我想在一种形式中使用两个实体,尽管使用了前面问题中类似的提示,但它不起作用。我有以下控制器:

<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\User;
use AppBundle\Form\UserType;
use AppBundle\Entity\School;
use AppBundle\Form\SchoolType;

class RegistrationController extends Controller
{

  /**
   * @Route("/register", name="user_register")
   */
  public function registerAction(Request $request)
  {
      $user = new User();
      $form = $this->createForm(new UserType(), $user);
      $form->add('status','hidden', array('attr' => array('value' => '0') ))
           ->add('school', new SchoolType());

      return $this->render('AppBundle:Main:register.html.twig', array('form' => $form->createView()));
  }

}

您的用户类必须有一个名为school的属性

/**
 * @ORM\Entity()
 * @ORM\Table(name="users")
 */
class User
{

/**
 * @ORM\OneToMany(targetEntity="Bundle\Entity\Schools",mappedBy="user")
 */
protected $school;
然后,为它生成实体

php app/console doctrine:generate:entities Bundle:User
或手动编写函数:

public function setSchool($school)
{
    $this->school= $school;

    return $this;
}    

public function getSchool()
{
    return $this->school;
}

它准确地告诉你你需要知道的。在用户实体中,您要么与学校实体没有关系,要么缺少学校的getter&setter。假设这是一对一的关系,你应该有如下几点:

   /**
     * @OneToOne(targetEntity="School", inversedBy="user")
     * @JoinColumn(name="school_id", referencedColumnName="id")
     **/
    private $school;
使用getter和setter:

public function setSchool(School $school = null)
{
    $this->school = $school;

    return $this;
}

public function getSchool()
{
    return $this->school;
}
注意:这些应该由自动生成。如果正确设置了用户->学校关系,并且缺少setter/getter,则可能根本没有运行此操作

请同时阅读

php app/console doctrine:generate:entities Bundle:User
public function setSchool($school)
{
    $this->school= $school;

    return $this;
}    

public function getSchool()
{
    return $this->school;
}
   /**
     * @OneToOne(targetEntity="School", inversedBy="user")
     * @JoinColumn(name="school_id", referencedColumnName="id")
     **/
    private $school;
public function setSchool(School $school = null)
{
    $this->school = $school;

    return $this;
}

public function getSchool()
{
    return $this->school;
}