Форма заменяет мою переменную в Symfony 4

Я хочу обновить список пользователей сущности под названием SAI, но после отправки формы я теряю информацию о SAI, которую я хочу обновить, и она заменяется SAI, возвращаемым формой.

Я попытался объяснить, что происходит с комментариями в следующем коде:

EdditSAIController.php

/**
 * @Route("/edit_sai/{id}/", name="edit_sai", requirements={"page"="\d+"}))
 * @Method({"GET"})
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function editSAI(Request $request)
{
    $entityManager = $this->getDoctrine()->getManager();
    $idSAI = $request->attributes->get('id_sai'); //Get the ID of the SAI from the link
    $sai = $this->getDoctrine()->getRepository(SAI::class)->find($idSAI); //Find the SAI in the database
    $oldUsers = $sai->getUsers(); //Get the users of the SAI
    $form = $this->createForm(SAIType::class,$sai); //Create the form, which includes a serial number and a list of users that you can modify, by adding or removing users
    $form->handleRequest($request);

    if ($form->isSubmitted()) {

        $newSAI = $form->getData(); //Get the data of the new SAI
        $sai->setSerialNumber($newSAI->getSerialNumber()); //Update the serial number
        $usersToAdd = $newSAI->getUsers();

        //If the old users are not in the list of users of the SAI returned by the form, it means that they got removed and
        //I have to remove them from the current SAI
        //(this is where the problem starts, since $oldUsers now contains the same users as the $newSAI, and I don't know why)
        //(and of course both of these loops won't work because $oldUsers and $usersToAdd contain the same data)
        foreach($oldUsers as $oldUser){
            if (!$usersToAdd->contains($oldUser)){
                $sai->deleteUser($oldUser);
            }
        }

        //Add the new users to the current SAI
        foreach($usersToAdd as $newUser){
            $sai->addUser($newUser);
        }

        //Update SAI
        $entityManager->persist($sai);
        $entityManager->flush();

        return $this->redirectToRoute('sais');
    }

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

edit_sai.html.twig

{%  extends 'home/index.html.twig' %}

{%  block body %}

<div class="main">
    <h1>Editar SAI</h1>
    <hr>
    <div class="formUsers">
        {{ form_start(form) }}
        {{ form_end(form) }}
    </div>
</div>

{%  endblock %}

{% block javascripts %}
{{ parent() }}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script> $('select[data-select="true"]').select2({}); </script>
{% endblock %}

Любая идея о том, что я делаю неправильно и что я должен сделать, чтобы решить это? Благодарю.

1 ответ

Решение

Наконец-то я понял, что было не так.
Как сказал в комментарии Дениз Актюрк, достаточно было использовать:

if ($form->isSubmitted()) {
    //Update SAI
    $entityManager->persist($sai);
    $entityManager->flush();
}

Но проблема заключалась в именах моих функций:
- В классе User.php у меня был delteSAI() вместо removeSAI ().
- В классе SAI.php у меня была deleteUser() вместо removeUser().

Я также добавил cascade={"persist", "remove"} в оба класса:

User.php

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\SAI", inversedBy="users", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="users_sais")
 */
private $sais;  

SAI.php

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\User", mappedBy="sais", cascade={"persist", "remove"})
 */
private $users;

Я понятия не имел, что Symfony4 так строго относится к именованию функций. Надеюсь, это кому-нибудь поможет.

Другие вопросы по тегам