Symfony 4表单 - 不存在变量形式

问题描述 投票:0回答:1

使用Symfony 4构建支持票证表单:

在页面控制器中创建路径和功能

/**
 * @Route("/support/ticket")
 */
public function ticket(){
    return $this->render('support/ticket/ticket.html.twig');
}
public function new(Request $request)
{
    // creates a Ticket and gives it some dummy data for this example
    $ticket = new Ticket();

    $form = $this->createFormBuilder($ticket)
        ->add('category', ChoiceType::class, array(
            'choices' => array(
                'ROMAC eHR' => 1,
                'ROMAC Website' => 2,
                'ROMAC Guide' => 3,
            )
        ))
        ->add('comment', TextareaType::class)
        ->add('save', SubmitType::class, array('label' => 'Submit Ticket'))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // $form->getData() holds the submitted values
        // but, the original `$task` variable has also been updated
        $ticket = $form->getData();

        // ... perform some action, such as saving the task to the database
        // for example, if Ticket is a Doctrine entity, save it!
        // $entityManager = $this->getDoctrine()->getManager();
        // $entityManager->persist($task);
        // $entityManager->flush();

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

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

然后在twig模板中呈现表单:

        {{ form_start(form) }}
        {{ form_errors(form) }}

        {{ form_row(form.category) }}
        {{ form_row(form.comment) }}
        {{ form_end(form) }}

当我加载页面时,我得到一个Symfony错误,指出“变量形式不存在”。

我按照文档https://symfony.com/doc/current/forms.html。我在哪里/如何找到问题?

php forms symfony twig symfony-forms
1个回答
0
投票

我假设您在访问“/ support / ticket”时遇到此错误

您在此函数中缺少“form”变量

public function ticket(){
    return $this->render('support/ticket/ticket.html.twig');
}

我建议将代码包装在“if”块中的twig模板中

{% if form is defined %}
    {{ form_start(form) }}
    {{ form_errors(form) }}

    {{ form_row(form.category) }}
    {{ form_row(form.comment) }}
    {{ form_end(form) }}
{% endif %}

或者您需要相应地调整控制器功能

© www.soinside.com 2019 - 2024. All rights reserved.