Tuesday, October 4, 2011

Deal with a nullable relation field in an Entity with Doctrine2

Entity generation from an existing database is a long way to go... Last issue : set a relation field to NULL => the generated setter expects an Entity Object as a parameter

MyEntity is an entity including a field myRelatedEntity referencing an entity MyRelatedEntity. Basic generation produces this setter :
class MyEntity
{

    ...

    /**
     * Set myRelatedEntity
     *
     * @param Xxx\YourBundle\Entity\MyRelatedEntity $myRelatedEntity
     */
    public function setMyRelatedEntity(MyRelatedEntity $myRelatedEntity)
    {
        $this->myRelatedEntity = $myRelatedEntity;
    }

    ...

}
This setter doesn't allow to set NULL value. Instead you get this kinf of error :
Catchable fatal error: Argument 1 passed to setMyRelatedEntity() must be an instance of \Xxx\YourBundle\Entity\MyRelatedEntity, null given
This indicates you have to modify the setter to accept null value :
class MyEntity
{

    ...

    /**
     * Set myRelatedEntity
     *
     * @param mixed $myRelatedEntity Entity MyRelatedEntity or NULL
     */
    public function setMyRelatedEntity(MyRelatedEntity $myRelatedEntity = null)
    {
        $this->myRelatedEntity = $myRelatedEntity;
    }

    ...

}

5 comments :

Thibaud said...

Or just add a default param "null" and all will be fine!
Like this:

/**
* Set myRelatedEntity
*
* @param Xxx\YourBundle\Entity\MyRelatedEntity $myRelatedEntity
*/
public function setMyRelatedEntity( \Xxx\YourBundle\Entity\MyRelatedEntity $myRelatedEntity = null)
{
$this->myRelatedEntity = $myRelatedEntity;
}

PéCé said...

Wow, I feel ashamed... At this time I didn't know that defining NULL as default value made type hinting to be neutralized if null was provided as parameter...

Thibaud said...

Me too since today! ;)
I saw your post, and well... I thought good to share :)

atrandafir said...

You saved me! Thanks! :)

Abdelaziz Khabthani said...

PHP is weird lol, Thanks dude!

Post a Comment

Comments are moderated before being published.