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


Take a look at


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.

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}">
        <argument name="view_model" xsi:type="object">Vendor\ModuleName\ViewModel\Test</argument>

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()) ?>
| improve this answer | |
  • how $block->getData is linked because there is no function in block with name of getData(); @Amit – usman Aug 25 '19 at 18:24
  • 1
    @usman: i tried $block->getViewModel() in template file and it works :) – Guru Nov 19 '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.