How to fix error 00 Call to a member function get() on null ($listOrder)

For Joomla! 4.x Coding related discussions, you could also use: http://groups.google.com/group/joomla-dev-general

Moderators: ooffick, General Support Moderators

Forum rules
Forum Rules
Absolute Beginner's Guide to Joomla! <-- please read before posting, this means YOU.
Forum Post Assistant - If you are serious about wanting help, you will use this tool to help you post.
Windows Defender SmartScreen Issues <-- please read this if using Windows 10.
Post Reply
zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Tue Mar 26, 2024 12:04 am

Hi!

This is my first component for FAQ. It has several views:

Faq - base view for page info
Faqcontent - view for list of all questions
FaqContentItem - edit view for add or edit question.

Now I have this error on page faqcontent:

Code: Select all

0 Call to a member function get() on null in JROOT/administrator/components/com_faq/tmpl/faqcontent/default.php:17
THis is code for file com_faq/tmpl/faqcontent/default.php:

Code: Select all

<?php
defined('_JEXEC') or exit();

use Joomla\CMS\Button\PublishedButton;
use Joomla\CMS\Button\TransitionButton;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Layout\LayoutHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;

$app            = Factory::getApplication();
$doc            = Factory::getDocument();

$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn  = $this->escape($this->state->get('list.direction'));
$saveOrder = $listOrder == 'a.ordering';
$orderingColumn = 'publish_up';
/** @var \Joomla\CMS\WebAsset\WebAssetManager $wa */
$wa = $app->getDocument()->getWebAssetManager();
$wa->useScript('table.columns')
	->useScript('multiselect');

if ($saveOrder && !empty($this->items)) {
    $saveOrderingUrl = 'index.php?option=com_faq&task=faqcontentitem.saveOrderAjax&tmpl=component&' . Session::getFormToken() . '=1';
    HTMLHelper::_('draggable.draggable');
}
?>

<div class="container-fluid">
    <div class="row">
        <div class="col">
            <form action="<?php echo Route::_('index.php?option=com_faq&view=faqcontent'); ?>" method="post" id="adminForm" name="adminForm">
		        <?php echo LayoutHelper::render('joomla.searchtools.default', ['view' => $this]); ?>
	            <?php if (empty($this->items)) : ?>
                    <div class="alert alert-info">
                        <span class="icon-info-circle" aria-hidden="true"></span><span class="visually-hidden"><?php echo Text::_('INFO'); ?></span>
			            <?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?>
                    </div>
	            <?php else : ?>
                    <table class="table itemList" id="faqList">
                        <thead>
                        <tr>
                            <th width="1%"><?php echo HtmlHelper::_('grid.checkall'); ?></th>
                            <th scope="col" class="w-1 text-center d-none d-md-table-cell">
			                    <?php echo HTMLHelper::_('searchtools.sort', '', 'a.ordering', $listDirn, $listOrder, null, 'asc', 'JGRID_HEADING_ORDERING', 'icon-sort'); ?>
                            </th>
		                    <th scope="col" class="w-1 text-center">
				                <?php echo HTMLHelper::_('searchtools.sort', 'JSTAGE', 'ws.title', $listDirn, $listOrder); ?>
                            </th>
                            <th scope="col" class="w-1 text-center">
			                    <?php echo HTMLHelper::_('searchtools.sort', 'JSTATUS', 'a.state', $listDirn, $listOrder); ?>
                            </th>
                            <th scope="col" style="min-width:100px">
			                    <?php echo HTMLHelper::_('searchtools.sort', 'JGLOBAL_TITLE', 'a.title', $listDirn, $listOrder); ?>
                            </th>
                            <th scope="col" class="w-10 d-none d-md-table-cell text-center">
			                    <?php echo HTMLHelper::_('searchtools.sort', 'COM_FAQ_HEADING_DATE_' . strtoupper($orderingColumn), 'a.' . $orderingColumn, $listDirn, $listOrder); ?>
                            </th>
                            <th scope="col" class="w-3 d-none d-lg-table-cell">
			                    <?php echo HTMLHelper::_('searchtools.sort', 'JGRID_HEADING_ID', 'a.id', $listDirn, $listOrder); ?>
                            </th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($this->items as $i => $item) : ?>
                            <tr class="row<?php echo $i % 2; ?>" data-draggable-group="<?php echo $item->catid; ?>">
                                <td>
                                    <?php
                                        $iconClass = '';
                                        if (!$saveOrder) {
                                            $iconClass = ' inactive tip-top hasTooltip" title="' . HTMLHelper::_('tooltipText', 'JORDERINGDISABLED');
                                        }
                                    ?>
                                    <span class="sortable-handler<?php echo $iconClass ?>">
                                        <span class="icon-menu" aria-hidden="true"></span>
                                    </span>
                                    <input type="text" style="display:none" name="order[]" size="5" value="<?php echo $row->ordering; ?>" class="width-20 text-area-order" />
                                </td>
                                <td class="text-center">
			                        <?php echo $item->state; ?>
                                </td>
                                <td>
                                    <a href="/<?php echo Route::_('index.php?option=com_faq&task=faqcontentitem.edit&id=' . (int) $item->id); ?>" title="<?php echo Text::_('JACTION_EDIT'); ?>">     
                                        <?php echo $this->escape($item->title); ?>
                                    </a>
                                </td>
                                <td class="text-center">
			                        <?php echo $item->published; ?>
                                </td>
                                <td class="text-center">
			                        <?php echo HTMLHelper::_('grid.id', $i, $item->id); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
		            <?php echo $this->pagination->getListFooter(); ?>
                <?php endif; ?>

                <input type="hidden" name="task" value="">
                <input type="hidden" name="boxchecked" value="0">
	            <?php echo HTMLHelper::_('form.token'); ?>
            </form>
        </div>
    </div>
</div>
This is the code for file src/Model/FaqcontentModel.php

Code: Select all

<?php

namespace Joomla\Component\Faq\Administrator\Model;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;

