Skip to content

Commit d60617f

Browse files
committed
Change unique field of User entity to username with form validation
1 parent 7d67387 commit d60617f

3 files changed

Lines changed: 42 additions & 2 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace DoctrineMigrations;
6+
7+
use Doctrine\DBAL\Schema\Schema;
8+
use Doctrine\Migrations\AbstractMigration;
9+
10+
final class Version20250703184453 extends AbstractMigration
11+
{
12+
public function getDescription(): string
13+
{
14+
return 'Change unique user field';
15+
}
16+
17+
public function up(Schema $schema): void
18+
{
19+
$this->addSql(<<<'SQL'
20+
DROP INDEX uniq_8d93d649e7927c74
21+
SQL);
22+
$this->addSql(<<<'SQL'
23+
CREATE UNIQUE INDEX UNIQ_8D93D649F85E0677 ON "user" (username)
24+
SQL);
25+
}
26+
27+
public function down(Schema $schema): void
28+
{
29+
$this->addSql(<<<'SQL'
30+
DROP INDEX UNIQ_8D93D649F85E0677
31+
SQL);
32+
$this->addSql(<<<'SQL'
33+
CREATE UNIQUE INDEX uniq_8d93d649e7927c74 ON "user" (email)
34+
SQL);
35+
}
36+
}

src/Doctrine/Entity/User.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,27 @@
88
use Doctrine\ORM\Mapping\GeneratedValue;
99
use Doctrine\ORM\Mapping\Id;
1010
use Doctrine\ORM\Mapping\Table;
11+
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
1112
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
1213
use Symfony\Component\Security\Core\User\UserInterface;
1314

1415
#[Entity(repositoryClass: UserRepository::class)]
1516
#[Table(name: '`user`')]
17+
#[UniqueEntity('username', message: 'This username is already taken')]
1618
class User implements UserInterface, PasswordAuthenticatedUserInterface
1719
{
1820
#[Column]
1921
#[GeneratedValue]
2022
#[Id]
2123
private ?int $id = null;
2224

23-
#[Column(length: 80)]
25+
#[Column(length: 80, unique: true)]
2426
private ?string $username = null;
2527

2628
#[Column(length: 180, nullable: true)]
2729
private ?string $name = null;
2830

29-
#[Column(length: 180, unique: true, nullable: true)]
31+
#[Column(length: 180, nullable: true)]
3032
private ?string $email = null;
3133

3234
#[Column]

translations/validators.en.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ Enter an email address: Enter an email address
33
Please enter a password: Please enter a password
44
The password fields must match: The password fields must match
55
Your password should be at least {{ limit }} characters: Your password should be at least {{ limit }} characters
6+
7+
This username is already taken: This username is already taken

0 commit comments

Comments
 (0)