John O'Grady
John O'Grady

Reputation: 245

Bind field on Symfony form to Parameter

I have a new (create) method for a roster entity and want to navigate to this method from a different service user entity passing the service user as a parameter. I then want to set the serviceUserId of the roster to the ID of the service user object.

My controller method routes ok from the service user entity to the roster and passes the service user object to the form correctly.

/**
     * Creates a new roster entity.
     *
     * @Route("/newfromsu/serviceUser={serviceUser}", name="roster_new_su")
     * @Method({"GET", "POST"})
     */
    public function newActionfromServiceUser(Request $request, ServiceUser $serviceUser)
    {
        $roster = new Roster();
        $form = $this->createForm('AppBundle\Form\RosterType', $roster);
        $form->handleRequest($request);


        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($roster);
            $em->flush($roster);

            return $this->redirectToRoute('roster_show', array('id' => $roster->getId()));
        }

        return $this->render('roster/newfromsu.html.twig', array(
            'roster' => $roster,
            'serviceUser'=>$serviceUser
        ,'form' => $form->createView(),
        ));
    }

The new roster template page and RosterType classes are currently as created by defaulted using the templated code

   {% extends '_base.html.twig' %}

{% block body %}
    {{ dump() }}
    <h1>Roster creation</h1>

    {{ form_start(form) }}
    {{ form_widget(form) }}
    <input type="submit" value="Create" />
    {{ form_end(form) }}

    <ul>
        <li>
            <a href="{{ path('roster_index') }}">Back to the list</a>
        </li>
    </ul>
{% endblock %}

and

    class RosterType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('serviceUserId')->add('rosterStartTime')->add('rosterEndTime')->add('rosterStatus')->add('numberResourcesNeeded')->add('customerId');

    }

My question: How can I set the serviceUserId value in the new form to ID of the incoming serviceUser object

Can I do this in the formBuilder or do I need to manually create a Twig form which lists each attribute and binds the relevant control there.

Thanks!

Upvotes: 1

Views: 582

Answers (1)

Frank B
Frank B

Reputation: 3697

The third parameter of the Controller::createForm function is an array with options.

$form = $this->createForm('AppBundle\Form\RosterType', $roster, array(
    'serviceUser' => $serviceUser
));

Now in the formType class you need to set a default value for $options['serviceUser']:

class RosterType extends AbstractType
{

    // ...

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Roster',
            'serviceUser' => NULL
        ));
    }
}

And now you are able to use the option in the buildForm method:

class RosterType extends AbstractType
{

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('serviceUserId', null, array(
                'data' => $options['serviceUser']
            ))
            ->add('rosterStartTime')
            ->add('rosterEndTime')
            ->add('rosterStatus')
            ->add('numberResourcesNeeded')
            ->add('customerId')
        ;

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Roster',
            'serviceUser' => NULL
        ));
    }
}

Upvotes: 3

Related Questions