Home > Back-end >  Codeigniter 4 - Validation messages are not displayed correctly
Codeigniter 4 - Validation messages are not displayed correctly

Time:08-16

I decided to put the validations and messages inside the HunterModel.php model. My createHunter() method inside the HunterController.php file should insert a record.

The following snippet shows the problem i'm having: Apparently $this->$data->listError();, doesn't reveal the message (or messages) i defined in $validationMessages.

  • HunterModel.php
    // Validation
    protected $validationRules      = [
        'name_hunter' => 'required|max_length[30]',
        'age_hunter' => 'required|integer',
        'height_hunter' => 'required|decimal',
        'weight_hunter' => 'required|decimal',
        'type_hunter' => 'required|max_length[30]',
        'type_nen' => 'required|max_length[30]',
        'type_blood' => 'required|max_length[3]'
    ];
    protected $validationMessages   = [
        'name_hunter' => [
            'required' => 'Hunter name cannot be empty.',
            'max_length' => 'The hunter name must have a maximum of 30 characters.'
        ],
        'age_hunter' => [
            'required' => 'Hunter age cannot be empty.',
            'integer' => 'The hunter's age must be an integer.'
        ],
        'height_hunter' => [
            'required' => 'Hunter height cannot be empty.',
            'decimal' => 'The hunter height must be a decimal number.'
        ],
        'weight_hunter' => [
            'required' => 'Hunter weight cannot be empty.',
            'decimal' => 'The hunter weight must be a decimal number.'
        ],
        'type_hunter' => [
            'required' => 'It is necessary to define the type of hunter.',
            'max_length' => 'The hunter type must be a maximum of 30 characters.'
        ],
        'type_nen' => [
            'required' => 'It is necessary to define the nen of the hunter.',
            'max_length' => 'The hunter's nen must have a maximum of 30 characters.'
        ],
        'type_blood' => [
            'required' => 'It is necessary to define the hunter's blood type.',
            'max_length' => 'The hunter's blood type must be a maximum of 3 characters.'
        ]
    ];
  • HunterController.php
    public function createHunter()
    {
        try {
            $hunter = new HunterModel();
            $data = [
                'name_hunter' => $this->request->getPost('name_hunter'),
                'age_hunter' => $this->request->getPost('age_hunter'),
                'height_hunter' => $this->request->getPost('height_hunter'),
                'weight_hunter' => $this->request->getPost('weight_hunter'),
                'type_hunter' => $this->request->getPost('type_hunter'),
                'type_nen' => $this->request->getPost('type_nen'),
                'type_blood' => $this->request->getPost('type_blood')
            ];
            if ($hunter->insert($data)){
                return $this->response->redirect(site_url('/read_hunters'));
            } else {
                $this->$data->listError();
            }
        } catch (\Exception $e) {
            exit($e->getMessage());
        } 
    }

CodePudding user response:

Create Validations.php in Libraries folder if it's does not exist.

Validations.php must be like:

<?php

namespace App\Libraries;

class Validations
{
   public $hunter = [
      'rules' => [
          'name_hunter' => 'required|max_length[30]',
          //other rules...
      ],
      'error' => [
          'name_hunter' => [
               'required' => 'Hunter name cannot be empty.',
               'max_length' => 'The hunter name must have a maximum of 30 characters.'
          ],
          //other error messages....
      ]
   ];
}

HunterController.php must be like:

<?php

namespace App\Controllers;

use App\Libraries\Validations;

class HunterController extends BaseController
{

public function __construct()
{
    $this->validator = new Validations();
}

public function createHunter()
{

    $response = [];
    $val = $this->validate(
         $this->validator->hunter['rules'],
         $this->validator->hunter['error']
    );
    if (!$val) {
        $response = [
           'success' => false,
            'msg' => addslashes((preg_replace('/\s /', ' ', $this->validation->listErrors())))
        ];
    }else {
        try {
        $hunter = new HunterModel();
        $data = [
            'name_hunter' => $this->request->getPost('name_hunter'),
            'age_hunter' => $this->request->getPost('age_hunter'),
            'height_hunter' => $this->request->getPost('height_hunter'),
            'weight_hunter' => $this->request->getPost('weight_hunter'),
            'type_hunter' => $this->request->getPost('type_hunter'),
            'type_nen' => $this->request->getPost('type_nen'),
            'type_blood' => $this->request->getPost('type_blood')
        ];
        if ($hunter->insert($data)){
            return redirect()->to(site_url('/read_hunters'));
        } else {
            $response = [
               'success' => false,
                'msg' => //your custom error message
            ];
        }
    } catch (\Exception $e) {
        exit($e->getMessage());
    } 
    //if you are using ajax
    return $this->response->setJSON($response);
}
}
  • Related