Reputation: 28284
I check for data below and if data is there in the form field it updates the table. Problem is that if I click the button twice (its ajax) it wll insert a second row. How can I prevent it. thanks
function update() {
if (!empty($this->data)) {
$this->Test->saveAll($this->data['Test'])
}
}
Upvotes: 0
Views: 539
Reputation: 2126
You should take a two-pronged approach to preventing this:
First, Disable the submit button on submit. For example in jQuery:
$('#form_id').submit(function(event) {
event.preventDefault();
$('input[type=submit]', this).attr('disabled', 'disabled');
// submit form via ajax...
}
Secondly, perform rational check server-side to prevent duplicate saves. For example, two identical records submitted within a minute or so would be considered an error. I'd probably do this by creating a custom validation rule on one of the fields that's always required. In your model:
var $validate = array(
'myfield' => array(
'rule' => 'duplicateCheck',
'message' => 'Duplicate record'
)
);
function duplicateCheck() {
$conditions = array(
'Model.field1' => $this->data['Model']['field1'],
...
'Model.created >' => date("Y-m-d H:i:s", time() - 60)
);
return !$this->hasAny($conditions);
}
Then in your controller, I would redirect the user to the existing record if the save fails and it was because of that specific validation rule. This let's the user move along without caring that anything went wrong.
function add() {
if(isset($this->data)) {
if($this->Model->save($this->data)) {
...
} else {
if(isset($this->Model->validationErrors['myfield'])) {
// find the existing record and redirect user to view it
}
}
}
}
Upvotes: 0
Reputation: 716
The problem is the form doesn't have the id field so cakephp insert a new row.
The easy way is check if exists another record with the same values before save.
You can check in function beforeSave() of the Model instead of the Controller action.
http://book.cakephp.org/#!/view/1052/beforeSave
Upvotes: 1