具有非映射字段的表单中的Symfony 3唯一约束

I'm using Symfony 3 and I'm working on a form without a mapped entity, with data_class => null like :

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname', null, ['label' => 'user.edit.label.firstname'])
            ->add('lastname', null, ['label' => 'user.edit.label.lastname'])
            ->add('email', EmailType::class, ['label' => 'common.email', ])
            ->add('state', ChoiceType::class, [
                'label' => 'common.state',
                'choices' => array_flip(CompanyHasUser::getConstants())
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => null,
            'translation_domain' => 'messages'
        ));
    }

So with this, how can I constraint my field 'email' to be unique ? I need to check that in my entity User (attribute=email).

Any ideas ?

Without a mapped entity, you'll have to check against the database. Easiest way to do that is to inject the UserRepository to your form class. (Inject a repository link.)

In your repository, create a method to query that ensures an email doesn't already exist. This could pretty easily return a boolean true or false.

In your form, create a custom constraint callback.

public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'         => null,
            'translation_domain' => 'messages',
            'constraints'        => [
                new Callback([
                    'callback' => [$this, 'checkEmails'],
                ]),
            ]))
        ;
    }

And add the callback function in the same form class, using the UserRepo.

/**
 * @param $data
 * @param ExecutionContextInterface $context
 */
public function checkEmails($data, ExecutionContextInterface $context)
{
    $email = $data['email'];
    if ($this->userRepository->checkEmail($email)) {
        $context->addViolation('You are already a user, log in.');
    }
}

See also this blog post on callback constraints without an entity.