我試圖獲得一個多關係(多個依賴一對多關係)的窗體,但沒有成功。我使用的是Symfony 2.3和FOSUserbundle。Symfony形式中的多個依賴一對多關係
實體用戶
use FOS\UserBundle\Entity\User as BaseUser;
[...]
/**
* @ORM\Entity
* @Gedmo\Loggable
* @ORM\Table(name="ta_user", indexes={@ORM\Index(name="IDX_LOGIN_TOKEN", columns={"login_token"})})
*/
class User extends BaseUser
{
[...]
/**
* @ORM\OneToMany(targetEntity="UserLifestyle", mappedBy="user", fetch="LAZY", cascade={"persist", "remove"})
*/
protected $lifestyle;
的UserManager
use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Entity\UserManager as BaseUserManager;
use Acme\UserBundle\Entity\LifestyleQuestion;
use Acme\UserBundle\Entity\UserLifestyle;
[...]
class UserManager extends BaseUserManager {
public function createUser() {
$user = parent::createUser();
$lifestyle = new UserLifestyle();
$lifestyle->setQuestion($this->objectManager->getReference('Acme\UserBundle\Entity\LifestyleQuestion', 1));
$user->addLifeStyle($lifestyle);
$lifestyle = new UserLifestyle();
$lifestyle->setQuestion($this->objectManager->getReference('Acme\UserBundle\Entity\LifestyleQuestion', 2));
$user->addLifeStyle($lifestyle);
$lifestyle = new UserLifestyle();
$lifestyle->setQuestion($this->objectManager->getReference('Acme\UserBundle\Entity\LifestyleQuestion', 3));
$user->addLifeStyle($lifestyle);
return $user;
}
實體UserLifestyle
/**
* @ORM\Entity
* @Gedmo\Loggable
* @ORM\Table(name="ta_user_lifestyle")
*/
class UserLifestyle
{
/**
* @ORM\Id
* @ORM\Column(type="smallint")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="lifestyle")
* @ORM\JoinColumn(name="user_id")
*/
protected $user;
/**
* @ORM\ManyToOne(targetEntity="LifestyleQuestion", inversedBy="answeredByUser")
* @ORM\JoinColumn(name="question_id")
*/
protected $question;
/**
* @ORM\ManyToOne(targetEntity="LifestyleAnswer", inversedBy="userAnswers")
* @ORM\JoinColumn(name="answer_id")
* @Gedmo\Versioned
*/
protected $answer;
然後,有一個形式類型
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', NULL, array('label' => 'E-Mail'))
[...]
->add('lifestyle', 'collection', array(
'type' => new RegistrationLifestyleType(),
'allow_add' => false,
'allow_delete' => false,
'label' => false,
))
現在應該有一個相關的RegistrationLifestyleType
。但我不知道它應該是什麼樣子。我期望在我的註冊表格中有三個選擇字段,顯示與這些問題相關的問題(如標籤)和一堆答案(作爲選擇字段)。該分配的UserManager三個問題到新創建的用戶,所以我們可以得到一個問題有:
$lifestyles = $user->getLifestyles();
foreach ($lifestyles as $lifestyle) {
$question = $lifestyle->getQuestion(); // echo $question->getQuestion();
$answers = $lifestyle->getQuestion()->getAnswers(); // loop through $answers and echo $answer->getAnswer();
}
但我怎麼能修改表單類型,得到這個工作。重要說明:我的意圖是儘可能使用內置功能,並儘量避免通過注入服務容器和實體管理器來擴充表單類型和其他類型。