I have a form which loads based on a lookup from the database of a id value from a get request.
$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);
}
You can see I'm adding a flashbag message of 'invalid client', but the problem is the form will still show. Is there some way to not show the form? Basically I just want the flashbag message to display and that's it.
I tried some things - i.e. setting $form to null, just returning the page, without the form, etc. but that just forces other problems.
You should indeed set $form to null when you have an invalid client. Then in your twig you could have a conditional rendering like this:
{% 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 %}
Write this:
if (is_null($search)) {
$this->addFlash('danger', 'Invalid Client');
return $this->render("...", [
"form" => null
...
]);
}
and then in twig file make following if condition:
{% if form is not null %}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
{% endif %}
You can use the not famous else
clause with the for
condition
{% for message in app.flashes('danger') %}
<div class="flash-notice">
{{ message }}
</div>
{% else %}
{# your form #}
{% endfor %}
see documentation
Try using instanceof instead.
if ($search instanceof Clients) {...}
This helped me to overcome some of those problems.
I agree with the other answers, especially iiirxs'.