Saturday, 15 June 2013

php - How to create multiple objects in add method of controller with CakePHP -



php - How to create multiple objects in add method of controller with CakePHP -

i have productscontroller add together view autocomplete field ('brand_name') on user can come in brand name. in handler want check if brand name exists in database, brand_id should set on product. if not exists in database, new brand should created , inserted in database.

the code beneath simplified:

app/model/product.php

class product extends appmodel { public $belongsto = array('brand'); }

app/controller/productscontroller.php

class productscontroller extends appcontroller { public $helpers = array('html', 'form', 'session'); public $components = array('session'); public function add() { if ($this->request->is('post')) { $this->product->create(); $brand = $this->product->brand->find( 'first', array( 'conditions' => array( 'brand.name' => $this->request->data['product']['brand_name'] ) ) ); if($brand) { $this->request->data['product']['brand_id'] = intval($brand['brand']['id']); } else { // add together new brand //$this->product->brand->create(); $this->product->brand->name = $this->request->data['product']['brand_name']; } if ($this->product->saveall($this->request->data)) { $this->session->setflash(__('the product has been saved.')); //$this->redirect(array('action' => 'index')); } else { $this->session->setflash(__('unable add together product.')); } } } }

everything works fine, except creating , inserting new brand object. how create object in code? i'm brand new cakephp if approach wrong, please allow me know.

i've fixed adding new value $this->request->data array, this:

if($brand) { $this->request->data['product']['brand_id'] = intval($brand['brand']['id']); } else { $this->request->data['brand']['name'] = $this->request->data['product']['brand_name']; }

php cakephp cakephp-2.3

No comments:

Post a Comment