defined('_JEXEC') or exit();

class FaqContentModel extends ListModel {

	/**
	 * Конструктор.
	 * @param   array  $config  Массив с конфигурационными параметрами.
	 */
	public function __construct($config = []){
		// Добавляем валидные поля для фильтров и сортировки.
		$config['filter_fields'] = array(
            'id', 'a.id',
            'title', 'a.title',
            'ordering', 'a.ordering',
            'state', 'a.state',
            'publish_up', 'a.publish_up'
        );

		parent::__construct($config);
	}


	/**
     * Method to get a list of items.
     *
     * @return  mixed   An array of data items on success, false on failure.
     */
    public function getItems()
    {
        // Get the query for retrieving items
        $query = $this->getQuery();

        // Set the query limits and execute
        $this->setState('list.limit', 0);
        $this->setState('list.start', 0);
        $this->setQuery($query);

        // Get the items from the query
        $items = $this->getList();

        return $items;
    }



	/**
	 * Метод для построения SQL запроса для загрузки списка данных.
	 * @return  string  SQL запрос.
	 */
	protected function getQuery(): string
	{

		$db = $this->getDbo();
        $query = $db->getQuery(true);

		$query->select('*');
		$query->from('#__faq_item');

        /* Add Searching */
		$state = $this->getState('filter.state');
		if (is_numeric($state))
		{
			$query->where('state = ' . (int) $state);
		}
		elseif ($state === '')
		{
			$query->where('(state = 0 OR state = 1)');
		}

		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			$search = $db->quote('%' . $db->escape($search, true) . '%', false);
			$query->where('title LIKE ' . $search);
		}

        $published = $this->getState('filter.published');
        if (is_numeric($published)) {    
            $query->where($db->quoteName('published') . ' = ' . $db->quote($published));
        } elseif ($published === '') {    
            $query->whereIn($db->quoteName('published'), array(0, 1));
        }

		// Добавляем сортировку.
		$orderCol  = $this->state->get('list.ordering', 'id');
		$orderDirn = $this->state->get('list.direction', 'desc');
		$query->order($db->escape($orderCol . ' ' . $orderDirn));



		return $query;
	}

	/* Prepare a helloworld record for saving in the database */
	protected function prepareTable($table)
	{	
	// Set ordering to the last item if not set
		if (empty($table->ordering))
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->select('MAX(ordering)')
				->from('#__faq_item');

			$db->setQuery($query);
			$max = $db->loadResult();

			$table->ordering = $max + 1;
		}
	}	
}
THis is the code for src/View/FaqContent/HtmlView.php

Code: Select all

<?php
namespace Joomla\Component\Faq\Administrator\View\FaqContent;
defined('_JEXEC') or die;

use Joomla\CMS\Language\Text;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;

/**
 * @package     Joomla.Administrator
 * @subpackage  com_faq
 *
 * @copyright   Copyright (C) 2022 Abdul waheed. All rights reserved.
 * @license     GNU General Public License version 3; see LICENSE
 */

class HtmlView extends BaseHtmlView {
    
    /**
     * Display the main "FaqContent" view
     *
     * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
     * @return  void
     */

    protected $items;
    protected $pagination;
    protected $state;
	public $filterForm;
	public $activeFilters;
     
    function display($tpl = null) {

        $this->items         = $this->get('Items');
	    $this->pagination    = $this->get('Pagination');
	    $this->state         = $this->get('State');

	    $this->filterForm    = $this->get('FilterForm');
	    $this->activeFilters = $this->get('ActiveFilters');

        $this->addToolBar();

        parent::display($tpl);

        $this->setDocument(Factory::getDocument());
    }

    protected function addToolBar() {
        ToolbarHelper::title(Text::_("COM_FAQ_LIST"), 'question-circle');
        ToolbarHelper::addNew('faqcontentitem.add');
        ToolbarHelper::editList('faqcontentitem.edit');
        ToolbarHelper::publish('faqcontentitem.publish', 'JTOOLBAR_PUBLISH', true);
        ToolbarHelper::unpublish('faqcontentitem.unpublish', 'JTOOLBAR_UNPUBLISH', true);
        ToolbarHelper::deleteList('', 'faqcontentitem.delete');
    }

    /**
     * Set document title
     */
    public function setDocument(\Joomla\CMS\Document\Document $document): void {
        $document->setTitle(Text::_("COM_FAQ"));
    }

}
THis is the code for file src/Controller/FaqcontentController.php:

Code: Select all

<?php

use Joomla\CMS\MVC\Controller\AdminController;

defined('_JEXEC') or die;

class FaqContentController extends AdminController {    
    public function getModel($name = 'FaqContent', $prefix = 'Faq', $config = array('ignore_request' => true)) {        
        return parent::getModel($name, $prefix, $config);    
    }
}
I want to fix this error and get list with questions, sorting, filter and ordering.
help please to fix error and maybe someone can give me manual.

Thanks

MarkRS
Joomla! Explorer
Joomla! Explorer
Posts: 330
Joined: Thu Oct 29, 2009 8:28 am
Location: UK

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by MarkRS » Tue Mar 26, 2024 4:19 pm

Looks like the line $this->state->get('list-ordering') is at fault, which means that $this->state is null. I see you've got get('State') in your view, but it's not working. You need "populateState" in your model.
It's a community, the more we all contribute, the better it will be.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Tue Mar 26, 2024 9:48 pm

MarkRS wrote:
Tue Mar 26, 2024 4:19 pm
Looks like the line $this->state->get('list-ordering') is at fault, which means that $this->state is null. I see you've got get('State') in your view, but it's not working. You need "populateState" in your model.
Thanks for your answer, I did some modifications of code.

Model:

Code: Select all

<?php

namespace Joomla\Component\Faq\Administrator\Model;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;

defined('_JEXEC') or exit();

class FaqContentModel extends ListModel {

