我要放弃食谱文章了表单集合 http://symfony.com/doc/current/cookbook/form/form_collections.html但是,当尝试将其保留到数据库时,我收到约束冲突错误,引用的列名称 id 为空。
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null
我相信实体设置正确且关联正确,是否需要在表单中添加一些我缺少的内容?
Client
/**
* @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');
}
客户端控制器
$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'));
}