9

I'm building a component and It needs access the #__content table. The component com_content does everything that my component needs to do in that table. How can I import the com_content models into the controllers in my component?

Is a good practice to use a existent table instead to create my own? My component is going to show a photo gallery with comments and I want to use the #__content table to store the comments. Should I create a new table to the comments?

17

You can import com_content models into the controller using addIncludePath() method:

JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_content/models', 'ContentModel');

addIncludePath() method adds a directory where JModelLegacy should search for models. You may either pass a string or an array of directories as the first parameter. As the second parameter you can specify class prefix for models (optional).

Then just use getInstance() method:

$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));

The first parameter is the model type to instantiate, the second is the prefix for the model class name (optional) and the third parameter is configuration array for model (optional).

But I prefer not to use existing core components tables for custom components.

2
  • Thanks! It is what I was looking for. I will try avoid to use existing core components. I think you are right about that. – csbenjamin Apr 23 '14 at 13:44
  • Okey I get, now... How can I use it. For example, let's assume that I have the function getMsg, how do I call it?. $this->msg = $this->get('Msg'); – ValRob Nov 2 '18 at 14:06
2

You may get an error like this:

Call to a member function load() on boolean

That mean you need to add JTable::addIncludePath also

Admin Model:

function getModelAdmin($component, $name = 'Custom', $prefix = 'CustomModel')
{
    JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/' . $component . '/tables', $prefix);
    JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/' . $component . '/models', $prefix);
    $model = JModelLegacy::getInstance($name, $prefix, array('ignore_request' => true));
    return $model;
}

Site Model:

function getModelSite($component, $name = 'Custom', $prefix = 'CustomModel')
{
    JTable::addIncludePath(JPATH_SITE . '/components/' . $component . '/tables', $prefix);
    JModelLegacy::addIncludePath(JPATH_SITE . '/components/' . $component . '/models', $prefix);
    $model = JModelLegacy::getInstance($name, $prefix, array('ignore_request' => true));
    return $model;
}
1
  • Welcome to JSE and thank you for contributing. Please take the tour and perhaps tell us about your Joomla experience in your profile. – mickmackusa Aug 15 '20 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.