	/**
	 * Конструктор.
	 * @param   array  $config  Массив с конфигурационными параметрами.
	 */
	public function __construct($config = []){
		// Добавляем валидные поля для фильтров и сортировки.
		$config['filter_fields'] = array(
            'id', 'a.id',
            'title', 'a.title',
            'ordering', 'a.ordering',
            'state', 'a.state',
            'publish_up', 'a.publish_up'
        );

		parent::__construct($config);
	}


	/**
     * Method to get a list of items.
     *
     * @return  mixed   An array of data items on success, false on failure.
     */
    public function getItems()
{
    // Get the query for retrieving items
    $query = $this->getQuery();

    // Set the query limits and execute
    $this->setState('list.limit', 0);
    $this->setState('list.start', 0);
    $this->setQuery($query);

    // Get the items from the query using parent::getItems()
    $items = parent::getItems();

    return $items;
}




	/**
	 * Метод для построения SQL запроса для загрузки списка данных.
	 * @return  string  SQL запрос.
	 */
	protected function getQuery(): string
	{

		$db = $this->getDbo();
        $query = $db->getQuery(true);

		$query->select('*');
		$query->from('#__faq_item');

        /* Add Searching */
		$state = $this->getState('filter.state');
		if (is_numeric($state))
		{
			$query->where('state = ' . (int) $state);
		}
		elseif ($state === '')
		{
			$query->where('(state = 0 OR state = 1)');
		}

		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			$search = $db->quote('%' . $db->escape($search, true) . '%', false);
			$query->where('title LIKE ' . $search);
		}

        $published = $this->getState('filter.published');
        if (is_numeric($published)) {    
            $query->where($db->quoteName('published') . ' = ' . $db->quote($published));
        } elseif ($published === '') {    
            $query->whereIn($db->quoteName('published'), array(0, 1));
        }

		// Добавляем сортировку.
		$orderCol  = $this->state->get('list.ordering', 'id');
		$orderDirn = $this->state->get('list.direction', 'desc');
		$query->order($db->escape($orderCol . ' ' . $orderDirn));



		return $query;
	}

	protected function populateState($ordering = 'a.id', $direction = 'desc')
{
    $app = Factory::getApplication();
    $input = $app->input;

    $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
    $this->setState('filter.search', $search);

    $published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
    $this->setState('filter.published', $published);

    // Set the default ordering and direction if not already set
    parent::populateState($ordering, $direction);
}


	/* Prepare a faqcontentiten record for saving in the database */
	protected function prepareTable($table)
	{	
	// Set ordering to the last item if not set
		if (empty($table->ordering))
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->select('MAX(ordering)')
				->from('#__faq_item');

			$db->setQuery($query);
			$max = $db->loadResult();

			$table->ordering = $max + 1;
		}
	}	
}
HtmlView.php

Code: Select all

<?php
namespace Joomla\Component\Faq\Administrator\View\FaqContent;
defined('_JEXEC') or die;

use Joomla\CMS\Language\Text;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;

class HtmlView extends BaseHtmlView {
    
    protected $items;
    protected $pagination;
    protected $state;
    public $filterForm;
    public $activeFilters;
     
    public function display($tpl = null) {
        try {
            // Get model
            $model = $this->getModel('FaqContent', 'Joomla\Component\Faq\Administrator\Model', array('ignore_request' => true));
    
            // Check if the model is properly loaded
            if (!$model) {
                throw new \Exception('Failed to load model.');
            }
    
            // Set state variables
            $model->populateState();
    
            // Get items from the model
            $this->items = $model->getItems();
            $this->pagination = $model->getPagination();
            $this->state = $model->getState();
    
            // Get filter form and active filters
            $this->filterForm = $model->getFilterForm();
            $this->activeFilters = $model->getActiveFilters();
    
            // Add toolbar
            $this->addToolBar();
    
            // Display the view
            parent::display($tpl);
    
            // Set document title
            $this->setDocument(Factory::getDocument());
        } catch (\Exception $e) {
            // Handle any exceptions
            Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
        }
    }    

    protected function addToolBar() {
        ToolbarHelper::title(Text::_("COM_FAQ_LIST"), 'question-circle');
        ToolbarHelper::addNew('faqcontentitem.add');
        ToolbarHelper::editList('faqcontentitem.edit');
        ToolbarHelper::publish('faqcontentitem.publish', 'JTOOLBAR_PUBLISH', true);
        ToolbarHelper::unpublish('faqcontentitem.unpublish', 'JTOOLBAR_UNPUBLISH', true);
        ToolbarHelper::deleteList('', 'faqcontentitem.delete');
    }

    public function setDocument(\Joomla\CMS\Document\Document $document): void {
        $document->setTitle(Text::_("COM_FAQ"));
    }
}

Controller:

Code: Select all

<?php

namespace Joomla\Component\Faq\Administrator\Controller;

use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\CMS\Application\CMSApplication;
use Joomla\Input\Input;

defined('_JEXEC') or die;

class FaqContentController extends AdminController {
    
    public function __construct($config = [], MVCFactoryInterface $factory = null, $app = null, $input = null)
    {
        parent::__construct($config, $factory, $app, $input);

    }

    public function getModel($name = 'FaqContent', $prefix = 'Administrator', $config = ['ignore_request' => true]){
        return parent::getModel($name, $prefix, $config);
    }
}

And I see these errors:
errors.png
Where I have mistake?
You do not have the required permissions to view the files attached to this post.

MarkRS
Joomla! Explorer
Joomla! Explorer
Posts: 330
Joined: Thu Oct 29, 2009 8:28 am
Location: UK

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by MarkRS » Wed Mar 27, 2024 11:05 am

I suspect the problem is your model load line in the view file. You don't need to do that at all.

Instead of your "$this->thing = $model->get<thing>();" lines you want "$this->thing = $this->get('<thing>');". The default model, which is the way you've (correctly) structured your model, will be loaded automatically and used.

Also I would suggest your namespace is badly named. Replacing the "Joomla" for something specific to you will keep your code out of the main Joomla namespace and better separated.

