Symfony 4.1.4 isSubmitted()在渲染形式上不起作用

时间:2018-09-24 14:16:05

标签: php symfony

所以我有这个简单的表格:

    class CreditType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('credits', EntityType::class, [
            'class' => Product::class,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('product')
                          ->orderBy('product.amount');
            },
            'expanded' => true,
            'choice_label' => function ($key) {
                return $key->amount.' credits voor maar '.$key->price;
            }
        ]);
    }
}
我在以下控制器中使用的

public function credits(Request $request)
{
    $form = $this->createForm(CreditType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted()) {
        throw new \Exception('It works!');
    }
    return $this->render(
        'credits/credits_widget.html.twig',
        [
            'form' => $form->createView(),
        ]
    );
} 

并在我的XXX.html.twig中使用它

{{ render(controller('App\\Controller\\DetailsController:credits')) }}

我已经和symfony一起工作了四个星期,所以没那么长。

我只想在提交表单时不调用我在if语句中放置的任何内容时调用某些函数,它现在不会引发任何异常。呈现表单时我看不到东西吗?还是不能这样做?

编辑: 我的credits_widget.html.twig

{% block credits %}
        {{ form_start(form.credits) }}
        {{ form_widget(form.credits) }}

        {% if app.user %}
            <button type="submit">Koop nu!</button>
        {% else %}
            <a href="#login-form"><button type="button">Login en koop</button></a>
            <a href="{{ path('user_registration') }}"><button type="button">Registreer en koop</button></a>
        {% endif %}
        {{ form_end(form.credits) }}
{% endblock %}

1 个答案:

答案 0 :(得分:0)

问题在于表单是不进行任何操作而呈现的,并且在提交时默认情况下将其提交到呈现该表单的根路径。因此,并未调用功劳行动。您应该像这样更改表单的操作:

public function credits(Request $request)
{
    // set current url path as form's action 
    $form = $this->createForm(CreditType::class, null, , [
        'action' => $request->getRequestUri()
    ]);

    $form->handleRequest($request);

    if ($form->isSubmitted()) {
        throw new \Exception('It works!');
    }
    return $this->render(
        'credits/credits_widget.html.twig',
        [
            'form' => $form->createView(),
        ]
    );
}

编辑:您当前正在渲染子表单form.credits,当您真正渲染从控制器传递来的表单时。您的credits_widget.html.twig模板应如下所示:

{% block credits %}
        {{ form_start(form) }}
            {{ form_widget(form) }}

            {% if app.user %}
                <button type="submit">Koop nu!</button>
            {% else %}
                <a href="#login-form"><button type="button">Login en koop</button></a>
                <a href="{{ path('user_registration') }}"><button type="button">Registreer en koop</button></a>
            {% endif %}
        {{ form_end(form) }}
{% endblock %}