6

I want to change a variable during runtime in Magento 2. Is this possible? If I look at how scope configuration works it only exists of getters, but I cannot find a way to manipulate this during runtime.

Please note that I do not want to save the value.

My use case: for some specific pages I want to hide the suffix. I want to do this by changing the configuration value design/head/title_suffix during runtime so it's reflected everywhere where this value is used.

1 Answer 1

0

The best way of doing this would be adding an after plugin for getting the Page title, you would not want to hook into the function for getting configs otherwise it would run every time a config is retrieved.

I do not know the exact logic you want to implement for when to change the suffix so the code below always changes the suffix, but the logic could be changed within shouldModify(). In a module:

app/code/VendorName/ModuleName/etc/frontend/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\View\Page\Title">
        <plugin name="vendorname_modulename_framework_view_page_title"
                type="VendorName\ModuleName\Plugin\Title" />
    </type>
</config>

app/code/VendorName/ModuleName/Plugin/Title.php

<?php
namespace VendorName\ModuleName\Plugin;

class Title
{
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @param \Magento\Framework\View\Page\Title $subject
     * @param string $result
     * @return string $result
     */
    public function afterGet(\Magento\Framework\View\Page\Title $subject, $result) // @codingStandardsIgnoreLine
    {
        if ($this->shouldModify()) {
            return rtrim($result, $this->scopeConfig->getValue(
                'design/head/title_suffix',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            )) . ' New suffix';
        }
        return $result;
    }

    /**
     * @return boolean
     */
    public function shouldModify()
    {
        return true;
    }
}

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.