You also don't need the __construct method in the controller. The controller *does* need to be there, but you don't need to re-implement any methods that simply call their parents.
It's a community, the more we all contribute, the better it will be.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Wed Mar 27, 2024 11:10 pm

MarkRS wrote:
Wed Mar 27, 2024 11:05 am
I suspect the problem is your model load line in the view file. You don't need to do that at all.

Instead of your "$this->thing = $model->get<thing>();" lines you want "$this->thing = $this->get('<thing>');". The default model, which is the way you've (correctly) structured your model, will be loaded automatically and used.

Also I would suggest your namespace is badly named. Replacing the "Joomla" for something specific to you will keep your code out of the main Joomla namespace and better separated.

You also don't need the __construct method in the controller. The controller *does* need to be there, but you don't need to re-implement any methods that simply call their parents.
THanks for your help, I'll do all these modifications, but also have error, but another.

Now I see error:

"0 Incorrect controller class: display"

code for controller:

Code: Select all

<?php

namespace VPJoomla\Component\Faq\Administrator\Controller;

use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\CMS\Application\CMSApplication;
use Joomla\Input\Input;

defined('_JEXEC') or die;

class FaqContentController extends AdminController {

    public function getModel($name = 'FaqContent', $prefix = 'Administrator', $config = ['ignore_request' => true]){
        return parent::getModel($name, $prefix, $config);
    }

    public function display($cachable = false, $urlparams = array()) {
        return parent::display($cachable, $urlparams);
    }
}
code for model:

Code: Select all

<?php

namespace VPJoomla\Component\Faq\Administrator\Model;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;

defined('_JEXEC') or exit();

class FaqContentModel extends ListModel {

	/**
	 * Конструктор.
	 * @param   array  $config  Массив с конфигурационными параметрами.
	 */
	public function __construct($config = []){
		// Добавляем валидные поля для фильтров и сортировки.
		$config['filter_fields'] = array(
            'id', 'a.id',
            'title', 'a.title',
            'ordering', 'a.ordering',
            'state', 'a.state',
            'publish_up', 'a.publish_up'
        );

		parent::__construct($config);
	}


	/**
     * Method to get a list of items.
     *
     * @return  mixed   An array of data items on success, false on failure.
     */
    public function getItems()
{
    // Get the query for retrieving items
    $query = $this->getQuery();

    // Set the query limits and execute
    $this->setState('list.limit', 0);
    $this->setState('list.start', 0);
    $this->setQuery($query);

    // Get the items from the query using parent::getItems()
    $items = parent::getItems();

    return $items;
}




	/**
	 * Метод для построения SQL запроса для загрузки списка данных.
	 * @return  string  SQL запрос.
	 */
	protected function getQuery(): string
	{

		$db = $this->getDbo();
        $query = $db->getQuery(true);

		$query->select('*');
		$query->from('#__faq_item');

        /* Add Searching */
		$state = $this->getState('filter.state');
		if (is_numeric($state))
		{
			$query->where('state = ' . (int) $state);
		}
		elseif ($state === '')
		{
			$query->where('(state = 0 OR state = 1)');
		}

		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			$search = $db->quote('%' . $db->escape($search, true) . '%', false);
			$query->where('title LIKE ' . $search);
		}

        $published = $this->getState('filter.published');
        if (is_numeric($published)) {    
            $query->where($db->quoteName('published') . ' = ' . $db->quote($published));
        } elseif ($published === '') {    
            $query->whereIn($db->quoteName('published'), array(0, 1));
        }

		// Добавляем сортировку.
		$orderCol  = $this->state->get('list.ordering', 'id');
		$orderDirn = $this->state->get('list.direction', 'desc');
		$query->order($db->escape($orderCol . ' ' . $orderDirn));



		return $query;
	}

	protected function populateState($ordering = 'a.id', $direction = 'desc')
{
    $app = Factory::getApplication();
    $input = $app->input;

    $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
    $this->setState('filter.search', $search);

    $published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
    $this->setState('filter.published', $published);

    // Set the default ordering and direction if not already set
    parent::populateState($ordering, $direction);
}


	/* Prepare a faqcontentiten record for saving in the database */
	protected function prepareTable($table)
	{	
	// Set ordering to the last item if not set
		if (empty($table->ordering))
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->select('MAX(ordering)')
				->from('#__faq_item');

			$db->setQuery($query);
			$max = $db->loadResult();

			$table->ordering = $max + 1;
		}
	}	
}
code for view:

Code: Select all

<?php

namespace VPJoomla\Component\Faq\Administrator\View\FaqContent;

defined('_JEXEC') or die;

use Joomla\CMS\Language\Text;
use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;

class HtmlView extends BaseHtmlView {
    
    protected $items;
    protected $pagination;
    protected $state;
    public $filterForm;
    public $activeFilters;
     
    public function display($tpl = null) {
        
            $this->items      = $this->get('Items');
            $this->pagination = $this->get('Pagination');
            $this->state      = $this->get('State');
    
            // Get filter form and active filters
            $this->filterForm    = $this->get('FilterForm');
            $this->activeFilters = $this->get('ActiveFilters');
    
            // Add toolbar
            $this->addToolBar();
    
            // Display the view
            parent::display($tpl);
    
            // Set document title
            $this->setDocument(Factory::getDocument());
    }    

    protected function addToolBar() {
        ToolbarHelper::title(Text::_("COM_FAQ_LIST"), 'question-circle');
        ToolbarHelper::addNew('faqcontentitem.add');
        ToolbarHelper::editList('faqcontentitem.edit');
        ToolbarHelper::publish('faqcontentitem.publish', 'JTOOLBAR_PUBLISH', true);
        ToolbarHelper::unpublish('faqcontentitem.unpublish', 'JTOOLBAR_UNPUBLISH', true);
        ToolbarHelper::deleteList('', 'faqcontentitem.delete');
    }

    public function setDocument(\Joomla\CMS\Document\Document $document): void {
        $document->setTitle(Text::_("COM_FAQ"));
    }
}
Really strange...

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Wed Mar 27, 2024 11:23 pm

