Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9137131
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T09:03:40+00:00 2026-06-17T09:03:40+00:00

Question is, how to add validation for unique username? i can simply check it

  • 0

Question is, how to add validation for unique username? i can simply check it by $user->findByUsername(…), but then i will not have proper error

Main problem is that form entity (Constraints) and (ORM) entity is separate one….

User :

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Table(name="_account")
 */
class User implements UserInterface
{


/**
 * @var integer
 *
 * @ORM\Id
 * @ORM\Column(name="id", type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @var string
 * 
 * @ORM\Column(name="usrename", type="string", length=255)
 */
protected $username;

// ...........
}

Registration :

use Symfony\Component\Validator\Constraints as Assert;

class Registration
{

/** accountName
 * @Assert\NotBlank()
 * @Assert\Regex
 * (
 *      pattern="/^[a-zA-Z0-9]{1,}$/i",
 *      message="You use illegal character(s). Must be a-z, A-Z and 0-9 symbols."
 * )
 * @Assert\Length
 * (
 *      min="4",
 *      minMessage="User name must be more then 3 characters.",
 *      max="25",
 *      maxMessage="User name must be less then 25 characters."
 * )
 */
protected $accountName;

public function setAccountName($accountName)
{
    $this->accountName = $accountName;
}
// ............
}

RegistrationType :

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RegistrationType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('accountName', 'text', array('label' => 'Account Name'))
            ->add('accountPass', 'repeated', array(
                'type' => 'password',
                'first_name' => 'Password',
                'second_name' => 'Confirm'))
            ->add('accountMail', 'text', array('label' => 'Account Email'))
            ->add('accountTerm', 'checkbox', array('label' => 'Our Terms of use'));
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Some\NewBundle\Form\Registration',
        'required' => false,
        'csrf_protection' => false
    ));
}
// ..........
}

and the last one, controller

class RegistrationController extends Controller
{

public function defaultAction()
{
    $form = $this->createForm(new RegistrationType(), new Registration);

    if ($this->getRequest()->isMethod('post'))
    {
        $form->bind($this->getRequest());
        if ($form->isValid())
        {
            $em = $this->getDoctrine()->getEntityManager();
            $ef = $this->get('security.encoder_factory');

            $user = new User();


            $data = $form->getData();
            $pass = $ef->getEncoder($user)->encodePassword($data->getAccountPass(), $user->getSalt());

            $user->setPassword($pass);
            $user->setUsername($data->getAccountName());
            $user->setEmail($data->getAccountMail());

            // changed from here
            $userErrors = $this->get('validator')->validate($user);
            if (count($userErrors) > 0)
            {
                foreach ($userErrors as $error)
                {
                    $form->addError(new FormError($error));
                    //$form->get($error->getPropertyPath())->addError($error->getMessage());
                }
            } else
            {
                $em->persist($user);
                $em->flush();
            }
        }
    }
    // ..............
    }}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T09:03:41+00:00Added an answer on June 17, 2026 at 9:03 am

    This is a job for Doctrine2 UniqueEntity constraint !

    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Security\Core\User\UserInterface;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    
    /**
     * @ORM\Table(name="_account")
     * @UniqueEntity("username")
     */
    class User implements UserInterface
    {
    
    
    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    
    /**
     * @var string
     * 
     * @ORM\Column(name="username", type="string", length=255, unique=true)
     */
    protected $username;
    
    // ...........
    }
    

    I also added unicity on the table structure (unique=true) for username column

    EDIT:

    As you handle different entity in the form than the one that is persisted, you must explicitely validate the ORM entity :

    public function defaultAction()
    {
        $form = $this->createForm(new RegistrationType(), new Registration);
    
        if ($this->getRequest()->isMethod('post'))
        {
            $form->bind($this->getRequest());
            if ($form->isValid())
            {
                $em = $this->getDoctrine()->getEntityManager();
                $ef = $this->get('security.encoder_factory');
    
                $user = new User();
    
    
                $data = $form->getData();
                $pass = $ef->getEncoder($user)->encodePassword($data->getAccountPass(), $user->getSalt());
    
                $user->setPassword($pass);
                $user->setUsername($data->getAccountName());
                $user->setEmail($data->getAccountMail());
    
                if ($this->get('validator')->validate(user))
                {
                    $em->persist($user);
                    $em->flush();
                }
                else
                {
                    $form->addError(/* ... */);
                }
            }
        }
        // ..............
    }
    

    I let you find out how to add error to your Form…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This question was asked but was not answered. I have contact form and I
this is a different question concerning: add a connection to database not working, asp.net
Question: I want to add a unique constraint on a mapping table (n:n). I
Question: Using Ruby it is simple to add custom methods to existing classes, but
Question 1) I have a control to which I add an attribute from the
REVISED QUESTION : We have tracked this down to a custom add to cart
If I add [Required] in my entity class then unobtrusive validation works fine. [Required]
I have a form (new poll form) in which I can add multiple items
I have a Django form that will add an entry to a database with
In WF4 custom activities, I understand you can add warning of validation error by

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.