2

I want to get block Magento\Catalog\Block\Product\ProductList\Toolbar, I tried this code but it not work and show error

Type Error occurred when creating the object: `Vendor/Module/Block/Search`

My code

$resultPage = $this->layoutFactory->create();
$blockToolbar = $resultPage->getLayout()->createBlock('Magento\Catalog\Block\Product\ProductList\Toolbar');
var_dump($blockToolbar->getCurrentOrder());
exit;

I tried " Code phtml " in phtml file, it works

Code phtml

$blockToolbar = $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ProductList\Toolbar');
var_dump($blockToolbar->getCurrentOrder());exit;

UPDATE

I used $objectManager and it works

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$blockToolbar = $objectManager->create('Magento\Catalog\Block\Product\ProductList\Toolbar');
var_dump($blockToolbar->getCurrentOrder());
exit;

2 Answers 2

1

You can call block function using below ways :

Method 1:

protected $layoutFactory;

public function __construct(
   ...
   \Magento\Framework\View\LayoutFactory $layoutFactory,
   ...
) {
   ...
   $this->layoutFactory = $layoutFactory;
   ...
}

Then you can instantiate a block like this:

$block = $this->layoutFactory->create()->createBlock('Magento\Catalog\Block\Product\ProductList\Toolbar');
var_dump($block->getCurrentOrder());exit;

Method 2 :

$block = $this->getLayout()->createBlock('Magento\Catalog\Block\Product\ProductList\Toolbar');    
var_dump($block->getCurrentOrder());exit;
0

You should return value, Follow below code

$resultPage = $this->resultPageFactory->create();
$blockToolbar = $resultPage->getLayout()->createBlock('Magento\Catalog\Block\Product\ProductList\Toolbar');
return $resultPage;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.