MarkRS wrote:
Wed Mar 27, 2024 11:05 am
I suspect the problem is your model load line in the view file. You don't need to do that at all.

Instead of your "$this->thing = $model->get<thing>();" lines you want "$this->thing = $this->get('<thing>');". The default model, which is the way you've (correctly) structured your model, will be loaded automatically and used.

Also I would suggest your namespace is badly named. Replacing the "Joomla" for something specific to you will keep your code out of the main Joomla namespace and better separated.

You also don't need the __construct method in the controller. The controller *does* need to be there, but you don't need to re-implement any methods that simply call their parents.
Maybe it will be more simple if I'll attach all code of component here.
com_faq.zip
You do not have the required permissions to view the files attached to this post.

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Thu Mar 28, 2024 6:29 am

You're passing the wrong namespace prefix in your service provider:

Code: Select all

$container->registerServiceProvider(new MVCFactory('\\Joomla\\Component\\Faq'));
$container->registerServiceProvider(new ComponentDispatcherFactory('\\Joomla\\Component\\Faq'));
Instead of your "$this->thing = $model->get<thing>();" lines you want "$this->thing = $this->get('<thing>');".
Please don't follow this advice. It's an ancient borderline magic method that only makes things harder to debug. It really should have been removed a long time ago.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Thu Mar 28, 2024 9:28 am

SharkyKZ wrote:
Thu Mar 28, 2024 6:29 am
You're passing the wrong namespace prefix in your service provider:

Code: Select all

$container->registerServiceProvider(new MVCFactory('\\Joomla\\Component\\Faq'));
$container->registerServiceProvider(new ComponentDispatcherFactory('\\Joomla\\Component\\Faq'));
Instead of your "$this->thing = $model->get<thing>();" lines you want "$this->thing = $this->get('<thing>');".
Please don't follow this advice. It's an ancient borderline magic method that only makes things harder to debug. It really should have been removed a long time ago.
Thanks, I fixed provider.php, but again I got the same error like in my first message of this topic:

Code: Select all

0 Call to a member function get() on null
 in JROOT/administrator/components/com_faq/tmpl/faqcontent/default.php:17
service/provider.php:

Code: Select all

<?php
defined('_JEXEC') or die;
use Joomla\CMS\Dispatcher\ComponentDispatcherFactoryInterface;
use Joomla\CMS\Extension\ComponentInterface;
use Joomla\CMS\Extension\MVCComponent;
use Joomla\CMS\Extension\Service\Provider\ComponentDispatcherFactory;
use Joomla\CMS\Extension\Service\Provider\MVCFactory;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\DI\Container;
use Joomla\DI\ServiceProviderInterface;

return new class implements ServiceProviderInterface {
    
    public function register(Container $container): void {
        $container->registerServiceProvider(new MVCFactory('\\VPJoomla\\Component\\Faq'));
        $container->registerServiceProvider(new ComponentDispatcherFactory('\\VPJoomla\\Component\\Faq'));
        $container->set(
            ComponentInterface::class,
            function (Container $container) {
                $component = new MVCComponent($container->get(ComponentDispatcherFactoryInterface::class));
                $component->setMVCFactory($container->get(MVCFactoryInterface::class));

                return $component;
            }
        );
    }
};
?>

MarkRS
Joomla! Explorer
Joomla! Explorer
Posts: 330
Joined: Thu Oct 29, 2009 8:28 am
Location: UK

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by MarkRS » Thu Mar 28, 2024 9:29 am

SharkyKZ wrote:
Thu Mar 28, 2024 6:29 am
Instead of your "$this->thing = $model->get<thing>();" lines you want "$this->thing = $this->get('<thing>');".
Please don't follow this advice. It's an ancient borderline magic method that only makes things harder to debug. It really should have been removed a long time ago.
Really? You mean the view really should getModel() itself and use that rather than (eg) $this->get('Item')?

I'm just curious. As far as I've seen, all the core, and all the documentation, does the latter.
It's a community, the more we all contribute, the better it will be.

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Thu Mar 28, 2024 9:56 am

zeus07 wrote:
Thu Mar 28, 2024 9:28 am

Thanks, I fixed provider.php, but again I got the same error like in my first message of this topic:

Code: Select all

0 Call to a member function get() on null
 in JROOT/administrator/components/com_faq/tmpl/faqcontent/default.php:17
I couldn't reproduce the issue on Windows so I suspect it's a class casing issue. The default model is set on the view based on view's name. Your view is named Faqcontent but your model is FaqContent. You should rename one or the other to use the same casing, or manually set the model on the view in your controller.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Thu Mar 28, 2024 10:10 am

SharkyKZ wrote:
Thu Mar 28, 2024 9:56 am
zeus07 wrote:
Thu Mar 28, 2024 9:28 am

Thanks, I fixed provider.php, but again I got the same error like in my first message of this topic:

Code: Select all

0 Call to a member function get() on null
 in JROOT/administrator/components/com_faq/tmpl/faqcontent/default.php:17
I couldn't reproduce the issue on Windows so I suspect it's a class casing issue. The default model is set on the view based on view's name. Your view is named Faqcontent but your model is FaqContent. You should rename one or the other to use the same casing, or manually set the model on the view in your controller.
If I changing the name of model or view, my component can't find view.

I recreated function getListQuery - but also the same error...

Model file:

Code: Select all

<?php

namespace VPJoomla\Component\Faq\Administrator\Model;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;

defined('_JEXEC') or exit();

class FaqContentModel extends ListModel {

	/**
	 * Конструктор.
	 * @param   array  $config  Массив с конфигурационными параметрами.
	 */
	public function __construct($config = []){
		// Добавляем валидные поля для фильтров и сортировки.
		$config['filter_fields'] = array(
            'id', 'a.id',
            'title', 'a.title',
            'ordering', 'a.ordering',
            'state', 'a.state',
            'publish_up', 'a.publish_up'
        );

		parent::__construct($config);
	}


