Issue
This question somewhat follows on from a previous question I asked about implementing validation when performing a search in a Cake 3.x application: CakePHP 3.x search form with 11 different models
I've been reading the documentation on Using Custom Validation Rules.
I have added the following to my Model/Table/EcsTable.php
:
public function validationSearch($validator)
{
$extra = 'Some additional value needed inside the closure';
$validator->add('value', 'custom', [
'rule' => function ($value, $context) use ($extra) {
return false;
},
'message' => 'The title is not valid'
]);
return $validator;
}
This is a copy of what is given in the docs except I have added return false
because I'm trying to test the validation method producing an error.
In my Controller I have the following:
$ecs_entity = TableRegistry::get('Ecs')->newEntity(
$this->request->getData(),
[
'validate' => 'search', // tells cake to use validateSearch
]
);
I cannot get this to generate a validation error. If I submit my form (so that the request data is submitted) and then do debug($ecs_entity);
the errors
property is an empty array:
object(Cake\ORM\Entity) {
'ecs' => [
'value' => '124'
],
// ...
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Ecs'
}
Why is this? I am planning on writing logic inside my closure inside validationSearch
which validates the data passed. However, I can't even get it to produce an error so haven't gone this far with it. Am I implementing this in the wrong way?
As per the original question I'm trying to do things in the proper "Cake way" of writing validation. I'm getting to the point where I'm seriously considering abandoning it and just sticking everything in the Controller, because it's so tedious to pass the data around - and involves more lines of code when I could just validate it right there in the controller.
Solution
The data you are passing to the newEntity
call is not in valid format.
It looks like you are passing something like
[
'ecs' => [
'value' => 123
]
]
When it should be:
[ 'value' => 123 ]
The debug output for a valid Ecs
entity should look like this:
object(Cake\ORM\Entity) {
'value' => '123',
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'value' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Esc'
}
As you can see value
is a direct property of the object.
Without seeing your Form
I can guess you have created it like:
$this->Form->control( 'ecs.value')
instead of
$this->Form->control( 'value' );
Answered By - Ilie Pandia
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.