Joomla: use multiple models in one view
In your controller:
$model1 = &$this->getModel('Model1Name', 'ModelPrefix');
// will load ModelPrefixModelModel1Name from file model1name.php in models directory
$model2 = &$this->getModel('Model2Name', 'ModelPrefix');
// will load ModelPrefixModelModel2Name
$view = &$this->getView($viewName, $viewType, $viewPrefix);
$view->setModel($model1, true); // true makes this the default model
$view->setModel($model2);
$view->display();
In your view:
//invoke get methods on model1 (the default model):
$data = &$this->get('data');
$pagination = &$this->get('pagination');
// get model 2:
$model2 = &$this->getModel('Model2Name');
// we can also get model 1 if we want:
$model1 = &$this->getModel();
Another solution:
In controller
Code:
$model1 = & $this->getModel( 'model1', 'ModelPrefix' );
$model1->setId(JRequest::getInt('id', 0));
//-------- any operation on Model1
$model2 = & $this->getModel( 'model2', 'ModelPrefix' );
//---------any operation on Model2
$view = & $this->getView('ViewName', 'html');
$view->setModel( $model1, true );
$view->setModel( $model2);
$view->display();
In View, assume that the each model contains getData() method.
Code:
//if not specify model name, it get from default model
$data_from_model1 = $this->get('Data', 'model1');
$data_from_model2 = $this->get('Data', 'model2');
some of my finding in calling Model (in controller)
Code:
$model1 = &$this->getModel('Model1Name', 'ModelPrefix');
only work if you are calling model within the same component.
For calling model from others components, also work for model from same component,
Code:
// from other component, you need to addPath
require_once(JPATH_COMPONENT.DS.'models'.DS.'myothermodel.php');
$config=array(); $config['param1']='value1'; $config['param2']='value2';
$model =& JModel::getInstance('foo', 'ComponentModel', $config); // this method always work for me