Azrik
Azrik

Reputation: 3

Set a default value in form only if my user hasrole : ROLE_USER [symfony 4]

I have a reporting request form. I would like the administrator to create a request for a user if needed.

So I have a field that will either be blocked if the user has a certain user role or the field will be opened if the user has an admin role.

DemandType.php

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('applicant', EntityType::class, array(
                'class' => User::class,
                'choice_label' => 'username',
                'query_builder' => function(EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->orderBy('u.username', 'ASC');
                },
            ))
            ->add('date', DateType::class, array(
                'format' => 'dd MMM yyyy',
                'disabled' => true,
            ))
            ->add('type', ChoiceType::class, array(
                'choices' => array(
                    'Demande de Reporting' => 'Reporting récurrent',
                    'Demande One Shot' => 'Reporting One Shot',
                ),
                'multiple' => false,
                'required' => true,
            ))
            ->add('dateDelivery', DateType::class, array(
                'format' => 'dd MMM yyyy',
            ))
            ->add('synthesis', TextareaType::class, array(
                'attr' => array(
                    'rows' => '3'
                ),
            ))
        ;
    }

DemandController.php

    public function create(Request $request, ObjectManager $em, UserRepository $repo)
    {
        $demand = new Demand();

        $users = $repo->findAll();

        $form = $this->createForm(DemandType::class, $demand);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em->persist($demand);
            $em->flush();

            $this->addFlash('success', 'Demande bien enregistrée');

            return $this->redirectToRoute('demand_show', array(
                'slug' => $demand->getSlug(),
            ));

        } elseif ($form->isSubmitted() && !$form->isValid()) {
            $this->addFlash('danger', 'Erreur lors de la validation du formulaire');
        }

        return $this->render('demand/new.html.twig', array(
            'form' => $form->createView(),
            'users' => $users
        ));
    }

newDemand.html.twig

{% if is_granted('ROLE_ADMIN') %}
    <div class="form-group row">
        {{ form_label(form.applicant, 'Demandeur * :', {'label_attr': {'class': 'col-sm-4 col-form-label'}}) }}
        <div class="col-sm-3">
            {{ form_widget (form.applicant, {'attr': {'class': 'form-control'}}) }}
        </div>
    </div>
{% else %}
    <div class="form-group row">
        {{ form_label(form.applicant, 'Demandeur * :', {'label_attr': {'class': 'col-sm-4 col-form-label'}}) }}
        <div class="col-sm-3">
            {{ form_widget (form.applicant, {'attr': {'value':app.user.username, 'disabled':'disabled', 'class': 'form-control'}}) }}
        </div>
    </div>
{% endif %}

I would like, if user have ROLE_USER the fields applicant was disable and show the name of user and if the user have ROLE_ADMIN the fields show all user available in database. for this second parts it's ok an admin can attribute a demand to an other user.

Now i would like to force a value app.user.username in widget demand.applicant for user with ROLE_USER.

Upvotes: 0

Views: 84

Answers (1)

Rawburner
Rawburner

Reputation: 1395

My suggestion: introduce a new option in DemandType like this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title');
    if($options['is_admin']){
        $builder->add('applicant', EntityType::class, array(
            'class' => User::class,
            'choice_label' => 'username',
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('u')
                    ->orderBy('u.username', 'ASC');
            },
        ))
    }
    $builder->add('date', DateType::class, array(
            'format' => 'dd MMM yyyy',
            'disabled' => true,
        ))
        ->add('type', ChoiceType::class, array(
            'choices' => array(
                'Demande de Reporting' => 'Reporting récurrent',
                'Demande One Shot' => 'Reporting One Shot',
            ),
            'multiple' => false,
            'required' => true,
        ))
        ->add('dateDelivery', DateType::class, array(
            'format' => 'dd MMM yyyy',
        ))
        ->add('synthesis', TextareaType::class, array(
            'attr' => array(
                'rows' => '3'
            ),
        ))
    ;
}

public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                //add this param to the rest if you have this block already
                'is_admin' => false
            ]
        );
    }

Then in cotroller you are able to pass the admin flag to DemandType:

public function create(Request $request, ObjectManager $em, UserRepository $repo)
{
    $demand = new Demand();

    $users = $repo->findAll();
    //Change here
    $form = $this->createForm(DemandType::class, $demand, ['is_admin' => $this->isGranted('ROLE'ADMIN')]);
    //Change end
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        //Change here
        if(!$this->isGranted('ROLE'ADMIN')){
            $demand->setApplicant($this->getUser());
        }
        //Change end
        $em->persist($demand);
        $em->flush();

        $this->addFlash('success', 'Demande bien enregistrée');

        return $this->redirectToRoute('demand_show', array(
            'slug' => $demand->getSlug(),
        ));

    } elseif ($form->isSubmitted() && !$form->isValid()) {
        $this->addFlash('danger', 'Erreur lors de la validation du formulaire');
    }

    return $this->render('demand/new.html.twig', array(
        'form' => $form->createView(),
        'users' => $users
    ));
}

Twig:

{% if is_granted('ROLE_ADMIN') %}
    <div class="form-group row">
        {{ form_label(form.applicant, 'Demandeur * :', {'label_attr': {'class': 'col-sm-4 col-form-label'}}) }}
        <div class="col-sm-3">
            {{ form_widget (form.applicant, {'attr': {'class': 'form-control'}}) }}
        </div>
    </div>
{% else %}
    <div class="form-group row">
        <label class="col-sm-4 col-form-label">Demandeur</label>
        <div class="col-sm-3">
            {{app.user.username}}
        </div>
    </div>
{% endif %}

Upvotes: 1

Related Questions