Symfony 表单 - 仅当我输入表单时清除会话变量

Symfony Form - clear session variable only when I enter the form

我只想在第一次进入 symfony 表单时清除会话变量。在此示例中,即使表单无效,会话也会被删除 - 我该如何更改?

public function dodajNewAction(Request $request, Pacjent $pacjent)
{
    unset($_SESSION['test']);

    $wykbad = new Wykbadpoz($pacjent);
    $wykbad->setRok(date('Y'));
    $wykbad->setMiesiac(date('n')); //miesiac bez zera wiodacego

    $form = $this->createForm('nfz_wykbadpoz_new', $wykbad);

    $form->handleRequest($request);

    return [
        'form' => $form->createView()
    ];
}

在 Symfony 项目中,你应该永远不要 使用像 $_SESSION ($_GET, $_POST, ...) 这样的超全局变量。您必须使用 Request 对象。

像这样:

public function dodajNewAction(Request $request, Pacjent $pacjent)
{
    $wykbad = new Wykbadpoz($pacjent);
    $wykbad->setRok(date('Y'));
    $wykbad->setMiesiac(date('n')); //miesiac bez zera wiodacego

    $form = $this->createForm('nfz_wykbadpoz_new', $wykbad);

    $form->handleRequest($request);

    $session = $request->getSession();
    if ($form->isValid() && $session->has('test')) {
        $session->remove('test');
    }

    return [
        'form' => $form->createView()
    ];
}