Symfony 4 - 如果数据库查找失败,如何避免呈现表单?
Symfony 4 - How to avoid rendering the form if database lookup fails?
我有一个表单,它基于从数据库中查找来自 get 请求的 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);
}
您可以看到我正在添加一个 'invalid client' 的 flashbag 消息,但问题是表格仍然会显示。有什么办法可以不显示表格吗?基本上我只想显示 flashbag 消息,仅此而已。
我尝试了一些方法——即将 $form 设置为 null,只返回页面,不带表单等,但这只会导致其他问题。
当您的客户端无效时,您确实应该将 $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 %}
这样写:
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 %}
您可以在 for
条件下使用 not famous else
子句
{% for message in app.flashes('danger') %}
<div class="flash-notice">
{{ message }}
</div>
{% else %}
{# your form #}
{% endfor %}
尝试改用 instanceof。
if ($search instanceof Clients) {...}
这帮助我克服了其中的一些问题。
我同意其他答案,尤其是 iiirxs'。
我有一个表单,它基于从数据库中查找来自 get 请求的 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);
}
您可以看到我正在添加一个 'invalid client' 的 flashbag 消息,但问题是表格仍然会显示。有什么办法可以不显示表格吗?基本上我只想显示 flashbag 消息,仅此而已。
我尝试了一些方法——即将 $form 设置为 null,只返回页面,不带表单等,但这只会导致其他问题。
当您的客户端无效时,您确实应该将 $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 %}
这样写:
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 %}
您可以在 for
条件下使用 not famous else
子句
{% for message in app.flashes('danger') %}
<div class="flash-notice">
{{ message }}
</div>
{% else %}
{# your form #}
{% endfor %}
尝试改用 instanceof。
if ($search instanceof Clients) {...}
这帮助我克服了其中的一些问题。
我同意其他答案,尤其是 iiirxs'。