Gaylord.P
Gaylord.P

Reputation: 1468

Insert entity with persist : cannot be null

I have two entity "OneToOne" with Symfony : "charge" and "ecriture" :

Charge entity :

    /**
     * @ORM\OneToOne(targetEntity="LogicielBundle\Entity\Ecriture", inversedBy="coproprieteCharge", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $ecriture;

    public function setEcriture(\LogicielBundle\Entity\Ecriture $ecriture)
    {
        $this->ecriture = $ecriture;
        $ecriture->setCoproprieteCharge($this);
        return $this;
    }

Ecriture entity :

<?php
class Ecriture
{

    /**
     * @ORM\OneToOne(targetEntity="LogicielBundle\Entity\Copropriete\Charge", mappedBy="ecriture", cascade={"persist"})
     * @ORM\JoinColumn(nullable=true)
     */
    private $coproprieteCharge;

    public function setCoproprieteCharge(\LogicielBundle\Entity\Copropriete\Charge $coproprieteCharge)
    {
        $this->coproprieteCharge = $coproprieteCharge;
        return $this;
    }

And I Have very simple form with imbrication :

ChargeType :

<?php
class ChargeType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('ecriture', new EcritureType, array(
                'label' => false
            ))
        ;
    }

This Controller is very simple : just call "New Charge()" beacause I think Ecriture insert with "persist" in entity comment.

But I have this error " SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'ecriture_id' cannot be null " ; I don't understand beacause "ecriture" insert with "persist"

Upvotes: 2

Views: 346

Answers (1)

Jan Mares
Jan Mares

Reputation: 805

OneToOne is represented only by one join column and it is the one on the field where you use inversedBy. There you specified, that this column is not nullable. As you probably did not set instance of Ecriture to your new instance of Charge entity it stays null and that is violation of nullable=false that you specified.

Cascade persist does not mean, that a new instance of entity is created by the entity manager, if it has not been set for not-nullable field. The entity managaer may not know how to create one (e.g. entity can have constructor with required parameters).

Upvotes: 0

Related Questions