如何避免保存数据时出错 - Cakephp

时间:2011-05-03 23:56:42

标签: validation cakephp

我正在使用Cakephp并尝试设置一种方法来确保我们的预订系统不会让两个用户预订相同的约会。防爆。用户1打开约会,用户2同时打开它。用户1预约约会。用户2尝试预订,但系统检查并发现它不再可用。

我想这会发生在验证中,或者在beforeSave()中,但无法弄清楚如何去做。

现在我在模型中创建了一个函数来从控制器调用。在控制器中我有:

if ($this->Timeslot->checkIfNotAvailable()) {
$this->Session->setFlash('This timeslot is no longer available');
$this->redirect(array('controller' => 'users', 'action' => 'partner_homepage')); 
}

在模型中我有这个功能:

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;
    }
}

我认为我没有被要求使用自定义验证。它显然不起作用。有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果你有什么工作,你可以坚持下去,你也可以尝试在你的模型中创建一个beforeValidate()回调函数。

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
   }
}

通过这种方式,您可以在进行验证之前删除time_slot,并在此时删除验证错误,将用户踢回编辑页面并让他们选择不同的时间段,理想情况下更新的数据输入页面将不再使用已用的时段。

相关问题