I need to use two models in a view for my custom component in Joomla 4.
I saw this post for Joomla 3, but it seems that there isn't getInstance() in the base Models anymore.
How I could do it ?
Joomla Stack Exchange is a question and answer site for Joomla! administrators, users, developers and designers. It only takes a minute to sign up.
Sign up to join this communityI need to use two models in a view for my custom component in Joomla 4.
I saw this post for Joomla 3, but it seems that there isn't getInstance() in the base Models anymore.
How I could do it ?
Assuming that the second model that you want to use is in your extension then you can create an instance of the model with the following command. In the example Articles
is the name of the name model and will look for class ArticlesModel in your extensions /Model directory while the Site
designates where to find the model, eg. Administrator, Site or API.
$model = $this->getMVCFactory()
->createModel('Articles', 'Site', ['ignore_request' => true]);
The second param allows you to have single model in the backend of your component and use it in either the Front-end or API of your extension, rather than having to have duplicate models.
If you want to access the Model of another extension then you have to first load or boot the other extension and then create an instance of the Model. This example would allow you to access the Articles model of com_content Front-end.
/** @var \Joomla\Component\Content\Administrator\Extension\ContentComponent $contentComponent */
$contentComponent = Factory::getApplication()->bootComponent('com_content');
/** @var \Joomla\Component\Content\Site\Model\ArticlesModel $model */
$model = $contentComponent->getMVCFactory()
->createModel('Articles', 'Site', ['ignore_request' => true]);