How can load Model function in block when overide or extend a core magento block
-
13-12-2019 - |
Solution
Following way you can get object manager instance
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
Now you can get/create any model or model collection. Here is an example of order collection.
$orderCollection = $objectManager->get('Magento\Sales\Model\Order')->getCollection()
OTHER TIPS
In Magento 2 constructor is not part of public API and you can change it (add more dependencies). And you should do not call ObjectManager direct.
in your case, add constructor with order factory
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Directory\Helper\Data $directoryHelper,
\Magento\Framework\Json\EncoderInterface $jsonEncoder,
\Magento\Framework\App\Cache\Type\Config $configCacheType,
\Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory,
\Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
\Magento\Framework\Module\Manager $moduleManager,
\Magento\Customer\Model\Session $customerSession,
\Magento\Customer\Model\Url $customerUrl,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,
array $data = []
) {
parent::__construct(...);
$this->collectionFactory = $collectionFactory;
and in method hello use it
public function hello()
{
return $this->collectionFactory->create()->load();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange