How to Produce a Data Grid in frontend page by using knockout JS

Magento 2 exploits Knockout JS files in frontend. It executes Model View View-Model design outline which is very handy to create a dynamic UI.

In this article, the following steps guide you how to produce a data grid in frontend of Magento 2 by using Knockout JS:

  1. construct grid view-model
  2. Execute _prepareItems() function in grid view-model
  3. Execute _prepareColumns() function in grid view-model
  4. Form priceRender view-model
  5. Form template file
  6. Form Action Controller
  7. Form Block class
  8. Declare layout file
  9. Form template .phtml

Construct grid view-model

/app/code/[NameSpace]/[ModuleName]/view/frontend/web/js/view/grid.js
define (

                [

                'jquery',

                'ko',

                'uiComponent',

                                '[NameSpace]_[ModuleName]/js/view/grid/price'

                ],

                function ($, ko, component, priceRender) {

                "use strict";

                return component.extend({

                items: ko.observableArray([]),

                columns: ko.observableArray([]),

                defaults: {

                                template: '[NameSpace]_[ModuleName]/grid',

                },

                initialize: function () {

                                this._super();

                                this._render();

                },

                _render: function() {

                                this._prepareColumns();

                                this._prepareItems();                     

                },

                _prepareItems: function () {

                },

                _prepareColumns: function () {



                },

                addItem: function (item) {

                                item.columns = this.columns;

                                this.items.push(item);

                },

                addItems: function (items) {

                                for (var i in items) {

                                this.addItem(items[i]);

                                }

                },

                addColumn: function (column) {

                                this.columns.push(column);

                }

                });

                }

);

This view-model will put the data of the grid into its template file: [NameSpace]_[ModuleName]/grid which is stored at

/app/code/[NameSpace]/[ModuleName]/view/frontend/web/template/grid.html

 Execute _prepareItems() function in grid view-model

In this function you list all of items which you want to illustrate in the grid. If you modify the list of items in this function, the data of grid on frontend page will be modified automatically.

_prepareItems: function () {

var items = [

 {name: "Well-Travelled Kitten", sales: 352, price: 75.95},

 {name: "Speedy Coyote", sales: 89, price: 190.00},

 {name: "Furious Lizard", sales: 152, price: 25.00},

{name: "Indifferent Monkey", sales: 1, price: 99.95},

{name: "Brooding Dragon", sales: 0, price: 6350},

];

this.addItems(items);

}

Execute _prepareColumns() function in grid view-model

In this function you declare all of columns which is shown in the grid.

_prepareColumns: function () {

                this.addColumn({headerText: "Item Name", rowText: "name", renderer: ''});

                this.addColumn({headerText: "Sales Count", rowText: "sales", renderer: ''});

                this.addColumn({headerText: "Price", rowText: "price", renderer: priceRender()});

}
  • HeaderText: the title of column
  • rowText: elements of item (name,sales &price)
  • renderer: In this model, use the renderer if you want to modify the display format of the column

 Form priceRender view-model

This view-model will assist you explain the price quality of items

/app/code/[NameSpace]/[ModuleName]/view/frontend/web/js/view/grid/price.js
define

 [

 'jquery',

 'ko',

 'uiComponent',

],

 function ($, ko, component) {

 "use strict";

   return component.extend({

 render: function (item) {

  return "$" + item.price.toFixed(2);

 }

 });

  }

);

 Form template file

The template is the analysis in Knockout JS, which is a HTML file

/app/code/[NameSpace]/[ModuleName]/view/frontend/web/template/grid.html
<table class="data table base list">

 <thead>

<tr data-bind="foreach: columns">

<th data-bind="text: headerText"></th>

</tr>

</thead>

<tbody data-bind="foreach: items">

 <tr data-bind="foreach: columns">

<td><span data-bind="text:  renderer ? renderer.render($parent) : $parent[rowText] "></span></td>

  </tr>

</tbody>

</table>

Form Action Controller

/app/code/[NameSpace]/[ModuleName]/Controller/Index/View.php
<?php

namespace [NameSpace]\[ModuleName]\Controller\Index;

class View extends \Magento\Framework\App\Action\Action

{

/**

* @var \Magento\Framework\View\Result\PageFactory

*/

protected $_resultPageFactory;

/**

* Index constructor.

* @param \Magento\Framework\App\Action\Context $context

* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory

*/

public function __construct(

\Magento\Framework\App\Action\Context $context,

  \Magento\Framework\View\Result\PageFactory $resultPageFactory

){

 $this->_resultPageFactory = $resultPageFactory;

 parent::__construct($context);

}

/**

* @return \Magento\Framework\View\Result\Page

*/

public function execute()

{

 return $this->_resultPageFactory->create();

}

}

 Form Block class

/app/code/[NameSpace]/[ModuleName]/Block/ViewAbstract.php
<?php

namespace [NameSpace]\[ModuleName]\Block;

class ViewAbstract extends \Magento\Framework\View\Element\Template

{

/**

* @var \Magento\Checkout\Model\CompositeConfigProvider

*/

protected $configProvider;

/**

* @var array

*/

protected $_layoutProcessors;

/**

* Lists constructor.

* @param \Magento\Framework\View\Element\Template\Context $context

* @param array $layoutProcessors

* @param array $data

*/

public function __construct(

   \Magento\Framework\View\Element\Template\Context $context,

 \Magento\Checkout\Model\CompositeConfigProvider $configProvider,

  array $layoutProcessors = [],

array $data = []

) {

  parent::__construct($context, $data);

$this->configProvider = $configProvider;

 $this->_layoutProcessors = $layoutProcessors;

}

/**

* @return string

*/

public function getJsLayout()

{

 foreach ($this->_layoutProcessors as $processor) {

 $this->jsLayout = $processor->process($this->jsLayout);

 }

 return parent::getJsLayout();

}

}

 Declare layout file

/app/code/[NameSpace]/[ModuleName]/Block/view/frontend/layout/[modulename]_index_view.xml
<?xml version="1.0"?>

<page layout='1column' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" >

<body>

 <referenceContainer name="content">

 <block class="[NameSpace]\[ModuleName]\Block\ViewAbstract" before="-" cacheable="false" template="[NameSpace]_[ModuleName]::grid.phtml">  <arguments>

  <argument name="jsLayout" xsi:type="array">

   <item name="components" xsi:type="array">

<item name="sample-grid" xsi:type="array">

  <item name="component" xsi:type="string">[NameSpace]_[ModuleName]/js/view/grid</item>

 </item>

 </item>

</argument>

 </arguments>

 </block>

 </referenceContainer>

</body>

</page>

 Form template .phtml

/app/code/[NameSpace]/[ModuleName]/Block/view/frontend/template/grid.phtml
 <div id="block-sample-grid" data-bind="scope:'sample-grid'" class="block">

<!-- ko template: getTemplate() --><!-- /ko -->

<script type="text/x-magento-init">

 {

"#block-sample-grid": {

   "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>

     }

}

</script>

</div>

 I hope the following information shows you How to Produce a Data Grid in frontend page by using knockout Js. You can also try our Magento 2 Demo For more queries feel free to find more Magento 2 Tutorials by our Experts.

Last Update: July 17, 2018  

February 17, 2018   147   Nandini R    Java Script    
Total 1 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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

Facebook
Google+
http://www.webnexs.com/blog/kb/produce-data-grid-frontend-page-using-knockout-js
Twitter
LinkedIn