php - Validation of fosuser field username

813

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' 
12

Answer

Solution:

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.

People are also looking for solutions to the problem: Updating MySQL database using PDO in PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.