Magento2 Block Error – Call to a Member Function Create() on Null

magento2

I want to display my custom database's data on customer side but when I try to get the data from the collection factory I am getting this error.

Call to a member function create() on null in /var/www/html/magento/app/code///Block/.php:40

Below this is my block's code.

class Webkul extends \Magento\Framework\View\Element\Template
{

protected $_gridFactory;

public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Webkul\Grid\Model\GridFactory $gridFactory)
{
    parent::__construct($context);
    $this->_girdFactory = $gridFactory;
}

public function getCollectionFor()
{
    $custom_variable = $this->_gridFactory->create();
    $collection = $custom_variable->getCollection();
    foreach($collection as $item){
        var_dump($item->getData());
    }
    exit;
}
}

I tried to get value in the $custom_variable but it has nothing.

Collection.php file

<?php

namespace Webkul\Grid\Model\ResourceModel\Grid;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected $_idFieldName = 'entity_id';
    /**
     * Define resource model.
     */
    protected function _construct()
    {
        $this->_init('Webkul\Grid\Model\Grid', 'Webkul\Grid\Model\ResourceModel\Grid');
    }
}

Best Answer

can you please try using objectmanager. I know it's not proper way but it might help you.

public function getCollectionFor()
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();
    $tableName = $resource->getTableName('your table name');


    $sql = "Select * FROM " . $tableName;
    $result = $connection->fetchAll($sql);
    return $result;
}

now call your function in your phtml file.