Symfony 3 unique limitation on form with no display field

I am using Symfony 3 and I am working on a form with no mapped object 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 how can I restrict my field to be 'email'

unique? I need to check what is in my entity User (attribute = email).

Any ideas?

+3


source to share


1 answer


Without a mapped entity, you will need to check the database. The easiest way to do this is to inject the UserRepository into the form class. ( Enter repository link .)

In your repository, create a request method that makes sure the email doesn't exist yet. This can return a boolean true or false quite easily.

In your form, create a custom callback.

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

      



And add a callback function to the same form class using 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 the blog post on callback constraints without an object .

+1


source







All Articles