2

I have a custom component where I was to be able to select other articles to show in the frontend. I have thought the best way to do this would be through the SQL field.

This is good that it gives me the ID of the article, but I want to be able to display the article name, intro image and intro text in the frontend of my custom component.

I have the following in my component XML

<field name="interested_in" type="sql" default="10" label="Select an article" query="SELECT id, title FROM #__content" key_field="id" value_field="title" />

This echo's the ID:

<?PHP echo $this->item->interested_in; ?>

But ideally, I need something along the lines of:

    <?php

    $id      = $this->item->interested_in;
    $article = JControllerLegacy::getInstance('Content')->getModel('Article')->getItem($id);
    $image   = json_decode($article->images);

    echo '<a href="' . JRoute::_('index.php?option=com_content&view=article&id=' . $id) . '">' . $article->title . '</a>';

    if ($image !== null) {
        echo '<img src="' . $image->image_intro . '" alt="">';
    }
    
    ?>

But this is giving me an error in the frontend:

Call to a member function getItem() on bool
2
  • 2
    Your XML uses name="interested_in" however you confirmed that $this->item->interest_in echoes the ID. Note the difference between interested_in and interest_in. Was this a typo in the question or if there a mismatch?
    – Lodder
    Jul 7 at 16:49
  • 2
    FYI the I've tested the code and everything works fine...assuming interested_in is used in both the XML and PHP
    – Lodder
    Jul 7 at 16:50
4

JControllerLegacy::getInstance() caches the first controller instance so you're actually getting an instance of your component's controller rather than Content controller. You can skip the controller and get the model directly instead:

JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_content/models', 'ContentModel');
$model = JModelLegacy::getInstance('Article', 'ContentModel');
$article = $model->getItem($id);
1
  • Worked perfectly, thank you! Jul 8 at 9:05

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.