Sunday, 7 July 2019

Symfony Form to store a selection of User Interests to UserInterests

My aim is to use a Symfony Form to allow a user to choose multiple interests and save these relationally against their user.

I have three entities to map and store this data:

User
 - id
 - name

Interest
 - id
 - name

UserInterest
 - id
 - user_id (FK ManyToOne user.id)
 - interest_id (FK ManyToOne interest.id)

I'm struggling to find the most dynamic Symfony way to process and save the Interests of a User to the UserInterest entity.

InterestsController.php

public function interests(Request $request)
{
    $error = null;

    $userInterests = new UserInterest();
    $userInterests->setUser($this->getUser());

    $form = $this->createForm(UserAccountInterests::class, $userInterests);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        try {
            $this->entityManager->persist($userInterests);
            $this->entityManager->flush();
    } catch (\Exception $e) {
            $error = $e->getMessage();
        }
    }

    $parameters = [
        'error' => $error,
        'user_interests_form' => $form->createView()
    ];

    return $this->render('user/interests.html.twig', $parameters);
}

UserInterestsType.php

class UserInterestsType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    $builder
        ->add('interest', EntityType::class, [
            'class' => Interest::class,
            'choice_label' => 'name',
            'expanded' => true,
            'multiple' => true
        ])
        ->add('update', SubmitType::class);
    }
 }

The problem

The issue I'm facing at the moment is that upon form submission this creates an instantiation of the UserInterest entity linked to a user but with multiple selected Interest as an array and not multiple UserInterest.

How can I do this in the proper Symfony way to allow for one form and simple controller logic so the user can load the page, select their interests from a multiple checkbox type, click save and then when the form is reloaded they are auto populated as prior selection?



from Symfony Form to store a selection of User Interests to UserInterests

No comments:

Post a Comment