	/**
     * Method to get a list of items.
     *
     * @return  mixed   An array of data items on success, false on failure.
     */
    public function getItems()
{
    // Get the query for retrieving items
    $query = $this->getQuery();

    // Set the query limits and execute
    $this->setState('list.limit', 0);
    $this->setState('list.start', 0);
    $this->setQuery($query);

    // Get the items from the query using parent::getItems()
    $items = parent::getItems();

    return $items;
}




	/**
	 * Метод для построения SQL запроса для загрузки списка данных.
	 * @return  string  SQL запрос.
	 */
	protected function getListQuery(): string
	{

		$db    = $this->getDatabase();
        $query = $db->getQuery(true);

		//$query->select('*');
		//$query->from('#__faq_item');

		$query->select(
            $this->getState(
                'list.select',
                [
                    $db->quoteName('a.id'),
                    $db->quoteName('a.title'),
                    $db->quoteName('a.state'),
                    $db->quoteName('a.publish_up'),
					$db->quoteName('a.ordering'),
				]
            )
        )
			->from($db->quoteName('#__faq_item', 'a'));


        // Фильтр по состоянию полученному из запроса
        $published = (string) $this->getState('filter.published');
 
        if (is_numeric($published))
        {
            $query->where($db->quoteName('a.state') . ' = :published');
            $query->bind(':published', $published, ParameterType::INTEGER);
        }
        elseif ($published === '')
        {
            $query->where('(' . $db->quoteName('a.state') . ' = 0 OR ' . $db->quoteName('a.state') . ' = 1)');
        }
 
        // Фильтр поиска по названию.
        $search = $this->getState('filter.search');
 
        if (!empty($search))
        {
            $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
            $query->where('(a.title LIKE ' . $search . ')');
        }


		// Добавляем сортировку.
		$orderCol  = $this->state->get('list.ordering', 'id');
		$orderDirn = $this->state->get('list.direction', 'desc');
		$query->order($db->escape($orderCol . ' ' . $orderDirn));



		return $query;
	}

	protected function populateState($ordering = 'a.id', $direction = 'desc')
{
    $app = Factory::getApplication();
    $input = $app->input;

    $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
    $this->setState('filter.search', $search);

    $published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
    $this->setState('filter.published', $published);

    // Set the default ordering and direction if not already set
    parent::populateState($ordering, $direction);
}


	/* Prepare a faqcontentiten record for saving in the database */
	protected function prepareTable($table)
	{	
	// Set ordering to the last item if not set
		if (empty($table->ordering))
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->select('MAX(ordering)')
				->from('#__faq_item');

			$db->setQuery($query);
			$max = $db->loadResult();

			$table->ordering = $max + 1;
		}
	}	
}
All code for component
com_faq.zip
You do not have the required permissions to view the files attached to this post.

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Thu Mar 28, 2024 12:28 pm

Renaming the model should not cause the view not to be found. I tried renaming to FaqcontentModel and it works fine. Using this naming convention would be the simplest solution. Other options include setting the model manually, overriding view's getName() method or even implementing your own MVC stack.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Thu Mar 28, 2024 12:31 pm

SharkyKZ wrote:
Thu Mar 28, 2024 12:28 pm
Renaming the model should not cause the view not to be found. I tried renaming to FaqcontentModel and it works fine. Using this naming convention would be the simplest solution. Other options include setting the model manually, overriding view's getName() method or even implementing your own MVC stack.
What else you renaming? Can you give me a code? Which file you edited?

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Thu Mar 28, 2024 12:43 pm

I just renamed FaqContentModel class to FaqcontentModel and its file to FaqcontentModel.php. Now I see this error but the fix is obvious:
Call to undefined method VPJoomla\Component\Faq\Administrator\Model\FaqcontentModel::getQuery()

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Thu Mar 28, 2024 12:50 pm

SharkyKZ wrote:
Thu Mar 28, 2024 12:43 pm
I just renamed FaqContentModel class to FaqcontentModel and its file to FaqcontentModel.php. Now I see this error but the fix is obvious:
Call to undefined method VPJoomla\Component\Faq\Administrator\Model\FaqcontentModel::getQuery()
Thanks, I understand you. Now I renamed classes and files and this page works good, but have some troubles with displaying items only.
I will edit the default.php of this page next to fix errors :)
THanks for help!

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Fri Mar 29, 2024 8:19 am

MarkRS wrote:
Thu Mar 28, 2024 9:29 am
Really? You mean the view really should getModel() itself and use that rather than (eg) $this->get('Item')?

I'm just curious. As far as I've seen, all the core, and all the documentation, does the latter.
Neither is great but getModel() is certainly better. get() is a pointless proxy method that only makes things harder to debug. This thread showcases that. We can see that $this->get('State') returns null but no way of telling why. Is it because the model is not set? Or maybe the model has no getState() method? Or maybe getState() method simply returns null? Or view's $state property is null? get() doesn't even say anywhere that it calls model's get<Something> method. You have to read external documentation or inspect the source code yourself.

Meanwhile, if you called $this->getModel()->getState(), you would instantly see that you're calling getState() method on null. This alone makes finding the culprit easier. Furthermore, you can add handling for the null case as well as some autocompletion:

Code: Select all

/** @var ?\VPJoomla\Component\Faq\Administrator\Model\FaqcontentModel */
$model = $this->getModel();

if ($model === null)
{
	throw new \SomeException('Model not set in view...');
}

$this->state = $model->getState();
This is much clearer than blindly using get() method but it's still far from ideal.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Fri Mar 29, 2024 9:03 am

SharkyKZ wrote:
Fri Mar 29, 2024 8:19 am
MarkRS wrote:
Thu Mar 28, 2024 9:29 am
Really? You mean the view really should getModel() itself and use that rather than (eg) $this->get('Item')?

