Overview

Packages

  • Net
  • None
  • PHP
  • system
    • base
    • caching
      • dependencies
    • cli
      • commands
        • shell
    • collections
    • console
    • db
      • ar
      • schema
        • mssql
        • mysql
        • oci
        • pgsql
        • sqlite
    • gii
    • i18n
      • gettext
    • logging
    • test
    • utils
    • validators
    • web
      • actions
      • auth
      • filters
      • form
      • helpers
      • renderers
      • services
      • widgets
        • captcha
        • pagers
  • Text
    • Diff
    • Highlighter
  • zii
    • behaviors
    • widgets
      • grid
      • jui

Classes

  • CButtonColumn
  • CCheckBoxColumn
  • CDataColumn
  • CGridColumn
  • CGridView
  • CLinkColumn
  • Overview
  • Package
  • Class
  • Tree
  • Download

Class CGridView

CGridView displays a list of data items in terms of a table.

Each row of the table represents the data of a single data item, and a column usually represents an attribute of the item (some columns may correspond to complex expression of attributes or static text).

CGridView supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode or normal page request. A benefit of using CGridView is that when the user browser disables JavaScript, the sorting and pagination automatically degenerate to normal page requests and are still functioning as expected.

CGridView should be used together with a IDataProvider data provider, preferrably a CActiveDataProvider.

The minimal code needed to use CGridView is as follows:

$dataProvider=new CActiveDataProvider('Post');

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
));

The above code first creates a data provider for the Post ActiveRecord class. It then uses CGridView to display every attribute in every Post instance. The displayed table is equiped with sorting and pagination functionality.

In order to selectively display attributes with different formats, we may configure the CGridView::$columns property. For example, we may specify only the title and create_time attributes to be displayed, and the create_time should be properly formatted to show as a time. We may also display the attributes of the related objects using the dot-syntax as shown below:

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'title',          // display the 'title' attribute
        'category.name',  // display the 'name' attribute of the 'category' relation
        'content:html',   // display the 'content' attribute as purified HTML
        array(            // display 'create_time' using an expression
            'name'=>'create_time',
            'value'=>'date("M j, Y", $data->create_time)',
        ),
        array(            // display 'author.username' using an expression
            'name'=>'authorName',
            'value'=>'$data->author->username',
        ),
        array(            // display a column with "view", "update" and "delete" buttons
            'class'=>'CButtonColumn',
        ),
    ),
));

Please refer to CGridView::$columns for more details about how to configure this property.

CWidget
Extended by CBaseListView
Extended by CGridView
Package: zii\widgets\grid
Copyright: 2008-2013 Yii Software LLC
License: http://www.yiiframework.com/license/
Author: Qiang Xue <qiang.xue@gmail.com>
Since: 1.1
Located at zii/widgets/grid/CGridView.php
Methods summary
public
# init( )

Initializes the grid view. This method will initialize required property values and instantiate CGridView::$columns objects.

Initializes the grid view. This method will initialize required property values and instantiate CGridView::$columns objects.

Overrides

CBaseListView::init()
protected
# initColumns( )

Creates column objects and initializes them.

Creates column objects and initializes them.

protected CDataColumn
# createDataColumn( string $text )

Creates a CDataColumn based on a shortcut column specification string.

Creates a CDataColumn based on a shortcut column specification string.

Parameters

$text
the column specification string

Returns

CDataColumn
the column instance
public
# registerClientScript( )

Registers necessary client scripts.

Registers necessary client scripts.

Overrides

CBaseListView::registerClientScript()
public
# renderItems( )

Renders the data items for the grid view.

Renders the data items for the grid view.

public
# renderTableHeader( )

Renders the table header.

Renders the table header.

public
# renderFilter( )

Renders the filter.

Renders the filter.

Since

1.1.1
public
# renderTableFooter( )

Renders the table footer.

Renders the table footer.

public
# renderTableBody( )

Renders the table body.

Renders the table body.

public
# renderTableRow( integer $row )

