0

我有一个表单,它根据从数据库中查找获取请求的 id 值加载。

$Id = $request->query->get('id');

if (!empty($Id) && $Id != 'add') {
    $search = $this->getDoctrine()
        ->getRepository(Clients::class)
        ->find($Id);

    if (is_null($search))
        $this->addFlash('danger', 'Invalid Client');
    else
        $form = $this->createForm(ClientViewType::class,$search);
}
else {
    $form = $this->createForm(ClientViewType::class);
}

您可以看到我正在添加“无效客户端”的 flashbag 消息,但问题是表单仍会显示。有什么办法不显示表格吗?基本上我只想显示 flashbag 消息,仅此而已。

我尝试了一些事情——即将$form 设置为null,只返回页面,没有表单等,但这只会导致其他问题。

4

4 回答 4

0

写这个:

if (is_null($search)) {
    $this->addFlash('danger', 'Invalid Client');
    return $this->render("...", [
       "form" => null
        ...
    ]);
}

然后在 twig 文件中进行以下 if 条件:

{% if form is not null %}
    {{ form_start(form) }}
         {{ form_widget(form) }}
    {{ form_end(form) }}
{% endif %}
于 2018-09-26T20:55:02.553 回答
0

尝试使用 instanceof 代替。

if ($search instanceof Clients) {...}

这帮助我克服了其中一些问题。

我同意其他答案,尤其是 iiirxs'。

于 2018-09-27T00:45:16.627 回答
0

您可以将 not Famouselse子句与for条件一起使用

{% for message in app.flashes('danger') %}
    <div class="flash-notice">
        {{ message }}
    </div>
{% else %}
   {# your form #}
{% endfor %}

文档

于 2018-09-26T22:37:56.437 回答
0

当您的客户端无效时,您确实应该将 $form 设置为 null。然后在你的树枝中,你可以有这样的条件渲染:

{% if form is not null %}
    {{ form_start(form) }}
        {{ form_widget(form) }}
    {{ form_end(form) }}
{% else %}
    {% for message in app.flashes('danger') %}
        <div class="flash-notice">
            {{ message }}
        </div>
    {% endfor %}
{% endif %}
于 2018-09-26T17:19:44.200 回答