2
但是,當我嘗試將此持久化到數據庫時,我得到了關於form collections的食譜文章,但遇到約束違規錯誤,並且引用列名稱id爲null。Symfony2 - ReferencedColumnName id爲null
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null
我相信這些實體安裝正確且相關性正確,有什麼我需要添加到我的表單中,我錯過了嗎?
客戶
/**
* @ORM\OneToMany(targetEntity="ClientPhone", mappedBy="clients", cascade={"persist"})
*/
protected $clientphones;
Clientphone
/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="clientphones")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id", nullable=false)
*/
protected $clients;
ClientType形式
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', 'text', array(
'label' => 'First Name'
))
->add('lastName', 'text', array(
'label' => 'Last Name'
))
->add('email', 'text', array(
'label' => 'E-mail Address'
))
->add('clientphones', 'collection', array(
'type' => new ClientPhoneType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
));
}
ClientPhoneType形式
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('home', 'text');
$builder->add('office', 'text');
$builder->add('mobile', 'text');
}
ClientController
$client = new Client();
$phone = new ClientPhone();
// $phone->home = '2134959249';
// $phone->office = '2134959249';
// $phone->mobile = '2134959249';
$client->getClientPhones()->add($phone);
$form = $this->createForm(new ClientType(), $client, array(
'action' => $this->generateUrl('client'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($client);
$em->flush();
$session = $request->getSession();
$session->getFlashBag()->add('message', 'Client successfully saved to database');
return $this->redirect($this->generateUrl('client'));
}
這是一個記錄的問題 - Doctrine2如果它被設置在僅持續一個新的關聯** *擁有*協會的一方。在這種情況下''clientphone'是所有者的一方,無論何時將'$ clientphone'添加到'$ client',您還需要將'$ client'添加到'$ clientphone'中。反過來不應該是必要的。 – 2014-11-04 09:20:21