doushi5752 2017-07-05 04:43
浏览 19

访问其他帖子字段以创建复杂的验证条件

I'm sending request data with parent/child relationships (1 level max depth). So parent_id references itself in the table as a fk.

debug($this->request->getData()) yields:

[
    "activities": [
        [
            "name": "Parent Activity",
            "id": 3,
            "parent_id": null,
            "quantity": null,
        ],

        [
            "name": "Child Activity",
            "id": 4,
            "parent_id": 3,
            "quantity" :5
        ],

        [
            "name": "Parent Activity 2",
            "id": 7,
            "parent_id": null,
            "quantity": null,
        ],

    ]
]

I want to create a Validation rule that will force parent activities who have no children ( nodes with parent_id pointing to them ) to have quantity" filled in (this can be any arbitrary field, I have a few others).

The most straight forward way I can think is by looping/manipulating the request data and marking it, but is there a nice Cake way of doing this and possibly in the Validation?

$data = $this->request->getData();
$collection = new \Cake\Collection\Collection($data);

// filter/map so I can create a new key to count the # of children, thus manipulating the data as such:

[
    "activities": [
        [
            "name": "Parent Activity",
            "id": 3,
            "parent_id": null,
            "quantity": null,
            "children": 1
        ],

        [
            "name": "Child Activity",
            "id": 4,
            "parent_id": 3,
            "quantity" :5
        ],

        [
            "name": "Parent Activity 2",
            "id": 7,
            "parent_id": null,
            "quantity": null,
            "children": 0
        ],

    ]
]

Then I could use the children as a condition in Validation rather than something more complicated. Though manipulating the request data doesn't seem that clean. Open to any other suggestions.

Using Cake3.

  • 写回答

1条回答 默认 最新

  • dongshao6591 2017-07-05 10:02
    关注

    Use conditional validation.

    Example taken from the link above:

    $validator->add('picture', 'file', [
        'rule' => ['mimeType', ['image/jpeg', 'image/png']],
        'on' => function ($context) {
            return !empty($context['data']['show_profile_picture']);
        }
    ]);
    

    $context is the data, just add your logic to check $context in the closure.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器