Welcome Guest, Not a member yet? Register   Sign In
Validation div always appears in view even if empty

I'm quite new to CodeIgniter and website development in general.
I'm following various tutorials and examples as well the official documentation, however I'm having some difficulties with displaying validation errors in my view.
Here's my controller section related to validation of a form input:
PHP Code:
public function add()

$model = new ReportModel();

 if (!
            'modello'  => 'required|numeric',
            'matricolaStruttura' => 'alpha_numeric|max_length[10]',
            'matricolaCabina'  => 'alpha_numeric|max_length[10]',
            'matricolaPorta'  => 'alpha_numeric|max_length[10]',
            'difetto' => 'required|numeric',
            'responsabile' => 'required|numeric',

and here's my view where I want to show validation errors if they happen:
PHP Code:
<?php $validation = \Config\Services::validation(); ?>
    <?php if ($validation): ?>
      <div class="alert alert-danger" role="alert">
        <?= $validation->listErrors() ?>
    <?php endif; ?>

in this case the result is that whenever I reach the view (even if post action has not been sent) I see the "alert div" block obviously empty of content. Of course I want it to be empty in that case.
If I remove the line
PHP Code:
<?php $validation = \Config\Services::validation(); ?>
what happens is that I get CI error of undefined $validation variable. I expect that the $validation variable is passed to the view with the option, but it seems not working.
PHP Code:
The code I wrote was extracted from this tutorial: https://makitweb.com/crud-create-read-up...igniter-4/ however I don't want to show errors in each form cell but in a div at top of the form.

Any suggestion? What's the best practice to have the validation errors shown as I want to?
Thanks in advance


PHP Code:

And in the view:

PHP Code:
<?php $errors session()->getFlashdata('errors'); ?>
    <?php if ($errors): ?>
      <div class="alert alert-danger" role="alert">
        <?= $errors ?>
    <?php endif; ?>

Theme © iAndrew 2016 - Forum software by © MyBB