简体   繁体   中英

Symfony embedded forms and constraints

Imagine a simple entity like this

class User {
  /**
   * @ORM\Embedded(class="Role")
   */
  protected $role;
}

and form type like this

class UserType extends AbstractType
{
  /**
   * @param FormBuilderInterface $builder
   * @param array $options
   */
  public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('role', RoleType::class);
}

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(
        array(
            'data_class' => 'XXXBundle\Entity\User',
            'csrf_protection' => false,
        )
    );
}
}

and the Role entity the the RoleType form

/**
 * @ORM\Embeddable()
 */
class Role
{
    /**
     * @ORM\Column(type="string")
     * @Assert\Choice(choices={"foo", "bar"})
     */
    private $name;

    /**
     * Role constructor.
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }
}

class RoleType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'XXXBundle\Entity\Role',
                'empty_data' => function (FormInterface $form) {
                    return new Role($form->get('name')->getData());
                },
            )
        );
    }
}

Using the typical form->isValid the choice constraint assertions is not working properly... is not actually validating the Role name value.

I found the solution for Symfony3

    /**
     * @ORM\Embedded(class="Role")
     * @Assert\Valid()
     */
    protected $role;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM