我要放弃关于 form collections 的食谱文章但是,当尝试将其保留到数据库时,我收到约束冲突错误,引用的列名称 id 为空。
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null
我相信实体设置正确并且关联正确,是否需要添加一些我缺少的内容?
客户端
/**
* @ORM\OneToMany(targetEntity="ClientPhone", mappedBy="clients", cascade={"persist"})
*/
protected $clientphones;
客户端电话
/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="clientphones")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id", nullable=false)
*/
protected $clients;
客户类型表单
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,
));
}
客户端电话类型表单
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('home', 'text');
$builder->add('office', 'text');
$builder->add('mobile', 'text');
}
客户端 Controller
$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'));
}
最佳答案
问题解决了。问题出在 addClientphone
函数中的 Client 实体。我必须更改预先生成的代码:
$this->clientphones[] = $clientphones;
至以下内容:
if (!$this->clientphones->contains($clientphone)) {
$clientphone->setClients($this);
$this->clientphones->add($clientphone);
}
return $this->clientphones;
关于forms - Symfony2 - ReferencedColumnName id 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725679/