Renders a table body row.

Renders a table body row.

Parameters

$row
the row number (zero-based).
public boolean
# getHasFooter( )

Returns

boolean
whether the table should render a footer. This is true if any of the CGridView::$columns has a true CGridColumn::hasFooter value.
public CFormatter
# getFormatter( )

Returns

CFormatter
the formatter instance. Defaults to the 'format' application component.
public
# setFormatter( CFormatter $value )

Parameters

$value
the formatter instance
Methods inherited from CBaseListView
renderContent(), renderEmptyText(), renderKeys(), renderPager(), renderSection(), renderSummary(), run()
Constants summary
string FILTER_POS_HEADER
#'header'
string FILTER_POS_FOOTER
#'footer'
string FILTER_POS_BODY
#'body'
Properties summary
public array $columns

grid column configuration. Each array element represents the configuration for one particular grid column which can be either a string or an array.

When a column is specified as a string, it should be in the format of "name:type:header", where "type" and "header" are optional. A CDataColumn instance will be created in this case, whose CDataColumn::$name, CDataColumn::$type and CGridColumn::$header properties will be initialized accordingly.

When a column is specified as an array, it will be used to create a grid column instance, where the 'class' element specifies the column class name (defaults to CDataColumn if absent). Currently, these official column classes are provided: CDataColumn, CLinkColumn, CButtonColumn and CCheckBoxColumn.

grid column configuration. Each array element represents the configuration for one particular grid column which can be either a string or an array.

When a column is specified as a string, it should be in the format of "name:type:header", where "type" and "header" are optional. A CDataColumn instance will be created in this case, whose CDataColumn::$name, CDataColumn::$type and CGridColumn::$header properties will be initialized accordingly.

When a column is specified as an array, it will be used to create a grid column instance, where the 'class' element specifies the column class name (defaults to CDataColumn if absent). Currently, these official column classes are provided: CDataColumn, CLinkColumn, CButtonColumn and CCheckBoxColumn.

#array()
public array $rowCssClass

the CSS class names for the table body rows. If multiple CSS class names are given, they will be assigned to the rows sequentially and repeatedly. This property is ignored if rowCssClassExpression is set. Defaults to array('odd', 'even').

the CSS class names for the table body rows. If multiple CSS class names are given, they will be assigned to the rows sequentially and repeatedly. This property is ignored if rowCssClassExpression is set. Defaults to array('odd', 'even').

See

rowCssClassExpression
#array('odd','even')
public string $rowHtmlOptionsExpression
a PHP expression that is evaluated for every table body row and whose result is used as additional HTML attributes for the row. The expression should return an array whose key value pairs correspond to html attribute and value. In this expression, you can use the following variables:
  • $row the row number (zero-based)
  • $data the data model for the row
  • $this the grid view object
The PHP expression will be evaluated using evaluateExpression.

A PHP expression can be any PHP code that has a value. To learn more about what an expression is, please refer to the php manual.

a PHP expression that is evaluated for every table body row and whose result is used as additional HTML attributes for the row. The expression should return an array whose key value pairs correspond to html attribute and value. In this expression, you can use the following variables:
  • $row the row number (zero-based)
  • $data the data model for the row
  • $this the grid view object
The PHP expression will be evaluated using evaluateExpression.

A PHP expression can be any PHP code that has a value. To learn more about what an expression is, please refer to the php manual.

Since

1.1.13
#
public boolean $showTableOnEmpty

whether to display the table even when there is no data. Defaults to true. The CBaseListView::$emptyText will be displayed to indicate there is no data.

whether to display the table even when there is no data. Defaults to true. The CBaseListView::$emptyText will be displayed to indicate there is no data.

#true
public mixed $ajaxUpdate

the ID of the container whose content may be updated with an AJAX response. Defaults to null, meaning the container for this grid view instance. If it is set false, it means sorting and pagination will be performed in normal page requests instead of AJAX requests. If the sorting and pagination should trigger the update of multiple containers' content in AJAX fashion, these container IDs may be listed here (separated with comma).

