I have quite an odd problem which i can't seem to figure out. I read some related questions such as this and this. However, these both use normal submission, whereas I am performing the save through an ajax request. (Which brings me to my problem).
Firstly, I am not sure how much level of 'graceful' degradation needs to be implemented nowadays with js/ajax (can easily not use a form).. However for the sake of js-disabled browsers/users, I think its' wise to use a form. What's your intake on this?
The main question however is the one below. I am trying to edit records using ajax as follows:
This is my form :
<?php echo $this->Form->create('BloodTarget',array('type' => 'post', 'default'=> false));?>
<?php $i = 0;?>
<?php foreach($targets as $target):?>
<?php echo $this->Form->input("BloodTarget.$i.cur_amount", array('type' => 'hidden', 'value' => $target['BloodTarget']['target_amount']));?>
<?php echo $this->Form->input("BloodTarget.$i.id", array('type' => 'hidden', 'value' => $target['BloodTarget']['id']));?>
<?php echo $this->Form->input("BloodTarget.$i.target_amount",array('label' => false,'type' => 'number','value' => $target['BloodTarget']['target_amount']));?>
<?php $i++;?>
<?php endforeach;?>
<?php echo $this->Form->end();?>
This generates something like this
<input type="hidden" name="data[BloodTarget][0][cur_amount]" value="26" id="BloodTarget0CurAmount">
<input type="hidden" name="data[BloodTarget][0][id]" value="1" id="BloodTarget0Id">
<div class="input number"><input name="data[BloodTarget][0][target_amount]" value="26"
type="number" id="BloodTarget0TargetAmount"></div>
In my jquery's ajax function I serialize the form
data: $("#BloodTargetRequestBloodForm").serializeArray()
which sends data like so:
_method:POST
data[BloodTarget][blood_group_id]:1
data[BloodTarget][blood_component]:Whole Blood
data[BloodTarget][target_amount]:0
Finally I save the data from the controller
if($this->BloodTarget->save($this->request->data['BloodTarget']))
and it does save, however, it creates a new record with an ID of zero instead updating the 3 records within the form.
What is wrong here? I also tried to set the ID before update,(but this doesn't work)
$this->BloodTarget->id = $this->request->data['BloodTarget']['id'];
For the life of me, can anyone please identify what is wrong in my code? What am I missing? Thanks a heaps!