I often use the patchEntity
function to hydrate my entity with form data, and it works fine, even with an ajax request.
But when I tried to insert data from an an ajax request with JSON data, patchEntity failed to retrieve the data.
My ajax request is very simple:
var rate = function (user, rate, success, error) {
$.ajax({
type: "POST",
url: baseUrl + 'rate/add',
data: {
id: this.id,
user: user.id
rate: rate
},
dataType: 'json',
success: success,
error: error
});
});
In my Rate controller, my add function looks like:
public function add()
{
if ($this->request->isAjax()) {
$this->layout = 'ajax';
$rate = $this->Rate->newEntity();
if ($this->request->is('post')) {
$rate = $this->Rate->patchEntity($rate, $this->request->data);
if ($rate->errors()) {
$this->set([
'status' => 500,
'message' => $rate->errors()
]);
} else {
if ($this->rate->save($rate)) {
$this->set([
'status' => 200
]);
} else {
$this->set([
'status' => 500,
'message' => $rate->errors()
]);
}
}
return $this->render('/Ajax/result');
}
}
This throw an exception:
Cannot insert row, some of the primary key values are missing. Got (, , ), expecting (id, user)
I can save my data using this instead of $this->Rate->patchEntity($rate, $this->request->data);
$rate['id'] = $this->request->data['id'];
$rate['user'] = $this->request->data['user'];
$rate['rate'] = $this->request->data['rate'];
What sort of array do I have to pass to patchEntity
function to makes this works?