I am struggling with how to do validation with belongsToMany relationships. Namely, the classic recipes/ingredients relationship. I would like a recipe to always have an ingredient on create or edit. What would my validation look like in my RecipesTable? I have tried:
$validator->requirePresence('ingredients')->notEmpty('ingredients')
As well as
$validator->requirePresence('ingredients._ids')->notEmpty('ingredients._ids')
The second one works in that my form doesn't validate, but it does not add the error
class to the input. I am setting up the input with a field name of ingredients._ids
.
I am also having trouble with creating the data to pass to $this->post
in my tests in order to successfully add a record in my test. My data in my test looks like:
$data = [
'ingredients' => [
'_ids' => [
'2'
]
];
And of course I'm doing the post in my test with $this->post('/recipes/add', $data);
I'm not passing the required rules for ingredients in my test.
I solved how to set up the validators. In the recipe Table validator:
$validator->add('ingredients', 'custom', [
'rule' => function($value, $context) {
return (!empty($value['_ids']) && is_array($value['_ids']));
},
'message' => 'Please choose at least one ingredient'
]);
However, the validation message was not being displayed on the form, so I'm doing a isFieldError
check:
<?php if ($this->Form->isFieldError('ingredients')): ?>
<?php echo $this->Form->error('ingredients'); ?>
<?php endif; ?>
I'm using multiple checkboxes in my view file versus a multi-select.
And with that, I'm getting my validation message on the form.
As I thought, my tests fell into place once I figured out the validator. What I show above is indeed correct for passing data in the test.
I will have desired to add this answer as a comment of Kris answer but I do not have enough reputation.
Alternatively, to solve the issue with validation message not being displayed on the form, you can add these two line in your controller.
if(empty($this->request->data['ingredients']['_ids']))
$yourentity->errors('ingredients', 'Please choose at least one ingredient');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With