2

I have a cookie variable mobile-application = "yes". I need to set a custom theme depends on this variable in magento2. I've already created a custom theme. How I can set it programmatically in runtime. In magento1 works this example:

<models>
    <core>
        <rewrite>
            <design>Packagename_Modulename_Model_Design</design>
        </rewrite>
    </core>
</models>

Rewrite PHP code

  public function loadChange($storeId, $date = null)
    {
        $result = $this->getResource()
            ->loadChange($storeId, $date);

        if (!empty($result)) {
            if (!empty($result['design'])) {
                $tmp = explode('/', $result['design']);
                $result['package'] = $tmp[0];
                $result['theme'] = $tmp[1];
            }

            $this->setData($result);
        }
        // your custom code goes here
        // custom condition
        if(true) {
            $result['package'] = 'default';
            $result['theme'] = 'modern';
            $this->setData($result);
        }

        return $this;
    }

Has anybody experience with this point for magetno2?

0

1 Answer 1

2

You can try the below code to update the theme on runtime in Magento 2.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get(\Magento\Framework\View\DesignInterface::class)->setDesignTheme('Magento/luma', 'frontend'); //where Magento/luma is the theme name.

However, you can use the dependency injection in your custom module instead of the $objectManager.

EDIT:

app/code/Vendor/Module/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="layout_load_before_custom" instance="Verndor\ModuleName\Observer\ChangeTheme" />
    </event>
</config>

Hope it will help!!!

2
  • Thanks Which event i have to use or create plugin?
    – omelandr
    Oct 9, 2019 at 7:11
  • You can do it using an observer. layout_load_before this event means change layout before the pages load.
    – Sumit
    Oct 9, 2019 at 7:13

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.