1

I am trying to create a model in Joomla that will display various information pertaining to a certain ID. When I create the function:

public function getItem ($id = null)
{
    if ($this->_item === null)
    {
        $this->_item = false;

        if (empty($id))
        {
            $id = $this->getState('player.id');
        }
        
    }

    $db    = Factory::getDbo();
    $query = $db->getQuery(true);
    $query = "SELECT name FROM #__baseball_teams WHERE id = $id";
    $db->setQuery($query);
    $this->_item = $db->loadObject()->name; 
    
    return $this->_item;
}

But when I change the query results from:

$this->_item = $db->loadObject()->name;

to

$this->_item->team = $db->loadObject()->name;

I keep getting errors such as Attempt to assign property "team" on bool

Or if I try changing things around, I get Attempt to assign string "team" on null, etc.

When I run a print_r, the data is there and a var_dump shows as strings, but I just have no idea why I cannot assign an additional -> without getting errors?

1 Answer 1

2

Well, your code is saying that $this->_item might be null (a non-object) -- if it is, you are overwriting it to be false (again, a non-object). Then, after grabbing your database results, you are trying to assign a property to $this->_item as if it was an object, but you cannot assign a property to a non-object. Perhaps you want to convert a null $this->_item to be an empty object so that you can assign properties to it.

Also, you are creating a query object with:
$query = $db->getQuery(true);

Then you are overwriting that object with a literal string with:
$query = "SELECT name FROM #__baseball_teams WHERE id = $id";

Instead, let's implement a prepared statement with query building helper methods in J4.

Untested suggestion:

public function getItem ($id = null): object
{
    if (!is_object($this->_item))
    {
        $this->_item = (object) [];

        if (!$id)
        {
            $id = $this->getState('player.id');
        }
        
        $db    = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select($db->quoteName('name'))
              ->from($db->quoteName('#__baseball_teams'))
              ->where($db->quoteName('id') . ' = :id')
              ->bind(':id', $id);
        $db->setQuery($query);
        $this->_item->name = $db->loadObject()->name; 
    }
    
    return $this->_item;
}

From PHP7.4, use the null coalescing assignment operator to replace the if (!$id) { ... } condition block.

$id ??= $this->getState('player.id');
1
  • As usual, you knocked it out of the park. Thanks for all you do mickmack.
    – Brandon
    Apr 29 at 15:38

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.