2
$extensionStatus=$this->helper('Esparksinc\Extension\Helper\Data')->getConfig('Extension/general/enableDisable');

how to use viewmodel instead helper method to acces the system.xml values in phtml in maganto 2

3

Take a look at

https://www.yireo.com/blog/2017-08-12-viewmodels-in-magento-2

When it is good to use viewModel ? What is difference between viewModel and Block?

Create a viewmodel class Test.php at app/code/Vendor/ModuleName/ViewModel and inject Esparksinc\Extension\Helper\Data at it __construct function.

<?php 
namespace Vendor\ModuleName\ViewModel;

class Test implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    private $helperData;
    public function __construct(
        \Esparksinc\Extension\Helper\Data $helperData
    )
    {
        $this->helperData= $helperData;
    }
    public function getSettingValue()
    {
        return $this->helperData>getConfig('Extension/general/enableDisable');
    }

}

And call this ViewModel class via layout handler

<referenceBlock name="{YourPhtmlFileLayoutName}">
    <arguments>
        <argument name="view_model" xsi:type="object">Vendor\ModuleName\ViewModel\Test</argument>
    </arguments>
</referenceBlock>

and Call the method of Vendor\ModuleName\ViewModel\Test at your phtml.

<?php /** @var \Vendor\ModuleName\ViewModel\Test $viewModel */ ?>
<?php $viewModel = $block->getData('viewModel') ?>
<?php echo (int) $viewModel->getSettingValue()) ?>
  • how $block->getData is linked because there is no function in block with name of getData(); @Amit – usman Aug 25 at 18:24
  • 1
    @usman: i tried $block->getViewModel() in template file and it works :) – Guru Nov 19 at 3:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.