Reputation: 1257
I have a JSON object that I need to post
& save it using cakePHP 3.
First I have 4 tables as in this image
Let's say a supplier buys some products, so I need to fill a purchase
record and the association table products_purchases
, which will contain all the records of products bought during that one purchase
.
I'll be using some JavaScript to dynamically generate some fields to be able to fill multiple products
with quantities, prices.. during that purchase
, and then store all the data in a JSON object
.
So in the add.ctp
view of purchase
, I'll have this JSON object
for exmaple :
$data = {
"reference": "V656413",
"supplier_id": 31,
"payment_id": 5,
"products_purchases": [
{
"product_id": 5566,
"purchase_id" 999,
"quantity": 4,
"price": 899
},
{
"product_id": 7865,
"purchase_id" 999,
"quantity": 6,
"price": 54
},{
"product_id": 434,
"purchase_id" 999,
"quantity": 8,
"price": 22
},
]
}
How can I POST
this object using the form
in the add.ctp
file, and how can I handle it and save it as an entity with its associations in the PurchasesController
?
The add
method in the controller for now is as follow :
public function add()
{
$purchase = $this->Purchases->newEntity();
if ($this->request->is('post')) {
$purchase = $this->Purchases->patchEntity($purchase, $this->request->data);
if ($this->Purchases->save($purchase)) {
$this->Flash->success(__('The purchase has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The purchase could not be saved. Please, try again.'));
}
}
$this->set('_serialize', ['purchase']);
}
Thank you very much!
Upvotes: 0
Views: 1305
Reputation: 21
You have to manage proper associations with your models. visit below link where you can see how to save data with associations.
https://book.cakephp.org/3.0/en/orm/saving-data.html
Upvotes: 1