Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3 belongsToMany Validation

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.

like image 411
Kris Avatar asked Mar 17 '23 23:03

Kris


2 Answers

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.

like image 147
Kris Avatar answered Mar 24 '23 07:03

Kris


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');
like image 30
jtraulle Avatar answered Mar 24 '23 06:03

jtraulle