开发者

Use existing relation or create a new one

I have this form which relates to an object of class Film, which has a Director relation, and I would like to have a choice between 开发者_开发百科selecting an existing director or creating a new one. The first choice is easy :

class FilmType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('director');
    }
}

The second choice is a quite easy too :

class FilmType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('director', new DirectorType());
    }
}

but I can't figure out how to reconcile the two solutions. I tried this:

class FilmType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    { 
        $builder->add('director')->add('director2', new DirectorType());
    }
}

but of course, it does not work because my entity has no corresponding field, and I get the following error :

Neither property "director_2" nor method "getDirector2()" nor method "isDirector2()" exists in class "Uc\LegalBundle\Entity\Film"

I think I should perhaps create a new class named DirectorChoiceType, for instance, but it seems a bit too much for this. Isn't there a simpler way to go?

Mockup of what I want to achieve :

Use existing relation or create a new one


// form
class FilmType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    { 
        $builder
            ->add('new_director_fn')
            ->add('new_director_ln')
            ->add('director', null, array(
                'empty_value' => 'Choose an option',
                'required' => false
            ));
    }
}

// entity
class Film
{

    // not mapped
    private $new_director_fn;

    // not mapped
    private $new_director_ln;

    // orm relation
    private $director;
    }
}


// controller
class FilmController
{

    public function createAction()
    {

        //...

        if ($form->isValid()) {
            if ( $film->director === null && ($film->new_director_fn && $film->new_director_ln) )
            {
                $director = new Director();
                $director->setFirstName($film->new_director_fn);
                $director->setLastName($film->new_director_ln);
                $em->persist($director);
                $film->setDirector($director);
            }
            $em->persist($film);
            $em->flush();
        }

        //...

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