0

I want to validate the username field which is a fosuser field but under my own validation rules.

Below are my code snippets:

FormType - UserType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{    
    $builder
        ->add('username')
     ...
}

Entity - User.php

class User extends BaseUser
{
    //no mention of any of the fosuser properties here
 ...
}

Validation: validation.yml

Project\MyBundle\Entity\User:
constraints:
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
        fields: username
        errorPath: username
        message: 'This username is already in use.'
properties:
    dob:
        - NotBlank: ~
        - Type: \DateTime

Controller: UserController.php

public function createAction(Request $request, $brandId)
{
    $entity = new User();
    $form = $this->createCreateForm($entity, $brandId);
    $form->handleRequest($request);

    if ($form->isValid()) {
        ...
    }
}

The validation always fails, ie. $form->isValid()is true even when I enter an already existing username in the form. Please help as I have not been able to figure out a solution so far. I tried copying the orm.xml file to myBundle under the validation folder. But it still takes no effect. Any help will be appreciated.

And when the saving happens i get a duplicate insert error as well.

An exception occurred while executing 'UPDATE user SET username = ?, username_canonical = ? WHERE id = ?' with params ["sub5", "sub5", 27]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'sub5' for key 'UNIQ_7BB0CD5292FC23A8' 
softie
  • 237
  • 1
  • 2
  • 17

1 Answers1

0

Did you tried using @UniqueEntity("username") in User.php, this automatically throws an error in the form saying it's already used.

use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
 * User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity()
 * @UniqueEntity("username")
 *
 */

That worked for me. However I do not use FosUserBundle but the principle should be the same.

Also, I found this which could help you or maybe this, those are using FosUserBundle.

Community
  • 1
  • 1
Splendonia
  • 1,329
  • 3
  • 37
  • 59