I am looking a way how can I change homepage route on specific customer group user login. So basically problem that specific customer groups when logged in must see a different home page. How can this be done using events and observers. Also restrict that view only to that customer group. Is there a way to do that?
2 Answers
Create a plugin for this.
VendorName/ModuleName/etc/frontend/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Cms\Controller\Index\Index">
<plugin name="stackexchange_home" type="VendorName\ModuleName\Plugin\Cms\Controller\Index\Index" sortOrder="1"/>
</type>
</config>
VendorName/ModuleName/Plugin/Cms/Controller/Index/Index.php
namespace VendorName\ModuleName\Plugin\Cms\Controller\Index;
use Magento\Customer\Model\Session;
use Magento\Cms\Helper\Page;
class Index
{
/**
* @var Session
*/
protected $session;
/**
* @var Page
*/
protected $pageHelper;
/**
* @param Page $pageHelper
* @param Session $customerSession
*/
public function __construct(
Page $pageHelper,
Session $customerSession
) {
$this->pageHelper = $pageHelper;
$this->session = $customerSession;
}
/**
* Renders CMS Home page
*
* @param string|null $coreRoute
* @return \Magento\Framework\Controller\Result\Forward
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundExecute(
\Magento\Cms\Controller\Index\Index $subject,
\Closure $proceed,
$coreRoute = null
) {
if ($this->session->isLoggedIn()) {
$pageId = 4;
return $this->pageHelper->prepareResultPage($subject, $pageId);
}
return $proceed($coreRoute);
}
}
-
Thanks! Worked. Now i need to remove hard coded id and load page by identifier. Also add restriction to that page that only that customer group can access.– kilisCommented Jun 20, 2016 at 14:14
-
use \Magento\Framework\App\Http\Context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH) to decide if customer is logged in– MammouthCommented Feb 15, 2022 at 15:14
I am not a magento2 guy. I can suggest you way how it could be done in magento 1.x. You can change it accordingly for magento2.
- In module's config.xml, under
<frontend>
tag, define your event likecontroller_action_layout_load_before
and define an observer's function to perform action on this event. - Check customer group of logged in user and if it matches with the group, then change value of
web/default/cms_home_page
area programmatically. You may need to change above setting again for other customer groups also. - It may be better not to change system configuration, but to redirect using:
header('Location: '.Mage::helper('core/url')->getHomeUrl(<your-other-cms-page-url>));
from observer when desired condition meets.
Please let me know if you need any clarification.
Note: Terms used in this solution are from magento 1.x, not for 2.x. You need to make changes accordingly.