How To get the collection from the ViewModel

Package name : Tridhya
Module : Blog
For fetching the data or getting the collection of the table we can use the ViewModel. Below is a short example that how we can fetch the collection data from the viewmodel

  • Declare view model in the layout file
    app\code\Tridhya\Blog\view\frontend\layout\blog_index_index.xml

Code:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="blog.list" template="Tridhya_Blog::blog.phtml">
<arguments>
<argument name="view_model" xsi:type="object">Tridhya\Blog\ViewModel\Data</argument>
</arguments>
</block>
</referenceContainer>
</body>
</page>

  • Create pltml file in path: app\code\Tridhya\Blog\view\frontend\templates\blog.phtml from the file we can load the view model with the name which we have passed in the arguments “view_model”

    Code:

<?php
$viewModel= $block->getData('view_model');
$blogs = $viewModel->getCollection();

?>

  • Create a file in path : app\code\Tridhya\Blog\ViewModel\Data.php

    Code:

    <?php
    namespace Tridhya\Blog\ViewModel;

class Data implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
protected $blogFactory;

public function __construct(
\Tridhya\Blog\Model\BlogFactory $blogFactory
) {
$this->blogFactory = $blogFactory;
}

public function getCollection() {
$blogFactory = $this->blogFactory->create();
$collection = $blogFactory->getCollection();
return $collection;
}
}
?>

I hope this has helped you understand how we can fetch the collection data from the viewmodel. If you have any questions we are here to help. Get in touch with us!

This blog is written by , Jainil Khamar – Sr. Software Engineer at Tridhya Innovation

 

 

CategoriesTechnologyTags

Leave a Reply

Your email address will not be published. Required fields are marked *