the ID of the container whose content may be updated with an AJAX response. Defaults to null, meaning the container for this grid view instance. If it is set false, it means sorting and pagination will be performed in normal page requests instead of AJAX requests. If the sorting and pagination should trigger the update of multiple containers' content in AJAX fashion, these container IDs may be listed here (separated with comma).

#
public string $updateSelector

the jQuery selector of the HTML elements that may trigger AJAX updates when they are clicked. These tokens are recognized: {page} and {sort}. They will be replaced with the pagination and sorting links selectors. Defaults to '{page}, {sort}', that means that the pagination links and the sorting links will trigger AJAX updates. Tokens are available from 1.1.11

Note: if this value is empty an exception will be thrown.

Example (adding a custom selector to the default ones):

 ...
 'updateSelector'=>'{page}, {sort}, #mybutton',
 ...

the jQuery selector of the HTML elements that may trigger AJAX updates when they are clicked. These tokens are recognized: {page} and {sort}. They will be replaced with the pagination and sorting links selectors. Defaults to '{page}, {sort}', that means that the pagination links and the sorting links will trigger AJAX updates. Tokens are available from 1.1.11

Note: if this value is empty an exception will be thrown.

Example (adding a custom selector to the default ones):

 ...
 'updateSelector'=>'{page}, {sort}, #mybutton',
 ...

Since

1.1.7
#'{page}, {sort}'
public string $ajaxUpdateError

a javascript function that will be invoked if an AJAX update error occurs.

The function signature is function(xhr, textStatus, errorThrown, errorMessage)
  • xhr is the XMLHttpRequest object.
  • textStatus is a string describing the type of error that occurred. Possible values (besides null) are "timeout", "error", "notmodified" and "parsererror"
  • errorThrown is an optional exception object, if one occurred.
  • errorMessage is the CGridView default error message derived from xhr and errorThrown. Usefull if you just want to display this error differently. CGridView by default displays this error with an javascript.alert()
Note: This handler is not called for JSONP requests, because they do not use an XMLHttpRequest.

Example (add in a call to CGridView):

 ...
 'ajaxUpdateError'=>'function(xhr,ts,et,err){ $("#myerrordiv").text(err); }',
 ...

a javascript function that will be invoked if an AJAX update error occurs.

The function signature is function(xhr, textStatus, errorThrown, errorMessage)
  • xhr is the XMLHttpRequest object.
  • textStatus is a string describing the type of error that occurred. Possible values (besides null) are "timeout", "error", "notmodified" and "parsererror"
  • errorThrown is an optional exception object, if one occurred.
  • errorMessage is the CGridView default error message derived from xhr and errorThrown. Usefull if you just want to display this error differently. CGridView by default displays this error with an javascript.alert()
Note: This handler is not called for JSONP requests, because they do not use an XMLHttpRequest.

Example (add in a call to CGridView):

 ...
 'ajaxUpdateError'=>'function(xhr,ts,et,err){ $("#myerrordiv").text(err); }',
 ...
#
public string $ajaxVar

the name of the GET variable that indicates the request is an AJAX request triggered by this widget. Defaults to 'ajax'. This is effective only when CGridView::$ajaxUpdate is not false.

the name of the GET variable that indicates the request is an AJAX request triggered by this widget. Defaults to 'ajax'. This is effective only when CGridView::$ajaxUpdate is not false.

#'ajax'
public mixed $ajaxUrl

the URL for the AJAX requests should be sent to. CHtml::normalizeUrl() will be called on this property. If not set, the current page URL will be used for AJAX requests.

the URL for the AJAX requests should be sent to. CHtml::normalizeUrl() will be called on this property. If not set, the current page URL will be used for AJAX requests.

Since

1.1.8
#
public string $ajaxType

the type ('GET' or 'POST') of the AJAX requests. If not set, 'GET' will be used. You can set this to 'POST' if you are filtering by many fields at once and have a problem with GET query string length. Note that in POST mode direct links and CGridView::$enableHistory feature may not work correctly!

