PHP Symfony如何使这个URL查询名称更用户友好

xsuvu9jc  于 2023-10-24  发布在  PHP
关注(0)|答案(1)|浏览(129)

我做了一个控制器类,一旦用户输入了值并提交了表单,它就会生成一个表单,我让它将表单值之一传递到URL中。
问题是它看起来像这样:
localhost/task/success?0=History
下面是我的控制器类的代码:

<?php

namespace App\Controller;

use App\Entity\Task;
use App\Form\TaskType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;

class TaskController extends AbstractController
{
    #[Route('/task', name: 'task')]
    public function taskForm(Request $request): Response
    {
        $task = new Task();

        $form = $this->createForm(TaskType::class, $task);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid())
        {
            return $this->redirectToRoute('task_success', (array)$task->getTask());
            //return $this->redirectToRoute('task_success'            (array)$request->request->get($task->getTask()));
        }

        return $this->render('Task/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }
    #[Route('/task/success', name:'task_success')]
    public function taskResult(Request $request): Response
    {
        $query = $request->query->get('0');
        return $this->render('Task/test.html.twig',[
            'task' => $query,
        ]);
    }
}

我怎样才能使它这样的查询是不是0=,所以它是说,在这种情况下,任务的文本字段的名称

cwdobuhd

cwdobuhd1#

您正在将$task->getTask()转换为数组,这将执行字符串到数组的转换,并创建一个索引为0的数组。
要解决此问题,您需要命名参数。

public function taskForm(Request $request): Response
{
// ...
    return $this->redirectToRoute('task_success', ['task' => $task->getTask()]);
// ...
}

然后可以获取查询参数task

public function taskResult(Request $request): Response
{
    $query = $request->query->get('task');
    // ...
}

相关问题