Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

how to use enum with multiple values in Assert\Choice ? #47691

Unanswered
kconde2 asked this question in Q&A
Discussion options

enum RoleEnum: string
{
    case ADMIN = 'ROLE_ADMIN';
    case USER = 'ROLE_USER';
}
class User {
    #[Assert\Choice(choices: RoleEnum::cases(), multiple: true)] // <- this is not working
    private array $roles = [];
}

I have this error message
image

Environnement
Symfony 6.1.4
php 8.1.10
Thanks in advance for helping me

You must be logged in to vote

Replies: 1 comment · 5 replies

Comment options

use Symfony\Component\Validator\Constraints\Type;

class User {
    #[All(new Type(RoleEnum::class))]
    private array $roles = [];
}

should do the trick.

You must be logged in to vote
5 replies
@kconde2
Comment options

I got this
image

@kconde2
Comment options

It's not working even with correct roles. Here I'm using Api Platform
image

@MatTheCat
Comment options

Well RoleEnum::cases returns instances of RoleEnum but you're validating a string...

See #43047 for a discussion and solutions about your use-case.

@kconde2
Comment options

I will see there.

Thanks for your help.

@kconde2
Comment options

@MatTheCat

I finally did this

 #[Assert\Choice(callback: [RoleEnum::class, 'values'] , multiple: true')]

And inside RoleEnum.php

 public static function values(): array
 {
     return array_column(self::cases(), 'value');
 }

Reference here : #43047 (comment)

Thanks again for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.