0
votes

I have this class:

 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
class Parameter{

    /**
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @ORM\ManyToOne(targetEntity="Project\Bundle\Entity\Anthropometry", inversedBy="parameter")
    * @ORM\JoinColumn(name="anthropometry_id", referencedColumnName="id")
    * 
    */
    protected $anthropometry;

    /**
     * @ORM\Column(name="data", type="string", length=255, nullable=true)
     */
    protected $data;
   ...

}

and this:

 /**
 * @ORM\Table(name="anthropometry")
 * @ORM\Entity
 */
class Anthropometry {
/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * 
 * @ORM\OneToMany(targetEntity="Project\Bundle\Entity\Parameter", mappedBy="anthropometry", cascade={"persist"})
 * 
 */ 
protected $parameter;

    ...
}

In my Controller I am creating a form and validating in the same Action. To create the form I need instance one Parameter. But not need persist him.

So.. when I call $em->flush I got the error:

A new entity was found through the relationship ...

To solve this I put cascade={"persist"} in annotation:

//Class Anthropometry
...
/**
 * 
 * @ORM\OneToMany(targetEntity="Project\Bundle\Entity\Parameter", mappedBy="anthropometry", cascade={"persist"})
 * 
 */ 
protected $parameter;

But now, in my Database, the parameters are being persisted with field 'Data' = NULL

Can I check with prePersist if the field is NULL before persist?

something like this?

//class Parameter
/**
 * 
 * @ORM\prePersist
 */
public function prePersist(){
    if($this->getData() == NULL){
        return false;
    }
}

Thx!

1

1 Answers

0
votes

I didn't verify if it works but you could try unsetting the parameter before persisting the Anthropometry (since you don't need to persist parameters):

//class Anthropometry
/**
 * @ORM\prePersist
 */
public function prePersist()
{
    if(!is_null($this->parameter) && $this->parameter->getData() == null){
        $this->parameter = null;
    }
}