简体   繁体   English

在视图joomla中调用模型函数

[英]Call model function inside view joomla

How can we call different models and their functions in Joomla 2.5 view ? 我们如何在Joomla 2.5视图中调用不同的模型及其功能?

Model: settings.php 型号: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: view.html.php 查看: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";
        }               
    }
}

I am using getModel('Settings'); 我正在使用getModel('Settings'); it works in controllers but it's give me an error in view. 它可以在控制器中工作,但是在视图上却给我一个错误。

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

You can try JModel class for calling the specific model in to view. 您可以尝试使用JModel类在其中调用特定模型。

$Model = JModel::getInstance('MODEL_NAME', 'MODEL_CLASS_PREFIX'); 

For example: 例如:

$model = JModel::getInstance('settings', 'UrcModel');
$settings = $model->getSettings ();

Hope it will help. 希望它会有所帮助。

It is considered to be bad style to instantiate a model within a view. 在视图中实例化模型被认为是不好的风格。 It is up to the controller to instantiate the model and assign it to the view, so the view can access the model through its getModel() method. 由控制器实例化模型并将其分配给视图,因此视图可以通过其getModel()方法访问模型。 That's exactly, what the setModel() method of a view is made for. 就是说,这就是视图的setModel()方法的作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM