Reputation: 898
I want to add data in two tables form one controller file when I call function for add data in second one table ..error comes Error: Call to a member function save() on a non-object
Here is my controller file
<?php
class CountryController extends AppController {
var $name = 'Country';
var $helpers = array('Html', 'Form' );
// called index function
public function index() {
$this->render();
}
// Function for add countries in database
public function addCountry() {
if (empty($this->data)) {
$this->render();
} else {
// $this->cleanUpFields();
if ($this->Country->save($this->data)) {
$this->Session->setFlash('The Counrty has been saved');
$this->redirect('/country/index');
} else {
$this->Session->setFlash('Please correct errors below.');
}
}
}
public function addCity() {
$cities = $this->set('country', $this->Country->find('all'));
$this->set(compact('cities'));
if(empty($this->data)){
$this->render();
} else {
print_r($this->data);// die();
if ($this->City->save($this->data)) {
$this->Session->setFlash('The City has been saved');
$this->redirect('/country/index');
} else {
$this->Session->setFlash('Please correct errors below.');
}
}
}
}
?>
Upvotes: 1
Views: 3719
Reputation: 1674
var $uses = array('Main model name' , '2nd model name' .......so on);
Eg:
<?php
class CountryController extends AppController {
var $name = 'Country';
var $helpers = array('Html', 'Form' );
// $uses is where you specify which models this controller uses
var $uses = array('Country', 'City');
// ... here go your controller actions (methods)
}
?>
Upvotes: 0
Reputation: 6767
You can use model chaining. I'm assuming a City and Country are related (maybe be an intermediary model State?).
So it would be $this->Country->City->save()
or $this->Country->IntermediaryModel->City->save()
depending on your relationships.
Upvotes: 1