Magento 2 - Set the page layout dynamically based on admin configuration
For magento 2 you have to do it using Helper and controller.
In Controller you have to write in Index.php
<?php
namespace MageArray\Blog\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
protected $viewHelper;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\MageArray\Blog\Helper\Index\View $viewHelper,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->viewHelper = $viewHelper;
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create(false, ['isIsolated' => true]);
$this->viewHelper->prepareAndRender($page, $this);
return $page;
}
}
In namespace MageArray\Blog\Controller\Index;
Here MageArray is my NameSpace, Blog is my Module Name, Index is My controller Ans Class Name "Index" Is My action.
Now Create Helper File as i have View.php Helper and put code as below.
<?php
namespace MageArray\Blog\Helper\Index;
use Magento\Framework\View\Result\Page as ResultPage;
class View extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\App\Helper\Context $context,
) {
$this->_scopeConfig = $scopeConfig;
parent::__construct($context);
}
public function getStoreConfig($storePath){
$StoreConfig = $this->_scopeConfig->getValue($storePath, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
return $StoreConfig;
}
public function initProductLayout(ResultPage $resultPage,$layout_id)
{
$post_list_layout = $this->getStoreConfig($layout_id);
$pageConfig = $resultPage->getConfig();
$pageConfig->setPageLayout($post_list_layout);
$update = $resultPage->getLayout()->getUpdate();
$controllerClass = $this->_request->getFullActionName();
return $this;
}
public function prepareAndRender(ResultPage $resultPage, $controller)
{
$this->initProductLayout($resultPage,'magearray/general/post_list_layout');
return $this;
}
}
make changes in namespace, module, helper and configPath names as per your requirements.