Hello,
I'm giving v4 a try after loving v3 for a long time.
I'm really impressed by the new REST features built in but i have a problem. (or lack of knowledge)
If i have a following validation rules in my model:
PHP Code:
<?php
namespace App\Models;
use CodeIgniter\Model;
class CompaniesModel extends Model
{
protected $table = 'companies';
protected $primaryKey = 'company_number';
protected $returnType = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['company_number', 'address_line_1', 'address_line_2', 'town', 'post_code'];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [
'company_number' => 'required|min_length[8]|max_length[10]|is_unique[companies.company_number,company_number,{company_number}]',
'address_line_1' => 'required|max_length[64]',
'address_line_2' => 'max_length[64]',
'town' => 'required|max_length[64]',
'post_code' => 'required|max_length[8]',
];
protected $validationMessages = [
'company_number' => [
'is_unique' => 'The company number provided already exists in the system.'
]
];
protected $skipValidation = false;
protected function beforeInsert(array $data){
$data['data']['country'] = "GB";
return $data;
}
protected function beforeUpdate(array $data){
//print_r($data); die;
return $data;
}
}
This works great for inserts but i get the
is_unique error when I try to do an update, luckily theres a feature to feature to fix that
PHP Code:
is_unique[companies.company_number,company_number,{company_number}]
But then insert breaks with a mysql error
Code:
Duplicate entry '77777777' for key 'company_number'
Is there a way to
easily fix this or have different validation rules for the 2 different requests ?
something like this maybe ?
PHP Code:
protected function beforeUpdate(array $data){
$this->validationRules['company_number'] = 'required|min_length[8]|max_length[10]|is_unique[companies.company_number,company_number,{company_number}]';
$data['data']['country'] = "GB";
return $data;
}