Bouffe
Bouffe

Reputation: 849

SonataAdmin form EntityType not required

My entity has an optional relationship (nullable=true) to other entity.

But When I use required = false The form created by Sonata has a <select> with only all my entities, not a blank value.

With a classic symfony form, required = false allow to select no entity

/**
 * @param FormMapper $formMapper
 */
protected function configureFormFields(FormMapper $formMapper)
{

    $formMapper
        ->add('otherEntity', EntityType::class, [
            'class'    => OtherEntity::class,
            'required' => false,
        ])
    ;
}

Do you know why?

Upvotes: 0

Views: 742

Answers (2)

Bouffe
Bouffe

Reputation: 849

I've just found that Sonata is adding a little cross to delete the current selected relationship

It's so small that I didn't saw it last night...

enter image description here

Thanks anyways for the answer M. Kebza!

Upvotes: 1

M. Kebza
M. Kebza

Reputation: 1508

First, check if your entity allows for null value on your relationship. In entity something like (note JoinColumn):

/**
 * @var OtherEntity
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\OtherEntity")
 * @ORM\JoinColumn(nullable=true)
 */
private $otherEntity;

Second add placeholder option to your form mapping:

/**
 * @param FormMapper $formMapper
 */
protected function configureFormFields(FormMapper $formMapper)
{

    $formMapper
        ->add('otherEntity', EntityType::class, [
            'class'    => OtherEntity::class,
            'required' => false,
            // This is what sonata requires
            'placeholder' => 'Please select entity' 
        ])
    ;
}

Upvotes: 3

Related Questions