Use “ViewModel” for block template

“ViewModel” is a feature allow write additional function without modify current block like override. Example: Sometime, you would like to add a template to a block but you must add function to block and call via template. So, you can use ViewModel in that case.

I would like to adjust template of sales_order_view.xml.
– Set template with new file: Lights_OrderProcessing::order/view/items.phtml
– Declare argument with name “viewModel” and your class process: Lights\OrderProcessing\ViewModel\Order\View\Items.
Example create a function get Image of product item:

namespace Lights\OrderProcessing\ViewModel\Order\View;

use Magento\Framework\DataObject;
use Magento\Framework\View\Element\Block\ArgumentInterface;
class Items extends DataObject implements ArgumentInterface
{

    /**
     * @var \Magento\Catalog\Helper\ImageFactory
     */
    protected $imageFactory;
    public function __construct(
        \Magento\Catalog\Helper\ImageFactory $imageFactory,
        array $data = []
    )
    {
        $this->imageFactory = $imageFactory;
        parent::__construct($data);
    }

    /**
     * @param $product
     * @return string
     */
    public function getImage($product){
        return $this->imageFactory->create()->init($product, 'product_thumbnail_image')->getUrl();
    }
}
Finally, you can call that function on your template file order/view/items.phtml :
$block->getData('viewModel')->getImage($product); 

Leave a Reply