Layouts play a major role in Magento to override existing core files without affecting a system. Magento supports various types of layouts like 1 column, 2 column-left, 2 column-right, 3 columns, etc. The structure of all pages is described in the layout file. Technically, a layout is an .xml file which contains declarations and different instructions. When it comes to building a page inside your store to give a touch of the personalized store environment, you need to change your layout file at the end. But What if you acquire dynamic layout programmatically?
Today, I’m again back with a small piece of code that will help you to easily override page layout programmatically in Magento 2. You can even set page layout of the controller action which resides on similar location like this.
Go to app/code/Vendor/Extension/Controller/Youraction/Action.php ans paste below code here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!--?php namespace Vendor\Extension\Controller\Youraction; use Magento\Framework\Controller\ResultFactory; class Action extends \Magento\Framework\App\Action\Action { public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory ) { $this->resultPageFactory = $resultPageFactory; parent::__construct($context); } public function execute() { $page = $this->resultPageFactory->create(false, ['isIsolated' => true]); // YOUR LOGIC TO GET SELECTED LAYOUT $youradminlayout = ‘YOUR_LAYOUT’; $page->getConfig()->setPageLayout($youradminlayout); return $page; } } </pre> <p>Once you implement above code you will able to override page layout inside your Magento 2 stores successfully. You can simply modify this code according to your need. Hit the stars below and comment down if you need help to implement this code.<br ?--> Happy Overriding! |
Hi Dhiren,
I am new to magento
i followed same steps as like u mentioned in this page :override-page-layout-programmatically-magento-2/
like:
public function execute()
{
if($this->getRequest()->getParam(‘order_id’)){
$customerId = $this->customerSession->getCustomerId();
$order = $this->orderFactory->create()->load($this->getRequest()->getParam(‘order_id’));
if ($order->getId()
&& $order->getCustomerId()
&& $order->getCustomerId() == $customerId){
$this->registry->register(‘current_order’, $order);
}else{
$resultRedirect = $this->redirectFactory->create();
return $resultRedirect->setUrl($this->url->getUrl(‘*/*/history’));
}
}
echo “1”;
$page = $this->resultPageFactory->create(false, [‘isIsolated’ => true]);
echo “2”;
// YOUR LOGIC TO GET SELECTED LAYOUT
$youradminlayout = ‘sales_order_viewinvoice_jp’;
$page->getConfig()->setPageLayout($youradminlayout);
echo “3”;
return $page;
}
upto last line it is printing but page is not coming in front end.
please help me on this.
thanks in advance