I'm just curious. As far as I've seen, all the core, and all the documentation, does the latter.
Neither is great but getModel() is certainly better. get() is a pointless proxy method that only makes things harder to debug. This thread showcases that. We can see that $this->get('State') returns null but no way of telling why. Is it because the model is not set? Or maybe the model has no getState() method? Or maybe getState() method simply returns null? Or view's $state property is null? get() doesn't even say anywhere that it calls model's get<Something> method. You have to read external documentation or inspect the source code yourself.

Meanwhile, if you called $this->getModel()->getState(), you would instantly see that you're calling getState() method on null. This alone makes finding the culprit easier. Furthermore, you can add handling for the null case as well as some autocompletion:

Code: Select all

/** @var ?\VPJoomla\Component\Faq\Administrator\Model\FaqcontentModel */
$model = $this->getModel();

if ($model === null)
{
	throw new \SomeException('Model not set in view...');
}

$this->state = $model->getState();
This is much clearer than blindly using get() method but it's still far from ideal.
Thanks for your advice. This view working, but now I have another errors :)
for example, if I'll try to add new item, I see this error:

Code: Select all

0 Call to a member function get() on null in JROOT/administrator/components/com_faq/src/View/Faqcontentitem/HtmlView.php:58
I understand the error in my file edit.php and Joomla gan't get fields, but why it can't get fields I can't understand. Maybe you can help me?

When I'll trying to edit item, I see this error:

Code: Select all

0 Call to a member function getTable() on false in JROOT/libraries/src/MVC/Controller/FormController.php:365
I added here code for component
You do not have the required permissions to view the files attached to this post.

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Fri Mar 29, 2024 9:26 am

First error is because $canDo is undefined. Second is because the file containing FaqContentitemModel is missing a namespace declaration.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Fri Mar 29, 2024 9:47 am

SharkyKZ wrote:
Fri Mar 29, 2024 9:26 am
First error is because $canDo is undefined. Second is because the file containing FaqContentitemModel is missing a namespace declaration.
I tried to add this variable in file like

Code: Select all

protected $canDo;
But after this the next error:

Code: Select all

0 syntax error, unexpected variable "$canDo", expecting "function"
About model you are right. But after this I see next error:

Code: Select all

0 Call to a member function get() on null in JROOT/administrator/components/com_faq/src/View/Faqcontentitem/HtmlView.php:60
This is code for HtmlView.php

Code: Select all

<?php

namespace VPJoomla\Component\Faq\Administrator\View\Faqcontentitem;

defined('_JEXEC') or exit();

use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;

/**
 * @package     Joomla.Administrator
 * @subpackage  com_faq
 *
 * @copyright   Copyright (C) 2022 Abdul waheed. All rights reserved.
 * @license     GNU General Public License version 3; see LICENSE
 */

class HtmlView extends BaseHtmlView {

    protected $form;
    protected $item;
    protected $state;
    protected $canDo;
    
    public function display($tpl = null) {

        var_dump($this->form);

        $this->form = $this->get('Form');
        $this->item = $this->get('Item');
        $this->state = $this->get('State');

        $this->canDo = ContentHelper::getActions('com_faq', 'faqcontentitem', $this->item->id);

        $this->addToolBar();
    
    // Get the document object
        $document = Factory::getDocument();
        parent::display($tpl);

        // Pass the document object to setDocument()
        $this->setDocument($document);
    }

    /**
     * Add toolbar
     */
    protected function addToolBar() {

        Factory::getApplication()->input->set('hidemainmenu', true);

		$toolbar = Toolbar::getInstance();

        ToolbarHelper::title(Text::_("COM_FAQ_EDIT"), 'question-circle');

		if ($canDo->get('core.create') || ($canDo->get('core.edit') && $this->item->id > 0))
        {
            $toolbar->addNew('faqcontentitem.add');
            $toolbar->apply('faqcontentitem.apply');
			$toolbar->save('faqcontentitem.save');
            $toolbar->save2copy('faqcontentitem.save2copy');
        }

		if (empty($this->item->id))
		{
			$toolbar->cancel('faqcontentitem.cancel', 'JTOOLBAR_CANCEL');
		}
		else
		{
			$toolbar->cancel('faqcontentitem.cancel', 'JTOOLBAR_CLOSE');
		}
    }

    /**
     * Set document title
     */
    public function setDocument(\Joomla\CMS\Document\Document $document): void {
        $document->setTitle(Text::_("COM_FAQ_EDIT"));
    }
}


SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Fri Mar 29, 2024 9:52 am

The local $canDo variable inside addToolBar() is still undefined. You can change it to $this->canDo now. Also you should use an IDE to help with errors like this.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Fri Mar 29, 2024 9:56 am

SharkyKZ wrote:
Fri Mar 29, 2024 9:52 am
The local $canDo variable inside addToolBar() is still undefined. You can change it to $this->canDo now. Also you should use an IDE to help with errors like this.
Yes, I'm use Visual code or PhpStorm.

After last edit I see error out of memory

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Fri Mar 29, 2024 1:05 pm

Out of memory error is due to var_dump(). Joomla has trouble dumping certain objects due to recursion. An issue has been raised but was closed without fix. Instead of var_dump() use Symfony's dump() function or install Xdebug PHP extension.
Last edited by SharkyKZ on Fri Mar 29, 2024 2:22 pm, edited 1 time in total.

MarkRS
Joomla! Explorer
Joomla! Explorer
Posts: 330
Joined: Thu Oct 29, 2009 8:28 am
Location: UK

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by MarkRS » Fri Mar 29, 2024 1:54 pm

SharkyKZ wrote:
Fri Mar 29, 2024 8:19 am
Neither is great but getModel() is certainly better. get() is a pointless proxy method that only makes things harder to debug. This thread showcases that.
Yup, fair enough. I s'pose I've just got used to it.

