lundi 30 août 2021

Symfony form EntityType checkbox

I'm attempting to create an admin user edit page based off the default user entity/form/repository that includes being able to select the roles for that user.

I created a UserRoles entity/repository to hold all the different roles. And have the following changes to the default UserFormType. It works fine to read the list of roles from UserRoles, and it saves the selected checkboxes to the User entity.

I just haven't been able to get the saved roles from the entity to show as checked in my form.

My code for 'choice_attr' is obviously wrong, but I've included it for some of my debug code. I'm hoping I'm just using the wrong parameter.

<?php

namespace App\Form;

class UserFormType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        //var_dump($options);die;
        $builder
                ->add('email', EmailType::class, ['required' => true])
                ->add('plainPassword', PasswordType::class, [ ... ],
                ])
                ->add('firstName', TextType::class, ['required' => true])
                ->add('lastName', TextType::class, ['required' => true])

                ->add('roles', EntityType::class, [
                        'class' => \App\Entity\UserRoles::class,
                        'choice_label' => 'role',

                        'choice_attr' => function ($val, $key, $index) {
                            var_dump($val);
                            var_dump($key);
                            var_dump($index); die;

                            return ($key==1) ? ['checked' => true] : ['checked' => false];
                        },
                        'multiple' => true,
                        'expanded' => true,
                        'data' => null
                    ])
                
                ->add('save', SubmitType::class, ['label' => 'Save'])
        ;

        $builder->get('roles')
            ->addModelTransformer(new CallbackTransformer(
                function ($transform) {
                    return $transform;
                },
                function ($reverseTransform) {
                    $ret = array();

                    foreach($reverseTransform as $obj)
                    {
                        $ret[] = $obj->getRole();
                    }
                    return $ret;
                }
            ))
        ;

        $builder->getForm();
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }

}




Aucun commentaire:

Enregistrer un commentaire