如何在Joomla 2.5视图中调用不同的模型及其功能?
型号:settings.php
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
class UrcModelSettings extends JModelItem
{
public function getSettings($user_id = '')
{
$user = JFactory::getUser();
$user_id=$user->id;
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__settings_urc');
$query->where('user_id = '. (int) $user_id);
$db->setQuery($query);
return $db->loadObjectList();
}
}
查看:view.html.php
// import Joomla view library
jimport('joomla.application.component.view');
/**
* HTML View class for the HelloWorld Component
*/
class UrcViewUrc extends JView
{
// Overwriting JView display method
function display($tpl = null)
{
$model = $this->getModel('Settings');
$datas = $model->getSettings();
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JLog::add(implode('<br />', $errors), JLog::WARNING, 'jerror');
return false;
}
// Display the view
$user = JFactory::getUser();
if($user->id!=0)
{
parent::display($tpl);
}
else
{
echo "You have not permission for this page";
}
}
}
我正在使用getModel('Settings');它在控制器中工作,但它在视图中给我一个错误。
Notice: Undefined index: settings in C:\wamp\www\Joomla\libraries\joomla\application\component\view.php on line 413
Fatal error: Call to a member function getSettings() on a non-object in C:\wamp\www\Joomla\components\com_urc\views\urc\view.html.php on line 40
答案 0 :(得分:8)
您可以尝试JModel
类来调用特定模型进行查看。
$Model = JModel::getInstance('MODEL_NAME', 'MODEL_CLASS_PREFIX');
例如:
$model = JModel::getInstance('settings', 'UrcModel');
$settings = $model->getSettings ();
希望它会有所帮助。
答案 1 :(得分:5)
在视图中实例化模型被认为是不好的风格。由控制器实例化模型并将分配给视图,因此视图可以通过其getModel()
方法访问模型。这就是视图的setModel()
方法。