SharkyKZ wrote:
Fri Mar 29, 2024 8:19 am
You have to read external documentation or inspect the source code yourself.
That goes for a large part of the system :eek: >:(
It's a community, the more we all contribute, the better it will be.

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Fri Mar 29, 2024 10:10 pm

AS I understood, function $canDo use only if you use ACL in your custom component. Now I don't now how to correctly use ACL and how to work with it, therefore I deleted $canDo from my view.
I can create item, save it or edit and save. But after this I see always these error:

Code: Select all

404 Can't find view [name, type, prefix]: faqcontentitems, html, Administrator.
I can't understand why it trying to find view "faqcontentitems", if view with list of items has name "faqcontent".

Can you help me?

Below code for component.
com_faq.zip
You do not have the required permissions to view the files attached to this post.

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2910
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by SharkyKZ » Sat Mar 30, 2024 9:44 am

Joomla derives list view name by pluralizing the item view. If you stick with core MVC, that would be the convention to follow. But alternatively you can declare the list view name in your controller:

Code: Select all

class FaqcontentitemController extends FormController {
    protected $view_list = 'faqcontent';
}

zeus07
Joomla! Apprentice
Joomla! Apprentice
Posts: 48
Joined: Fri Feb 05, 2016 12:25 am

Re: How to fix error 00 Call to a member function get() on null ($listOrder)

Post by zeus07 » Sat Mar 30, 2024 10:36 pm

SharkyKZ wrote:
Sat Mar 30, 2024 9:44 am
Joomla derives list view name by pluralizing the item view. If you stick with core MVC, that would be the convention to follow. But alternatively you can declare the list view name in your controller:

Code: Select all

class FaqcontentitemController extends FormController {
    protected $view_list = 'faqcontent';
}
Thanks! Now it works good!

I have another questions about buttons in Toolbar , I mean buttons in Actions. Now, if I'll click on item state in list items - working publishing and unpublishing. But if I'll use button Actions - nothing works. I mean all buttons: Publish, Unpubkish, Archive, Trash.

How I can fix it? Maybe I should to add some methods in model?

This is FaqcontentModel.php:

Code: Select all

<?php

namespace VPJoomla\Component\Faq\Administrator\Model;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\ListModel;
use Joomla\Database\ParameterType;

defined('_JEXEC') or exit();

class FaqcontentModel extends ListModel {

	/**
	 * Конструктор.
	 * @param   array  $config  Массив с конфигурационными параметрами.
	 */
	public function __construct($config = []){
		// Добавляем валидные поля для фильтров и сортировки.
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
            	'id', 'a.id',
            	'title', 'a.title',
            	'ordering', 'a.ordering',
            	'state', 'a.state',
            	'publish_up', 'a.publish_up'
        	);
		}

		parent::__construct($config);
	}


	/**
     * Method to get a list of items.
     *
     * @return  mixed   An array of data items on success, false on failure.
     */
    public function getItems()
    {
        $items = parent::getItems();
 
        return $items;
    }




	/**
	 * Метод для построения SQL запроса для загрузки списка данных.
	 * @return  string  SQL запрос.
	 */
	protected function getListQuery(): string
	{

		$db    = $this->getDatabase();
        $query = $db->getQuery(true);

		//$query->select('*');
		//$query->from('#__faq_item');

		$query->select(
            $this->getState(
                'list.select',
                [
                    $db->quoteName('a.id'),
                    $db->quoteName('a.title'),
                    $db->quoteName('a.state'),
                    $db->quoteName('a.publish_up'),
					$db->quoteName('a.ordering'),
				]
            )
        )
			->from($db->quoteName('#__faq_item', 'a'));


        // Фильтр по состоянию полученному из запроса
        $published = (string) $this->getState('filter.published');
 
        if (is_numeric($published))
        {
            $query->where($db->quoteName('a.state') . ' = :published');
            $query->bind(':published', $published, ParameterType::INTEGER);
        }
        elseif ($published === '')
        {
            $query->where('(' . $db->quoteName('a.state') . ' = 0 OR ' . $db->quoteName('a.state') . ' = 1)');
        }
 
        // Фильтр поиска по названию.
        $search = $this->getState('filter.search');
 
        if (!empty($search))
        {
            $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
            $query->where('(a.title LIKE ' . $search . ')');
        }


		// Добавляем сортировку.
		$orderCol  = $this->state->get('list.ordering', 'id');
		$orderDirn = $this->state->get('list.direction', 'desc');
		$query->order($db->escape($orderCol . ' ' . $orderDirn));



		return $query;
	}

	protected function populateState($ordering = 'a.id', $direction = 'desc')
{
    $app = Factory::getApplication();
    $input = $app->input;

    $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
    $this->setState('filter.search', $search);

    $published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
    $this->setState('filter.published', $published);

    // Set the default ordering and direction if not already set
    parent::populateState($ordering, $direction);
}

protected function getStoreId($id = '')
{
	// Compile the store id.
	$id .= ':' . $this->getState('filter.search');
	$id .= ':' . $this->getState('filter.published');

	return parent::getStoreId($id);
}


	/* Prepare a faqcontentiten record for saving in the database */
	protected function prepareTable($table)
	{	
	// Set ordering to the last item if not set
		if (empty($table->ordering))
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->select('MAX(ordering)')
				->from('#__faq_item');

			$db->setQuery($query);
			$max = $db->loadResult();

			$table->ordering = $max + 1;
		}
	}

    /**
     * Method to change the published state of one or more records.
     *
     * @param array    &$pks   A list of the primary keys to change.
     * @param integer $value  The value of the published state.
     *
     * @return  boolean  True on success.
     *
     * @since   4.0.0
     */
    public function publish(array &$pks, int $value = 1) {
        if (empty($pks)) {
            return false; // No records to update
        }

        $db = $this->getDatabase();

        // Sanitize the value
        $value = (int) $value;

        try {
            $query = $db->getQuery(true)
                ->update($db->quoteName('#__faq_item'))
                ->set($db->quoteName('state') . ' = ' . $value)
                ->whereIn($db->quoteName('id'), $pks);

            $db->setQuery($query);
            $db->execute();

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

}


Post Reply

Return to “Joomla! 4.x Coding”