CakePHP 3属于ToMany验证

Kri*_*ris 4 validation cakephp model has-and-belongs-to-many cakephp-3.0

我正在努力学习如何使用belongsToMany关系进行验证.即,经典的食谱/配料关系.我想要一个配方,在创建或编辑时始终有一个成分.我的RecipesTable中的验证结果如何?我试过了:

$validator->requirePresence('ingredients')->notEmpty('ingredients')
Run Code Online (Sandbox Code Playgroud)

以及

$validator->requirePresence('ingredients._ids')->notEmpty('ingredients._ids')
Run Code Online (Sandbox Code Playgroud)

第二个工作原理是我的表单不验证,但它不会将error类添加到输入中.我正在使用字段名称设置输入ingredients._ids.

我也无法创建要$this->post在我的测试中传递的数据,以便在我的测试中成功添加记录.我测试中的数据如下:

$data = [
    'ingredients' => [
        '_ids' => [
             '2'
        ]
    ];
Run Code Online (Sandbox Code Playgroud)

当然,我正在测试我的测试 $this->post('/recipes/add', $data);

我没有在测试中传递成分所需的规则.

Kri*_*ris 5

我解决了如何设置验证器的问题.在配方表验证器中:

$validator->add('ingredients', 'custom', [
    'rule' => function($value, $context) {
        return (!empty($value['_ids']) && is_array($value['_ids']));
    },
    'message' => 'Please choose at least one ingredient'
]);
Run Code Online (Sandbox Code Playgroud)

但是,验证消息没有显示在表单上,​​所以我正在isFieldError检查:

        <?php if ($this->Form->isFieldError('ingredients')): ?>
            <?php echo $this->Form->error('ingredients'); ?>
        <?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

我在视图文件中使用多个复选框而不是多选.

有了这个,我在表单上收到验证消息.

正如我想的那样,一旦我找到了验证器,我的测试就出现了.我在上面展示的内容对于在测试中传递数据确实是正确的.