-1

I have a User entity with bidirectional relationship to Passport entity

/** @Entity */
class User
{

    /**
     * @OneToOne(targetEntity="Passport", mappedBy="user")
     * @JoinColumn(name="passport_id", referencedColumnName="id")
     */
    private $passport;

    // plus other fields
    // plus getters and setters for all of the above...
}


/** @Entity */
class Passport
{

    /**
     * @OneToOne(targetEntity="User", inversedBy="passport", cascade={"persist", "remove"})
     * @JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;

}

and I have FormType

 /** @UserType */
 $builder->add
 (
    'passport',
    'entity',
     array(
         'class' => 'AppBundle\Passport',
         'empty_value' => 'Please choose a passport'
     )
 );

so when submitting the form with chosen passport for user, we need to set user in passport entity too

/** @Entity */
    class User
    {
        //  
        public function setPassport($passport){
            $this->passport=$passport;
            if ($passport){
                $passport->setUser($this);
            }
        }
        //and other setters
    }

Suppose User entity has link to Passport entity. And now in form we want to unlink it (set passport to null). We can select empty_value choice, so after submitting the form user will have no passport. But passport will still have link to user.

It is possible to setUser(null) in controller just before binding the request to the form, but

what is the best solution here?

Is it a good idea to have unidirectional relationship in current case?

1 Answers1

0

It sure seems that a unidirectional relationship would make things much simpler in this case, what about a choice_loader option for the ChoiceType field, it does a callback to a function providing choices, you could provide a null choice and a list of passports to choose from.