0.5.14 • Published 5 years ago

yii-react-gridview v0.5.14

Weekly downloads
14
License
ISC
Repository
github
Last release
5 years ago

Yii2 GridView widget for react

This component is created to simplify moving from php rendering of built-in Yii2 Gridview widget to React-based application using some of its familiar settings.

Simple example

Installing

npm install --save yii-react-gridview

Setting props

Instead of using pager or dataProvider objects as it used in Yii2 Gridview widget, some of its properties (or equivalents) should be set as props directly in GridView component. It makes more suitable way for React of re-rendering the component in case if some prop will be changed. See Available props to find out how to set up your GridView.

Example

of component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import GridView from 'yii-react-gridview';
import Axios from 'axios';

class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      data: null,
    };
    Axios.get('/your/get-data').then(response => {
      let dataProvider = response.data;
      this.pageSize = dataProvider.pageSize;
      this.headerCells = dataProvider.headerCells;
      this.maxButtonCount = dataProvider.maxButtonCount;
      this.setState({
        data: dataProvider.data,
        currentPage: dataProvider.currentPage,
        totalCount: dataProvider.totalCount,
      });
    });

    this.columns = {
      username: null,
      email: null,
      city: null,
    }
  }
  
  onPageButtonClicked = (currentPage) =>  {
    Axios.get('/your/get-data').then(response => {
      this.setState({
        currentPage: currentPage,
        //...
      });
    })
  };
  
  onSortChanged = (sort) =>  {
    this.setState({sort: sort});
    Axios.get('/your/get-data', {
      params: {
        // Pass 'sort' as is (js-object) or prepare it to be compatible with Query::orderBy()
        orderBy: sort,
        //...
      }
    }).then(response => {
      this.setState({
        //...
      });
    });
  };
  
  render() {
    return (
      <div className="App">
        <GridView
          data={ this.state.data }
          headerCells={ this.headerCells }
          columns={ this.columns }
          currentPage={ this.state.currentPage }
          totalCount={this.state.totalCount}
          maxButtonCount={ this.maxButtonCount }
          pageSize={this.pageSize }
          onPageButtonClick={ this.onPageButtonClicked }
          onSortChange={ this.onSortChanged }
        />
      </div>
    );
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));

of action:

class YourController extends Controller {
    public function actionGetData($currentPage = 0, $pageSize = 20, $filters = [], $orderBy = '') {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        
        // Prepare orderBy object here or do it in 'onSortChange' callback
        // Anyway make it compatible with '->orderBy($orderBy)'
        $preparedOrderBy = [];
        if ($orderBy) {
            foreach (Json::decode($orderBy) as $col => $sort) {
                $preparedOrderBy[] = "{$col} {$sort}";
            }
            if (!empty($preparedOrderBy)) {
                $preparedOrderBy = implode(',', $preparedOrderBy);
            }
        }
        // Probably $filters should be also prepared
        // ...
        
        return [
            'data' => ArrayHelper::toArray(User::find()
                ->andFilterWhere($filters)
                ->offset($currentPage * $pageSize)
                ->orderBy($preparedOrderBy)
                ->limit($pageSize)
                ->all(), [
                User::class => [
                    'username',
                    'email',
                    'city',
                ]
            ]),
            'headerCells' => (new User)->attributeLabels(),
            'currentPage' => (int) $currentPage,
            'totalCount' => (int) User::find()->andFilterWhere($filters)->count(),
            'pageSize' => $pageSize,
        ];
    }        
}

Available props

