Magento 2.1 : How to overwrite default page layout in Block
-
20-12-2020 - |
Question
I have a custom module having layout XML file for the front end, in which the default page layout configuration is set to one column, I wish to give the user the ability to change the configuration as specified in the system configurations(like 2columns-left, 2columns-right, 3coulmns). I can get the values from configuration via helper in to the block file prepareLayout ,I would like to know if we can set the layout just like the pagetitle , metakeyowords we use to set. How can we set and overwrite default values in prepare layout in block file? Thanks.
The XML default value is :
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
Solution
You can set page layout from the controller action. Suppose this is your action file avilable at this location.
app/code/Vendor/Extension/Controller/Youraction/Action.php
Put this code like this.
<?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 FROM ADMIN
$youradminlayout = 'XYZ';
$page->getConfig()->setPageLayout($youradminlayout);
return $page;
}
}