Ab-Sadiq
Ab-Sadiq

Reputation: 31

Displaying Error Message in CodeIgniter 4

I am humbly seeking a help on how to go about displaying error message in CI4. i have create a controller like this:

public function login()
{
    $validation = \config\services::validation();

    $errors  = array('email' => 'bad email',
                'pass' => 'bad pass '); 


    if(!$this->validate(array('email' => 'required',
                         'pass' => 'required')))
    {
        echo view('login', array('validation' => $this->validator));
    }
    else
    {
        print 'success';
    }
}

while a tested each of the error reporting function below:

$validation->listErrors();
$validation->listErrors('list');
$validation->showError();
$validation->showError('sigle');
$validation->showError('email');

but non of these function work, if i entered correct data it print success as assign but upon wrong data it all show the same error message which is:

  1. Call to a member function listErrors() on null.
  2. Call to a memberfunction listErrors() on null.
  3. Call to a member function showError()on null.
  4. Call to a member function ShowError() on null.

Upvotes: 2

Views: 8756

Answers (1)

nadim achmad
nadim achmad

Reputation: 96

call form helper in your controller before your validation start

 helper('form');

and i re-arrange ur code like this

public function login()
    {
        $data = [
            'validation' => \config\services::validation()
        ];

        if ($this->request->getMethod() == "post") { // if the form request method is post
            helper('form');
            $rules = [
                'email' => [
                    'rules' => 'required',
                    'errors' => [
                        'required' => 'bad email'
                    ]
                ],
                'pass' => [
                    'rules' => 'required',
                    'errors' => [
                        'required' => 'bad pass'
                    ]
                ]
            ];

            if (!$this->validate($rules)) {
                echo view('login', array('validation' => $this->validator));
            } else {
                // whatever you want todo 
            }
        }

        echo view('login', $data);
    }

in your login view, if you want to call all error list you got use this method $validation->listErrors();

if you want to call a specific error use this method $validation->listErrors('email');

if you want to check is the specific field returning an error use this method $validation->hasError('email'))

i hope this help you to solve your problem

Upvotes: 1

Related Questions