PropertyTypeDefault valueDescription
dataArrayundefinedArray of models to show in list
notSetTextstring'(not set)'Text will be shown when a cell in a row is not set
headerCellsObject{}Key-value pairs of names of data models properties. It should contain the same keys as keys of an Object in data.Values of headerCells could be either strings or object of following structure: { value: 'Column Title', column: 'attrbute_name', enableSorting: true, sort: 'ASC' }.If enableSorting is true then column required. sort (if specified) must be either 'ASC' or 'DESC'
footerCellsArray[]Array of strings or components corresponding cells of tfoot-row. Make sure the array length match the table
captionStringundefinedA string for caption if necessary
emptyCaptionString'Nothing found'The text will be shown when no data rows are loaded
captionOptionsObject{}HTML attributes of caption
containerOptionsObject{}HTML attributes of GridView instance conteiner (div that wraping the table and the pager)
tableOptionsObject{}HTML attributes of table
showHeaderBooleantrueWhether show \<thead> or not
showFooterBooleanfalseWhether show \<tfoot> or not
hidePagerBooleanfalseWhether show pager buttons or not
placeFooterAfterBodyBooleantrueWhether place \<tfoot> after body or not
headerRowOptionsObject{}HTML attributes of thead > row
footerRowOptionsObject{}HTML attributes of tfoot > row
rowOptionsObject{}HTML attributes of tbody > row
columnsObjectundefinedKeys of the object are whether properties of a model in data (then the title will be provided by headerCells) or custom strings that will be a column titles.Values of the object are either null (to provide a model value as is) or function (cell, rowId, hoveredRowId) (to decorate a model value with its result).Also string 'serial' can be set to provide models numeration.If 'checkbox' is set as a key and its value (just value at least) then column of checkboxes will be rendered in order to select row(s) ids (a value that specified in rowIdColumn)
filtersObjectnullContain filters for specified columns. Filters can be:a) string 'text' renders simple input of type="text";b) Object { type: ..., options: {...} } where type can be either 'text' (input of type="text"), 'checkbox' or 'select'. Options typically are HTML attributes of the inputs. If type is 'select' then options should contain data - object of options (where key is value attribute of an \<option> and value is its text);c) function (name, onChange) to render custom input with name={ name } and onChange={ onChange } (must return a React.Component/html)
onSortChangefunction(sort)undefinedCallback to sort the data with sort - key-value object (js { column:'ASC' /* or 'DESC' */ }) to sort the data. The way of is up to you
onFilterChangefunction(filters)undefinedCallback to filter the data with filters - key-value object to filter the data. Required when filters are specified. The way of filtering depends on you
pagerOptionsobjectundefinedHTML attributes of pager container
currentPageintegerundefinedNumber of current page (begins from 0). Should be provided by data provider
totalCountintegerundefinedTotal count of models given in data. Should be provided by data provider
maxButtonCountinteger10Max count of pager links
pageSizeinteger20Max count of models on a page
pagerTagstring'ul'Tag name of pager container
pageTagstring'li'Tag name of pager link
activePageCssClassstring'active'Class name of active page link
disabledPageCssClassstring'disabled'Class name of disabled pager link
nextPageCssClassstring'next'Class name of 'next' page link
prevPageCssClassstring'prev'Class name of 'previous' page link
firstPageCssClassstring'first'Class name of 'first' page link
lastPageCssClassstring'last'Class name of 'last' page link
nextPageLabelstring'»'Label of 'next' page link
prevPageLabelstring'«'Label of 'previous' page link
firstPageLabelstringnullLabel of 'first' page link
lastPageLabelstringnullLabel of 'last' page link
onPageButtonClickfunction(pageNumber)nullCallback of click on pager link with given page number. Originally it should replace pageNumber with its page number and reload the data, but it's up to you whatever it does.
onSelectionChangefunction(selectedRowIds)nullCallback which will be applied when a row is (or all rows are) selected. Array of selected values specified in rowIdColumn will be passed in selectedRowIds
rowIdColumnstring'id'Column name that could be used as primary key for selection. If onSelectionChange is set, then array of values of selected rowIdColumn will be passed as an argument
0.5.14

5 years ago

0.5.13

5 years ago

0.5.12

5 years ago

0.5.11

5 years ago

0.5.10

5 years ago

0.5.9

5 years ago

0.5.8

5 years ago

0.5.7

5 years ago

0.5.6

6 years ago

0.5.5

6 years ago

0.5.4

6 years ago

0.5.3

6 years ago

0.5.2

6 years ago

0.5.1

6 years ago

0.5.0

6 years ago

0.4.2

6 years ago

0.4.1

6 years ago

0.4.0

6 years ago

0.3.1

6 years ago

0.3.0

6 years ago

0.1.0

6 years ago