开发者

How to avoid errors in saving data - Cakephp

I'm using Cakephp and trying to put in a method to make sure our reservation system doesn't let two users book the same appointment. Ex. User 1 opens the appointment, and User 2 opens it simultaneously. User 1 books the appointment. User 2 tries to book it but the system checks and sees it is no longer available.

I imagine this would take place in validation, or in a beforeSave(), but can't figure out how to do it.

Right now I made a function in the model to call from the controller. In the controller I have:

if ($this->Timeslot->checkIfNotAvailable()) {
$this->Session->setFlash('This timeslot is no longer available');
$this->redirect(arr开发者_运维问答ay('controller' => 'users', 'action' => 'partner_homepage')); 
}

and in the model I have this function:

function checkIfNotAvailable($data) {
    $this->recursive = -1;
    $timeslot = $this->find('all', array(
        'conditions' => array(
            'Timeslot.id' => $this->data['Timeslot']['id'])
        )
    );
    if ($timeslot['student_id'] == 0) {
        //They can reserve it, do not spring a flag
        return false;
    } else {
        //Throw a flag!
        return true;
    }
}

I think I'm mixed up using custom validation when it's not called for. And it's not working obviously. Any suggestions?

Thanks!


If what you have is working, you can stick with it, you could also try creating a beforeValidate() call back function in your Model.

class YourModel extends AppModel {
   function beforeValidate(){
      if( !$this->checkIfNotAvailable( $this->data ) ) {
         unset($this->data['YourModel']['time_slot']);
      }
      return true; //this is required, otherwise validation will always fail
   }
}

This way you remove the time_slot before it goes to validation and it will drop a validation error at that point, kicking the user back to the edit page and getting them to pick a different time slot, ideally the updated data entry page will no longer have the used time slot available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