CodeIgniter Forums
CIv4 Call to a member function setRules() on null - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: CIv4 Call to a member function setRules() on null (/showthread.php?tid=79467)



CIv4 Call to a member function setRules() on null - pc87 - 06-20-2021

I am getting `Call to a member function setRules() on null error` while saving data.
I'm using codeigniter version 4.0.4 

Model Code:
PHP Code:
<?php

namespace App\Models;

use 
App\Models\BaseModel;

class 
EmploymentLetterModel extends BaseModel
{

    protected $table 'ci_employment_letters';

    protected $primaryKey 'letter_id';

    protected $allowedFields = ['letter_id''employee_id''address''country_id''state''city''zipcode''created_at'];

    protected $validationRules = [
        'employee_id' => 'required',
        'address' => 'required',
        'country_id' => 'required',
        'state' => 'required',
        'city' => 'required',
        'zipcode' => 'required',
    ];

    protected $validationMessages = [
        'employee_id' => [
            'required' => "The {field} field is required."
        ],
        'address' => [
            'required' => "The {field} field is required."
        ],
        'country_id' => [
            'required' => "The {field} field is required."
        ],
        'state' => [
            'required' => "The {field} field is required."
        ],
        'city' => [
            'required' => "The {field} field is required."
        ],
        'zipcode' => [
            'required' => "The {field} field is required."
        ],
    ];
    protected $skipValidation false;


BaseModel:
It is connecting to database based on subdomain, it is multi database tenancy application
PHP Code:
<?php

namespace App\Models;

use 
CodeIgniter\Database\Config;
use 
CodeIgniter\Model;

class 
BaseModel extends Model
{
    protected $db;
    protected $tempReturnType 'array';
    public function __construct()
    {
        if (isset($_SERVER['HTTP_HOST'])) {
            $basename config('App')->baseName;
            $subdomain str_replace($basename''$_SERVER['HTTP_HOST']);
            if ($subdomain) {
                $user = new \App\Models\SuperModel();
                $company $user->where('domain'$_SERVER['HTTP_HOST'])->first();
                if (!empty($company)) {
                    //$database = config('database');
                    $custom = [
                        'DSN'      => 'mysql:host=' $company['db_host'] . ';dbname=' $company['db_name'],
                        'hostname' => $company['db_host'],
                        'username' => $company['db_user'],
                        'password' => $company['db_password'],
                        'database' => $company['db_name'],
                        'DBDriver' => 'MySQLi',
                        'DBPrefix' => '',
                        'pConnect' => false,
                        'DBDebug'  => (ENVIRONMENT !== 'production'),
                        'charset'  => 'utf8',
                        'DBCollat' => 'utf8_general_ci',
                        'swapPre'  => '',
                        'encrypt'  => false,
                        'compress' => false,
                        'strictOn' => false,
                        'failover' => [],
                        'port'    => $company['db_port'],
                    ];

                    //\Config\Database::connect('company');
                    $this->db = \Config\Database::connect($custom);
                }
            }
        }
    }


Controller:
PHP Code:
<?php

namespace App\Controllers\Employee;

use 
App\Models\UsersModel;

use 
App\Controllers\BaseController;
use 
App\Models\EmploymentLetterModel;

class 
Employmentletter extends BaseController
{
    public $usession;
    public $user_info;
    public $employmentLetter;

    public function __construct()
    {
        $usersModel = new UsersModel();
        $session = \Config\Services::session();
        $this->usession $session->get('sup_username');
        $this->user_info $usersModel->where('user_id'$this->usession['sup_user_id'])->first();
        $this->employmentLetter = new EmploymentLetterModel();
    }

    public function add()
    {

        if ($this->request->getPost('type') === 'add_record') {
            $Return = ['result' => '''error' => '''csrf_hash' => ''];
            $Return['csrf_hash'] = csrf_hash();

            $data = [
                'employee_id' => $this->user_info['user_id'],
                'address' => $this->request->getPost('address'FILTER_SANITIZE_STRING),
                'country_id'  => $this->request->getPost('country_id'FILTER_SANITIZE_STRING),
                'state'  => $this->request->getPost('state'FILTER_SANITIZE_STRING),
                'city'  => $this->request->getPost('city'FILTER_SANITIZE_STRING),
                'zipcode'  => $this->request->getPost('zipcode'FILTER_SANITIZE_STRING),
                'created_at' => date('Y-m-d h:i:s')
            ];

            if ($this->employmentLetter->save($data) === false) {
                $ruleErrors $this->employmentLetter->errors();
                foreach ($ruleErrors as $err) {
                    $Return['error'] = $err;
                    if ($Return['error'] != '') {
                        exit(json_encode($Return));
                    }
                }
            } else {
                $Return['result'] = lang('Success.common_address_added');
            }
            exit(json_encode($Return));
        }
    }


Error Stack:
Code:
CRITICAL - 2021-06-21 02:41:40 --> Call to a member function setRules() on null
#0 D:\laragon\www\hrmsv4\system\Model.php(727): CodeIgniter\Model->validate(Array)
#1 D:\laragon\www\hrmsv4\system\Model.php(574): CodeIgniter\Model->insert(Array, false)
#2 D:\laragon\www\hrmsv4\app\Controllers\Employee\Employmentletter.php(74): CodeIgniter\Model->save(Array)
#3 D:\laragon\www\hrmsv4\system\CodeIgniter.php(918): App\Controllers\Employee\Employmentletter->add()
#4 D:\laragon\www\hrmsv4\system\CodeIgniter.php(404): CodeIgniter\CodeIgniter->runController(Object(App\Controllers\Employee\Employmentletter))
#5 D:\laragon\www\hrmsv4\system\CodeIgniter.php(312): CodeIgniter\CodeIgniter->handleRequest(NULL, Object(Config\Cache), false)
#6 D:\laragon\www\hrmsv4\index.php(45): CodeIgniter\CodeIgniter->run()
#7 {main}

Please help me to resolve this issue.


RE: CIv4 Call to a member function setRules() on null - ikesela - 06-21-2021

leaves this empty (maybe problem with your validation message, default CI4 validation message is already enough)
protected $validationMessages = [];

or you can easily set the custom validation message in app folder Language->en->validation.php


RE: CIv4 Call to a member function setRules() on null - paulbalandan - 06-22-2021

In your App\Models\BaseModel::__construct method, add this line as the very first line of your constructor.
PHP Code:
parent::__construct(); 

Please remember that whenever you extend a class that has a defined constructor method and you are defining your own constructor, you need to explicitly add that line in order to inherit the parent's initialization processes.