the type ('GET' or 'POST') of the AJAX requests. If not set, 'GET' will be used. You can set this to 'POST' if you are filtering by many fields at once and have a problem with GET query string length. Note that in POST mode direct links and CGridView::$enableHistory feature may not work correctly!

Since

1.1.14
#
public string $beforeAjaxUpdate

a javascript function that will be invoked before an AJAX update occurs. The function signature is function(id,options) where 'id' refers to the ID of the grid view, 'options' the AJAX request options (see jQuery.ajax api manual).

a javascript function that will be invoked before an AJAX update occurs. The function signature is function(id,options) where 'id' refers to the ID of the grid view, 'options' the AJAX request options (see jQuery.ajax api manual).

#
public string $afterAjaxUpdate

a javascript function that will be invoked after a successful AJAX response is received. The function signature is function(id, data) where 'id' refers to the ID of the grid view, 'data' the received ajax response data.

a javascript function that will be invoked after a successful AJAX response is received. The function signature is function(id, data) where 'id' refers to the ID of the grid view, 'data' the received ajax response data.

#
public string $selectionChanged

a javascript function that will be invoked after the row selection is changed. The function signature is function(id) where 'id' refers to the ID of the grid view. In this function, you may use $(gridID).yiiGridView('getSelection') to get the key values of the currently selected rows (gridID is the DOM selector of the grid).

a javascript function that will be invoked after the row selection is changed. The function signature is function(id) where 'id' refers to the ID of the grid view. In this function, you may use $(gridID).yiiGridView('getSelection') to get the key values of the currently selected rows (gridID is the DOM selector of the grid).

See

CGridView::$selectableRows
#
public integer $selectableRows

the number of table body rows that can be selected. If 0, it means rows cannot be selected. If 1, only one row can be selected. If 2 or any other number, it means multiple rows can be selected. A selected row will have a CSS class named 'selected'. You may also call the JavaScript function $(gridID).yiiGridView('getSelection') to retrieve the key values of the currently selected rows (gridID is the DOM selector of the grid).

the number of table body rows that can be selected. If 0, it means rows cannot be selected. If 1, only one row can be selected. If 2 or any other number, it means multiple rows can be selected. A selected row will have a CSS class named 'selected'. You may also call the JavaScript function $(gridID).yiiGridView('getSelection') to retrieve the key values of the currently selected rows (gridID is the DOM selector of the grid).

#1
public string $baseScriptUrl

the base script URL for all grid view resources (eg javascript, CSS file, images). Defaults to null, meaning using the integrated grid view resources (which are published as assets).

the base script URL for all grid view resources (eg javascript, CSS file, images). Defaults to null, meaning using the integrated grid view resources (which are published as assets).

#
public string $cssFile

the URL of the CSS file used by this grid view. Defaults to null, meaning using the integrated CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.

the URL of the CSS file used by this grid view. Defaults to null, meaning using the integrated CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.

#
public string $nullDisplay

the text to be displayed in a data cell when a data value is null. This property will NOT be HTML-encoded when rendering. Defaults to an HTML blank.

the text to be displayed in a data cell when a data value is null. This property will NOT be HTML-encoded when rendering. Defaults to an HTML blank.

#'&nbsp;'
public string $blankDisplay

the text to be displayed in an empty grid cell. This property will NOT be HTML-encoded when rendering. Defaults to an HTML blank. This differs from CGridView::$nullDisplay in that CGridView::$nullDisplay is only used by CDataColumn to render null data values.

the text to be displayed in an empty grid cell. This property will NOT be HTML-encoded when rendering. Defaults to an HTML blank. This differs from CGridView::$nullDisplay in that CGridView::$nullDisplay is only used by CDataColumn to render null data values.

Since

1.1.7
#'&nbsp;'
public string $loadingCssClass

the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. Defaults to 'grid-view-loading'.

the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. Defaults to 'grid-view-loading'.

Since

