Search code examples
phpsymfonyformbuilder

how to have symfony2 formbuilder check in DB as part of validation


What is the best way of checking whether a value exists already before allowing a form to insert it? I want the form validation to be false if there is already a user with the specified username. I guess a unique constraint somewhere would do here, but to be more all-round, or to be able to check for values in a more customized way. Let's say there are several admin accounts in a customer account, they all have privileges to demote other admins, and one check I would like to be able to make is whether you are disabling the last admin or not (and if so prevent the demote action, with a nice error message right on the form...)

Could I for instance access the entity manager from within my formType, or would that have to be passed from the controller that workaround-ish way?

    $builder
        ->add('username', 'text', array('label' => 'Användarnamn '))
        ->add('email', 'email', array('label' => 'Epost '))
        ->add('plainPassword', 'repeated', array('type' => 'password', 'first_name' => 'Lösenord ', 'second_name' => 'Upprepa lösenord',));

Solution

  • You should create a custom validation constraint and inject it with EntityManager to access the database.