0

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(array('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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Steve, thanks for the suggestion. My way isn't working right now...do you see any errors in what I'm doing with that method?
Your attempt is probably failing because you're using a find('all') which will return an entire array of records, this making it impossible to test $timeslot['student_id']. Try switching it to a find('first') and you might be OK.
OK...thanks steve, got it to work both ways. The find('all') was one problem, and also I needed to send $this->data when I called "checkIfNotAvailable". Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.