1.1.1
#'grid-view-loading'
public string $filterSelector

the jQuery selector of filter input fields. The token '{filter}' is recognized and it will be replaced with the grid filters selector. Defaults to '{filter}'.

Note: if this value is empty an exception will be thrown.

Example (adding a custom selector to the default one):

 ...
 'filterSelector'=>'{filter}, #myfilter',
 ...

the jQuery selector of filter input fields. The token '{filter}' is recognized and it will be replaced with the grid filters selector. Defaults to '{filter}'.

Note: if this value is empty an exception will be thrown.

Example (adding a custom selector to the default one):

 ...
 'filterSelector'=>'{filter}, #myfilter',
 ...

Since

1.1.13
#'{filter}'
public string $filterCssClass

the CSS class name for the table row element containing all filter input fields. Defaults to 'filters'.

the CSS class name for the table row element containing all filter input fields. Defaults to 'filters'.

Since

1.1.1

See

CGridView::$filter
#'filters'
public string $filterPosition
whether the filters should be displayed in the grid view. Valid values include:
  • header: the filters will be displayed on top of each column's header cell.
  • body: the filters will be displayed right below each column's header cell.
  • footer: the filters will be displayed below each column's footer cell.
whether the filters should be displayed in the grid view. Valid values include:
  • header: the filters will be displayed on top of each column's header cell.
  • body: the filters will be displayed right below each column's header cell.
  • footer: the filters will be displayed below each column's footer cell.

Since

1.1.1

See

CGridView::$filter
#'body'
public CModel $filter

the model instance that keeps the user-entered filter data. When this property is set, the grid view will enable column-based filtering. Each data column by default will display a text field at the top that users can fill in to filter the data. Note that in order to show an input field for filtering, a column must have its CDataColumn::$name property set or have CDataColumn::$filter as the HTML code for the input field. When this property is not set (null) the filtering is disabled.

the model instance that keeps the user-entered filter data. When this property is set, the grid view will enable column-based filtering. Each data column by default will display a text field at the top that users can fill in to filter the data. Note that in order to show an input field for filtering, a column must have its CDataColumn::$name property set or have CDataColumn::$filter as the HTML code for the input field. When this property is not set (null) the filtering is disabled.

Since

1.1.1
#
public boolean $hideHeader

whether to hide the header cells of the grid. When this is true, header cells will not be rendered, which means the grid cannot be sorted anymore since the sort links are located in the header. Defaults to false.

whether to hide the header cells of the grid. When this is true, header cells will not be rendered, which means the grid cannot be sorted anymore since the sort links are located in the header. Defaults to false.

Since

1.1.1
#false
public boolean $enableHistory
whether to leverage the DOM history object. Set this property to true to persist state of grid across page revisits. Note, there are two limitations for this feature:
  • this feature is only compatible with browsers that support HTML5.
  • expect unexpected functionality (e.g. multiple ajax calls) if there is more than one grid/list on a single page with enableHistory turned on.
whether to leverage the DOM history object. Set this property to true to persist state of grid across page revisits. Note, there are two limitations for this feature:
  • this feature is only compatible with browsers that support HTML5.
  • expect unexpected functionality (e.g. multiple ajax calls) if there is more than one grid/list on a single page with enableHistory turned on.

Since

1.1.11
#false
Properties inherited from CBaseListView
$dataProvider, $emptyText, $enablePagination, $enableSorting, $htmlOptions, $itemsCssClass, $pager, $pagerCssClass, $summaryCssClass, $summaryText, $tagName, $template
Magic properties summary
public boolean $hasFooter

Whether the table should render a footer. This is true if any of the CGridView::$columns has a true CGridColumn::hasFooter value.

Whether the table should render a footer. This is true if any of the CGridView::$columns has a true CGridColumn::hasFooter value.

public CFormatter $formatter

The formatter instance. Defaults to the 'format' application component.

The formatter instance. Defaults to the 'format' application component.

Yii Framework API documentation generated by ApiGen 3.0dev