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

Hi,
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()
 {
 
helper('form');

 
$model = new ReportModel();

 if (!
$this->validate([
            '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',
        ]))
{
 return 
redirect()->to('defect')->withInput()->with('validation',$this->validator);
}
else 
[...] 

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() ?>
      </div>
    <?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:
withInput()->with('validation'$this->validator
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
Reply
#2

Try:

PHP Code:
->with('errors'$this->validator->listErrors()) 


And in the view:


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




Theme © iAndrew 2016 - Forum software by © MyBB