You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Symfony中获取URL参数id并将其识别为question_id

具体修改方案

1. 调整控制器代码

首先你需要从URL查询参数中获取id值作为question_id,将对应问题关联到新建的回答实体上,修改后的控制器代码如下:

/**
 * Create action.
 *
 * @param \Symfony\Component\HttpFoundation\Request $request          HTTP request
 * @param \App\Repository\AnswerRepository          $answerRepository Answer repository
 * @param \App\Repository\QuestionRepository        $questionRepository Question repository
 *
 * @return \Symfony\Component\HttpFoundation\Response HTTP response
 *
 * @throws \Doctrine\ORM\ORMException
 * @throws \Doctrine\ORM\OptimisticLockException
 *
 * @Route(
 *     "/create",
 *     methods={"GET", "POST"},
 *     name="answer_create",
 * )
 */
public function create(Request $request, AnswerRepository $answerRepository, QuestionRepository $questionRepository): Response
{
    $answer = new Answer();
    // 从URL查询参数获取question_id
    $questionId = $request->query->get('id');
    // 校验参数合法性
    if (!$questionId || !is_numeric($questionId)) {
        throw $this->createNotFoundException('无效的问题ID');
    }
    // 查询对应问题实体
    $question = $questionRepository->find($questionId);
    if (!$question) {
        throw $this->createNotFoundException('指定问题不存在');
    }
    // 关联问题到回答
    $answer->setQuestion($question);

    $form = $this->createForm(AnswerType::class, $answer);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $answerRepository->save($answer);
        $this->addFlash('success', 'answer_created_successfully');
        // 可选:提交后跳转回问题详情页,体验更友好
        return $this->redirectToRoute('question_show', ['question_id' => $questionId]);
        // 原来的跳转逻辑保留也可以
        // return $this->redirectToRoute('answer_index');
    }

    return $this->render(
        'answer/create.html.twig',
        [
            'form' => $form->createView(),
            'question' => $question,
            'question_id' => $questionId
        ]
    );
}

2. 修改模板代码

需要给表单提交地址带上id参数,避免POST提交时丢失question_id,同时调整模板中用到的变量:

{% extends 'base.html.twig' %}

{% block title %}
    {{ 'title_answer_create'|trans ({'%id%': question.id|default('')})}}
{% endblock %}

{% block body %}
    <h1>{{ 'title_answer_create'|trans }}</h1>
    {# 提交地址带上question_id参数 #}
    {{ form_start(form, { method: 'POST', action: url('answer_create', {'id': question_id}) }) }}
    {{ form_widget(form) }}
    <div class="form-group row float-sm-right">
        <input type="submit" value="{{ 'action_save'|trans }}" class="btn btn-primary" />
    </div>
    <div class="form-group row float-sm-left">
        <a href="{{ url('question_show', {'id': question_id}) }}" class="btn btn-link">
            {{ 'action_back_to_question'|trans }}
        </a>
        {# 原来的返回列表按钮可以保留 #}
        {# <a href="{{ url('question_index') }}" class="btn btn-link">
            {{ 'action_back_to_list'|trans }}
        </a> #}
    </div>
    {{ form_end(form) }}
{% endblock %}

更规范的可选优化

推荐你把路由参数改成路径参数而非查询参数,更符合RESTful规范,只需要修改路由注解即可:

/**
 * @Route(
 *     "/create/{question_id}",
 *     methods={"GET", "POST"},
 *     name="answer_create",
 * )
 */
public function create(Request $request, AnswerRepository $answerRepository, QuestionRepository $questionRepository, int $question_id): Response
{
    // 这里就不需要自己从query里取id了,Symfony会自动把路径里的question_id参数注入
    $question = $questionRepository->find($question_id);
    // 其余逻辑和上面一致
}

修改后对应的访问路径变为localhost:8000/answer/create/254,生成路由的时候也只需要传question_id参数即可。

内容的提问来源于stack exchange,提问作者Harizu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:39:04