【发布时间】:2020-02-16 14:36:28
【问题描述】:
完整代码的链接。 Download from here
我正在学习 Magento 2,现在遇到了一个错误。 这是调用我的前端视图块时的错误消息。
Fatal error: Uncaught Error: Call to a member function dispatch() on null in C:\wamp64\www\magento2\vendor\magento\framework\Model\ResourceModel\Db\Collection\AbstractCollection.php:541 Stack trace: #0 C:\wamp64\www\magento2\vendor\magento\framework\Data\Collection\AbstractDb.php(577): Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection->_beforeLoad() #1 C:\wamp64\www\magento2\vendor\magento\framework\Data\Collection\AbstractDb.php(565): Magento\Framework\Data\Collection\AbstractDb->loadWithFilter(false, false) #2 C:\wamp64\www\magento2\vendor\magento\framework\Data\Collection.php(333): Magento\Framework\Data\Collection\AbstractDb->load() #3 C:\wamp64\www\magento2\app\code\Mastering\SampleModule\Block\Hello.php(19): Magento\Framework\Data\Collection->getItems() #4 C:\wamp64\www\magento2\app\code\Mastering\SampleModule\view\frontend\templates\hello.phtml(7): Mastering\SampleModule\Block\Hello->getItems() #5 C:\wamp64\www\magento2\vendor\magento\framework\View\TemplateEngine\Php.php(59): include('C:\\wamp in C:\wamp64\www\magento2\vendor\magento\framework\Model\ResourceModel\Db\Collection\AbstractCollection.php on line 541
这是我卡在 Hello.php 类中的代码。
<?php
namespace Mastering\SampleModule\Block;
use Magento\Framework\View\Element\Template;
use Mastering\SampleModule\Model\ResourceModel\Item\CollectionFactory;
class Hello extends Template {
private $collectionFactory;
public function __construct(Template\Context $context, CollectionFactory $collectionFactory, array $data = [] ){
$this->collectionFactory = $collectionFactory;
parent::__construct($context, $data);
}
public function getItems() {
return $this->collectionFactory->create()->getItems();
}
}
Collection.php 类
namespace Mastering\SampleModule\Model\ResourceModel\Item;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Mastering\SampleModule\Model\Item;
use Mastering\SampleModule\Model\ResourceModel\Item as ItemResource;
class Collection extends AbstractCollection {
protected $_idFieldName = 'id';
public function __construct() {
$this->_init( Item::class, ItemResource::class );
}
}
app\code\Mastering\SampleModule\view\frontend\layout\mastering_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block name="mastering_hello" class="Mastering\SampleModule\Block\Hello" template="hello.phtml" />
</referenceContainer>
</body>
</page>
Hello.phtml 查看文件
<?php
/** @var \Mastering\SampleModule\Block\Hello $block */
//var_dump($block->getItems());
?>
<?php foreach($block->getItems() as $item ): ?>
<p>
<?php echo $item->getName(); ?>: <?php $item->getDescription(); ?>
</p>
<?php endforeach; ?>
【问题讨论】:
-
我也面临类似的问题。