I'm trying to get form validation to work at the model level. I have three fields, id, name and email, and I have them all set to required.
I'm using the CI 4 Entity class, so on an incoming request, I get the JSON, fill my new Entity on creation, and then pass to the model.
No matter what I do, for the fields name and email (set to varchar 150 and not NULL in SQL), when I try to insert, name and email are stored as empty strings when I don't include them in my JSON (for instance, if I pass id alone).
How can I make it so that if the name and email keys are not passed, the required error is shown?
Model:
Controller:
I'm using the CI 4 Entity class, so on an incoming request, I get the JSON, fill my new Entity on creation, and then pass to the model.
No matter what I do, for the fields name and email (set to varchar 150 and not NULL in SQL), when I try to insert, name and email are stored as empty strings when I don't include them in my JSON (for instance, if I pass id alone).
How can I make it so that if the name and email keys are not passed, the required error is shown?
Model:
PHP Code:
<?php
namespace Modules\User\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'Modules\User\Entities\User';
protected $useSoftDeletes = true;
protected $allowedFields = ['id', 'name', 'email', 'password'];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [
'id' => 'required|integer|is_unique[users.id]',
'name' => 'required',
'email' => 'required|valid_email|is_unique[users.email]
];
protected $validationMessages = [
'id' => [
'required' => 'An ID is required. This is normally a Podio Item ID.',
'integer' => 'ID must be an integer.',
'is_unique' => 'A record with this ID already exists.'
],
'name' => [
'required' => 'A name is required.' ],
'email' => [
'required' => 'An email address is required.',
'valid_email' => 'You must enter a valid email address.',
'is_unique' => 'The email address already exists in the system.'
]
];
protected $skipValidation = false;
}
Controller:
PHP Code:
public function create()
{
$json = $this->request->getJSON(true);
if ($json == null) {
$response = array(
'code' => 400,
'errors' => array('Request cannot be empty.')
);
return $this->respond($response, 200);
}
$user = new User($json);
if ($this->model->insert($user) === false) {
$response = array(
'code' => 400,
'errors' => $this->model->errors()
);
return $this->respond($response, 200);
}
$response = array(
'code' => 200,
'message' => 'User has been created.'
);
return $this->respond($response, 200);
}