Home > other >  Codeigniter 4 model does not validate or updates $updatedField
Codeigniter 4 model does not validate or updates $updatedField

Time:06-03

This is my first time working with models in CI4. The below model works when fetching data, and also updating an excising record. But for some reason it does not validate any input data. I can leave the fields blank or fill them with a single character, they'd still update. Also when they update the $updatedField doesn't change (stays NULL).

<?php

namespace App\Models;

use CodeIgniter\Model;

class GroupsModel extends Model
{
    protected $DBGroup = 'default';
    protected $table      = 'auth_groups';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    protected $returnType     = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['name', 'description'];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules    = [
        'name'        => 'required|min_length[3]|is_unique[auth_groups.name]',
        'description'     => 'required|min_length[3]',
    ];

    protected $validationMessages = [
        'name'        => [
            'is_unique' => 'Name has to be unique',
        ],
    ];
    protected $skipValidation     = false;
}

Here's the relevant code in the controller:

                  $groupmodel=new GroupModel();
                $group = $groupmodel->find($_GET["id"]);
                if(is_null($group)){throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();}
                if($_SERVER['REQUEST_METHOD'] == 'POST'){$groupmodel->update($_GET["id"],$_POST);}
                helper('form');
                $data = [
                    'username'  =>  user()->username,
                    'title'    =>  'Groups',
                    'group'    =>  $group,
                    'errors'    =>  $groupmodel->errors(),
                ];
                echo view('panel/header', $data);
                echo view('panel/admin/group_edit', $data);
                echo view('panel/footer', $data); 

Here's the table:

    CREATE TABLE `auth_groups` (
  `id` int UNSIGNED NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL
)

Looking forward to your feedback!

CodePudding user response:

As @steven7mwesigwa attentively pointed out there was a typo in the controller calling the wrong (?) model. This solved everything!

I was calling GroupModel, but the model was called GroupsModel.

  • Related