简体   繁体   English

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

[英]Symfony 4 forms - Variable form does not exist

Using Symfony 4 to build a support ticket form:使用 Symfony 4 构建支持工单表单:

Created route and functions in page controller在页面控制器中创建路由和函数

/**
 * @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(),
    ));
}

And then render the form in the twig template:然后在 twig 模板中渲染表单:

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

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

When I load the page I get a Symfony error stating that "Variable form does not exist".当我加载页面时,我收到一个 Symfony 错误,指出“变量形式不存在”。

I have followed the documentation https://symfony.com/doc/current/forms.html .我遵循了文档https://symfony.com/doc/current/forms.html Where/how can I find the issue?我在哪里/如何找到问题?

I assume you get this error while accessing "/support/ticket"我假设您在访问“/support/ticket”时遇到此错误

You have "form" variable missing in this function此函数中缺少“表单”变量

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

I will suggest to wrap your code in twig template in a "if" block我会建议将您的代码包装在“if”块中的树枝模板中

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

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

Or you need to adjust your controller functions accordingly或者您需要相应地调整控制器功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM