Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3 unique constraint in form with non mapped field

Tags:

php

symfony

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 ?

like image 241
Clément Andraud Avatar asked Dec 04 '25 14:12

Clément Andraud


1 Answers

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.

like image 92
Ollie in PGH Avatar answered Dec 07 '25 04:12

Ollie in PGH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!