Roman Newaza
Roman Newaza

Reputation: 11700

Adding related entities better way

How to implement adding related Role entities better way? It would be nice to keep it inside of a form if possible or maybe if I add a method to an User entity directly... Is there built-in mechanism for it or what patter shall I use?

public function add(Request $request)
{
    $data = $request->request->all();
    $user = new User();
    $form = $this->createForm(UserType::class, $user);
    $form->submit($data);
    if (false === $form->isValid()) {
        return $form;
    }
    $user = $form->getData();
    // Adding a Roles
    if (!empty($data['user_roles'])) {
        foreach ($data['user_roles'] as $value) {
            // Checking if a Role is present in DB
            $role = $this->getDoctrine()
                ->getRepository(Role::class)
                ->findOneBy(['role_name' => $value]);
            if ($role) {
                $user->setUserRole($role);
            }
        }
    }
    $this->em->persist($user);
    $this->em->flush();

    return new JsonResponse(
        [
            'status' => 'ok',
            'last_insert_id' => $user->getId(),
        ],
        JsonResponse::HTTP_CREATED
    );
}

Upvotes: 0

Views: 56

Answers (1)

J. Almandos
J. Almandos

Reputation: 347

I've always worked like that and I've never had a problem. In fact, I don't even use symfony's forms because they're not that flexible. The best way to do it is the one that you feel more comfortable with. Just be sure to be clean and consistent. Of course you can add a method to the User entity, but it's just a matter of modularization, that's not very necessary in this case.

Upvotes: 1

Related Questions