Symfony2 - ReferencedColumnName id is null
I am about to post an article in a form collection collection , however, while trying to save this to the database, I get a constraint violation error with the specified column name named null.
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null
I believe the entities are set up correctly and linked correctly, is there anything I need to add to my form that I cannot see?
Client
/**
* @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 form
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 form
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'));
}
+2
source to share
1 answer
Figured out the problem. The problem was the Client object in the function addClientphone
. I had to change the pre-generated code:
$this->clientphones[] = $clientphones;
To the next:
if (!$this->clientphones->contains($clientphone)) {
$clientphone->setClients($this);
$this->clientphones->add($clientphone);
}
return $this->clientphones;
+4
source to share