Call model function inside view joomla

Prince picture Prince · May 2, 2013 · Viewed 12.1k times · Source

How can we call different models and their functions in Joomla 2.5 view ?

Model: 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

// 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'); 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

Answer

Toretto picture Toretto · May 2, 2013

You can try JModel class for calling the specific model in to view.

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

For example:

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

Hope it will help.