skip to Main Content

I’m trying to create a edit form for user and want to list current user roles in form and
also want to make choice from all roles from enum Roles.

There is a example of my code.
Current error is "Object of class AppEntityRoles could not be converted to string", but i tried many examples from here and I can’t run my code.
Can someone explain me how is correct way to do it? For sure I made a mistake somewhere, but I can’t figure out exactly where.
I’m working with PHP 8.1, Symfony 7.1
Thanks in advance


<?php

use AppFormUserFormType;
use AppRepositoryUserRepository;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;


namespace Entity;
enum Roles: string
{
    case ADMIN = 'ADMIN';
    case EMPLOYEE = 'EMPLOYEE';
    case CLIENT = 'CLIENT';

    public static function getRole($name)
    {
        return self::tryFrom($name)->value;
    }
}

class User implements UserInterface
{
    /**
     * @var list<string> The user roles
     */
    #[ORMColumn]
    private array $roles = [];

    /**
     * @see UserInterface
     *
     * @return list<string>
     */
    public function getRoles(): array
    {
        return $this->roles;
    }
}

namespace Form;
class UserFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('roles', ChoiceType::class, [
                    'label' => 'role: ',
                    'choices' => Roles::cases(),
                    'choice_value' => function ($choice) {
                        return Roles::getRole($choice);
                    },
                ]
            );
    }
}


class AdminController extends AbstractController
{
    private UserRepository $userRepository;

    public function __construct(EntityManagerInterface $em, UserRepository $userRepository)
    {
        $this->em = $em;
        $this->userRepository = $userRepository;
    }

    #[Route('admin/user_edit/{id}', name: 'admin_user_edit')]
    public function editUser(Request $request, $id): Response
    {
        $user = $this->userRepository->findOneById($id);
        /*
         *  record for roles in DB is {'1': 'ADMIN', '2': 'EMPLOYEE'}
         */
        $form = $this->createForm(UserFormType::class, $user);

        try {
            $form->handleRequest($request);
        } catch (Exception $e) {
            echo 'failed : '.$e->getMessage();
        }

        if ($form->isSubmitted() && $form->isValid()) {
            // TODO process data
        }

        return $this->render('admin/user_edit.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Ok, I found a solutions for that example of my code. Just add 'multiple' => true to options

    $builder
                ->add('roles', ChoiceType::class, [
                        'label' => 'role: ',
                        'choices' => Roles::cases(),
                        'multiple' => true,
                        'choice_value' => function ($choice) {
                            return Roles::getRole($choice);
                        },
                    ]
                );
    

    and shows correct values. Also change Roles from enum to class.


  2. you may try the enums type of symfony forms.
    https://symfony.com/doc/current/reference/forms/types/enum.html

    Otherwise, to answer your question Roles::cases() returns an array of Enums, and php do not know how it should print it.
    You could try using

    array_column(Roles::cases(), 'name');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search