简体   繁体   中英

Save multiple hasMany data with saveAll() in CakePHP without writing id's in the view

I FINALLY got my hasMany data to save using saveAll() - (an Event that hasMany Schedules).

I got it to work by repeating through the $this->data['Schedule'] data on the events/admin_edit.ctp, and building out all the fields for any/all schedules that are related to that event.

This seems fine (I think), but my question/problem is - I had to add the Schedule.id and Schedule.event_id fields as hidden fields so it'd know what data to save. This seems awfully unsecure/wrong... 1) is it the right way to do it? and 2) Couldn't someone just edit the field to another ID, and hit save to update a different event's information?

My next assumption is that I'll have to build in some kind of checks into the controller before doing the saveAll()... but the more I write, the more complicated it's going to get, and the less Cake-like it seems.

Any thoughts/suggestions on how to better do what I'm doing, or insight as to what to check before doing the saveAll() is greatly appreciated.

I assume you have users that are allowed to edit their own events. If that's the case, the easiest way is to add a validation rule that verifies that the user is allowed to edit the submitted schedule.

In your action, before the save() is called, inject the current user id into each record. ie:

$this->data['Schedule'][0]['user_id'] = $this->Auth->user('id');

This may not work exactly, but should get you close. In your Schedule model, add a validation rule:

var $validate = array(
    'user_id' => array(
        'rule' => 'checkAuth'
        'message' => 'Nice try buddy.',
        'on' => 'update'
    )
);

function checkAuth() {
    $authorized = true;
    if(!$this->hasAny(array(
            'Schedule.id'=>$this->data['Schedule']['id'], 
            'Schedule.user_id' => $this->data['Schedule']['user_id']))) {
        $authorized = false;         
    }
    return $authorized;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM