Package | zii.widgets.grid |
---|---|
Inheritance | class CGridView » CBaseListView » CWidget » CBaseController » CComponent |
Since | 1.1 |
Source Code | framework/zii/widgets/grid/CGridView.php |
$dataProvider=new CActiveDataProvider('Post'); $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, ));
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.
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', ), ), ));
$data['create_time']
, not as object property.
Property | Type | Description | Defined By |
---|---|---|---|
actionPrefix | string | the prefix to the IDs of the actions. | CWidget |
afterAjaxUpdate | string | a javascript function that will be invoked after a successful AJAX response is received. | CGridView |
ajaxType | string | the type ('GET' or 'POST') of the AJAX requests. | CGridView |
ajaxUpdate | mixed | the ID of the container whose content may be updated with an AJAX response. | CGridView |
ajaxUpdateError | string | a javascript function that will be invoked if an AJAX update error occurs. | CGridView |
ajaxUrl | mixed | the URL for the AJAX requests should be sent to. | CGridView |
ajaxVar | string | the name of the GET variable that indicates the request is an AJAX request triggered by this widget. | CGridView |
baseScriptUrl | string | the base script URL for all grid view resources (eg javascript, CSS file, images). | CGridView |
beforeAjaxUpdate | string | a javascript function that will be invoked before an AJAX update occurs. | CGridView |
blankDisplay | string | the text to be displayed in an empty grid cell. | CGridView |
columns | array | grid column configuration. | CGridView |
controller | CController | Returns the controller that this widget belongs to. | CWidget |
cssFile | string | the URL of the CSS file used by this grid view. | CGridView |
dataProvider | IDataProvider | the data provider for the view. | CBaseListView |
emptyCssClass | string | the CSS class name for the container of the emptyText property. | CBaseListView |
emptyTagName | string | the HTML tag name for the container of the emptyText property. | CBaseListView |
emptyText | string | the message to be displayed when dataProvider does not have any data. | CBaseListView |
enableHistory | boolean | whether to leverage the {@link https://developer. | CGridView |
enablePagination | boolean | whether to enable pagination. | CBaseListView |
enableSorting | boolean | whether to enable sorting. | CBaseListView |
filter | CModel | the model instance that keeps the user-entered filter data. | CGridView |
filterCssClass | string | the CSS class name for the table row element containing all filter input fields. | CGridView |
filterPosition | string | whether the filters should be displayed in the grid view. | CGridView |
filterSelector | string | the jQuery selector of filter input fields. | CGridView |
formatter | CFormatter | the formatter instance. | CGridView |
hasFooter | boolean | whether the table should render a footer. | CGridView |
hideHeader | boolean | whether to hide the header cells of the grid. | CGridView |
htmlOptions | array | the HTML options for the view container tag. | CBaseListView |
id | string | Returns the ID of the widget or generates a new one if requested. | CWidget |
itemsCssClass | string | the CSS class name for the container of all data item display. | CBaseListView |
loadingCssClass | string | the CSS class name that will be assigned to the widget container element when the widget is updating its content via AJAX. | CGridView |
nullDisplay | string | the text to be displayed in a data cell when a data value is null. | CGridView |
owner | CBaseController | Returns the owner/creator of this widget. | CWidget |
pager | array|string | the configuration for the pager. | CBaseListView |
pagerCssClass | string | the CSS class name for the pager container. | CBaseListView |
rowCssClass | array | the CSS class names for the table body rows. | CGridView |
rowCssClassExpression | string | a PHP expression that is evaluated for every table body row and whose result is used as the CSS class name for the row. | CGridView |
rowHtmlOptionsExpression | string | a PHP expression that is evaluated for every table body row and whose result is used as additional HTML attributes for the row. | CGridView |
selectableRows | integer | the number of table body rows that can be selected. | CGridView |
selectionChanged | string | a javascript function that will be invoked after the row selection is changed. | CGridView |
showTableOnEmpty | boolean | whether to display the table even when there is no data. | CGridView |
skin | mixed | the name of the skin to be used by this widget. | CWidget |
summaryCssClass | string | the CSS class name for the summary text container. | CBaseListView |
summaryTagName | string | the HTML tag name for the container of the summaryText property. | CBaseListView |
summaryText | string | the summary text template for the view. | CBaseListView |
tagName | string | the tag name for the view container. | CBaseListView |
template | string | the template to be used to control the layout of various sections in the view. | CBaseListView |
updateSelector | string | the jQuery selector of the HTML elements that may trigger AJAX updates when they are clicked. | CGridView |
viewPath | string | Returns the directory containing the view files for this widget. | CWidget |
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | CComponent |
__construct() | Constructor. | CWidget |
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent |
__isset() | Checks if a property value is null. | CComponent |
__set() | Sets value of a component property. | CComponent |
__unset() | Sets a component property to be null. | CComponent |
actions() | Returns a list of actions that are used by this widget. | CWidget |
asa() | Returns the named behavior object. | CComponent |
attachBehavior() | Attaches a behavior to this component. | CComponent |
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent |
attachEventHandler() | Attaches an event handler to an event. | CComponent |
beginCache() | Begins fragment caching. | CBaseController |
beginClip() | Begins recording a clip. | CBaseController |
beginContent() | Begins the rendering of content that is to be decorated by the specified view. | CBaseController |
beginWidget() | Creates a widget and executes it. | CBaseController |
canGetProperty() | Determines whether a property can be read. | CComponent |
canSetProperty() | Determines whether a property can be set. | CComponent |
createWidget() | Creates a widget and initializes it. | CBaseController |
detachBehavior() | Detaches a behavior from the component. | CComponent |
detachBehaviors() | Detaches all behaviors from the component. | CComponent |
detachEventHandler() | Detaches an existing event handler. | CComponent |
disableBehavior() | Disables an attached behavior. | CComponent |
disableBehaviors() | Disables all behaviors attached to this component. | CComponent |
enableBehavior() | Enables an attached behavior. | CComponent |
enableBehaviors() | Enables all behaviors attached to this component. | CComponent |
endCache() | Ends fragment caching. | CBaseController |
endClip() | Ends recording a clip. | CBaseController |
endContent() | Ends the rendering of content. | CBaseController |
endWidget() | Ends the execution of the named widget. | CBaseController |
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent |
getController() | Returns the controller that this widget belongs to. | CWidget |
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent |
getFormatter() | Returns the formatter instance. Defaults to the 'format' application component. | CGridView |
getHasFooter() | Returns whether the table should render a footer. This is true if any of the columns has a true CGridColumn::hasFooter value. | CGridView |
getId() | Returns the ID of the widget or generates a new one if requested. | CWidget |
getOwner() | Returns the owner/creator of this widget. | CWidget |
getViewFile() | Looks for the view script file according to the view name. | CWidget |
getViewPath() | Returns the directory containing the view files for this widget. | CWidget |
hasEvent() | Determines whether an event is defined. | CComponent |
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent |
hasProperty() | Determines whether a property is defined. | CComponent |
init() | Initializes the grid view. | CGridView |
raiseEvent() | Raises an event. | CComponent |
registerClientScript() | Registers necessary client scripts. | CGridView |
render() | Renders a view. | CWidget |
renderContent() | Renders the main content of the view. | CBaseListView |
renderEmptyText() | Renders the empty message when there is no data. | CBaseListView |
renderFile() | Renders a view file. | CBaseController |
renderFilter() | Renders the filter. | CGridView |
renderInternal() | Renders a view file. | CBaseController |
renderItems() | Renders the data items for the grid view. | CGridView |
renderKeys() | Renders the key values of the data in a hidden tag. | CBaseListView |
renderPager() | Renders the pager. | CBaseListView |
renderSummary() | Renders the summary text. | CBaseListView |
renderTableBody() | Renders the table body. | CGridView |
renderTableFooter() | Renders the table footer. | CGridView |
renderTableHeader() | Renders the table header. | CGridView |
renderTableRow() | Renders a table body row. | CGridView |
run() | Renders the view. | CBaseListView |
setFormatter() | Sets the formatter instance | CGridView |
setId() | Sets the ID of the widget. | CWidget |
widget() | Creates a widget and executes it. | CBaseController |
Method | Description | Defined By |
---|---|---|
createDataColumn() | Creates a CDataColumn based on a shortcut column specification string. | CGridView |
initColumns() | Creates column objects and initializes them. | CGridView |
renderDataCell() | A seam for people extending CGridView to be able to hook onto the data cell rendering process. | CGridView |
renderSection() | Renders a section. | CBaseListView |
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.
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 enableHistory feature may not work correctly!
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).
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.
Useful if you just want to display this error differently. CGridView by default displays this error with an javascript.alert()... 'ajaxUpdateError'=>'function(xhr,ts,et,err,id){ $("#"+id).text(err); }', ...
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 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 ajaxUpdate is not false.
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).
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).
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 nullDisplay in that nullDisplay is only used by CDataColumn to render null data values.
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 CDataColumn::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.
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.
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:
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 CSS class name for the table row element containing all filter input fields. Defaults to 'filters'.
whether the filters should be displayed in the grid view. Valid values include:
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 formatter instance. Defaults to the 'format' application component.
whether the table should render a footer. This is true if any of the columns has a true CGridColumn::hasFooter value.
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.
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 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 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')
.
a PHP expression that is evaluated for every table body row and whose result is used as the CSS class name for the row. In this expression, you can use the following variables:
$row
the row number (zero-based).$data
the value provided by grid view object for the row.$this
the grid view object.$data
depends on data provider which is passed to the
grid view object. In case of CActiveDataProvider, $data
will have
object type and its values are accessed like $data->property
. In case of
CArrayDataProvider or CSqlDataProvider, it will have array type and its values must be
accessed like $data['property']
.
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 value provided by grid view object for the row.$this
the grid view object.$data
depends on data provider which is passed to the
grid view object. In case of CActiveDataProvider, $data
will have
object type and its values are accessed like $data->property
. In case of
CArrayDataProvider or CSqlDataProvider, it will have array type and its values must be
accessed like $data['property']
.
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).
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).
whether to display the table even when there is no data. Defaults to true. The emptyText will be displayed to indicate there is no data.
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', ...
protected CDataColumn createDataColumn(string $text)
| ||
$text | string | the column specification string |
{return} | CDataColumn | the column instance |
protected function createDataColumn($text)
{
if(!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/',$text,$matches))
throw new CException(Yii::t('zii','The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.'));
$column=new CDataColumn($this);
$column->name=$matches[1];
if(isset($matches[3]) && $matches[3]!=='')
$column->type=$matches[3];
if(isset($matches[5]))
$column->header=$matches[5];
return $column;
}
Creates a CDataColumn based on a shortcut column specification string.
public CFormatter getFormatter()
| ||
{return} | CFormatter | the formatter instance. Defaults to the 'format' application component. |
public function getFormatter()
{
if($this->_formatter===null)
$this->_formatter=Yii::app()->format;
return $this->_formatter;
}
public boolean getHasFooter()
| ||
{return} | boolean | whether the table should render a footer. This is true if any of the columns has a true CGridColumn::hasFooter value. |
public function getHasFooter()
{
foreach($this->columns as $column)
if($column->getHasFooter())
return true;
return false;
}
public void init()
|
public function init()
{
parent::init();
if(empty($this->updateSelector))
throw new CException(Yii::t('zii','The property updateSelector should be defined.'));
if(empty($this->filterSelector))
throw new CException(Yii::t('zii','The property filterSelector should be defined.'));
if(!isset($this->htmlOptions['class']))
$this->htmlOptions['class']='grid-view';
if($this->baseScriptUrl===null)
$this->baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets')).'/gridview';
if($this->cssFile!==false)
{
if($this->cssFile===null)
$this->cssFile=$this->baseScriptUrl.'/styles.css';
Yii::app()->getClientScript()->registerCssFile($this->cssFile);
}
$this->initColumns();
}
Initializes the grid view. This method will initialize required property values and instantiate columns objects.
protected void initColumns()
|
protected function initColumns()
{
if($this->columns===array())
{
if($this->dataProvider instanceof CActiveDataProvider)
$this->columns=$this->dataProvider->model->attributeNames();
elseif($this->dataProvider instanceof IDataProvider)
{
// use the keys of the first row of data as the default columns
$data=$this->dataProvider->getData();
if(isset($data[0]) && is_array($data[0]))
$this->columns=array_keys($data[0]);
}
}
$id=$this->getId();
foreach($this->columns as $i=>$column)
{
if(is_string($column))
$column=$this->createDataColumn($column);
else
{
if(!isset($column['class']))
$column['class']='CDataColumn';
$column=Yii::createComponent($column, $this);
}
if(!$column->visible)
{
unset($this->columns[$i]);
continue;
}
if($column->id===null)
$column->id=$id.'_c'.$i;
$this->columns[$i]=$column;
}
foreach($this->columns as $column)
$column->init();
}
Creates column objects and initializes them.
public void registerClientScript()
|
public function registerClientScript()
{
$id=$this->getId();
if($this->ajaxUpdate===false)
$ajaxUpdate=false;
else
$ajaxUpdate=array_unique(preg_split('/\s*,\s*/',$this->ajaxUpdate.','.$id,-1,PREG_SPLIT_NO_EMPTY));
$options=array(
'ajaxUpdate'=>$ajaxUpdate,
'ajaxVar'=>$this->ajaxVar,
'pagerClass'=>$this->pagerCssClass,
'loadingClass'=>$this->loadingCssClass,
'filterClass'=>$this->filterCssClass,
'tableClass'=>$this->itemsCssClass,
'selectableRows'=>$this->selectableRows,
'enableHistory'=>$this->enableHistory,
'updateSelector'=>$this->updateSelector,
'filterSelector'=>$this->filterSelector
);
if($this->ajaxUrl!==null)
$options['url']=CHtml::normalizeUrl($this->ajaxUrl);
if($this->ajaxType!==null) {
$options['ajaxType']=strtoupper($this->ajaxType);
$request=Yii::app()->getRequest();
if ($options['ajaxType']=='POST' && $request->enableCsrfValidation) {
$options['csrfTokenName']=$request->csrfTokenName;
$options['csrfToken']=$request->getCsrfToken();
}
}
if($this->enablePagination)
$options['pageVar']=$this->dataProvider->getPagination()->pageVar;
foreach(array('beforeAjaxUpdate', 'afterAjaxUpdate', 'ajaxUpdateError', 'selectionChanged') as $event)
{
if($this->$event!==null)
{
if($this->$event instanceof CJavaScriptExpression)
$options[$event]=$this->$event;
else
$options[$event]=new CJavaScriptExpression($this->$event);
}
}
$options=CJavaScript::encode($options);
$cs=Yii::app()->getClientScript();
$cs->registerCoreScript('jquery');
$cs->registerCoreScript('bbq');
if($this->enableHistory)
$cs->registerCoreScript('history');
$cs->registerScriptFile($this->baseScriptUrl.'/jquery.yiigridview.js',CClientScript::POS_END);
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiGridView($options);");
}
Registers necessary client scripts.
protected void renderDataCell(CGridColumn $column, integer $row)
| ||
$column | CGridColumn | The Column instance to |
$row | integer |
protected function renderDataCell($column, $row)
{
$column->renderDataCell($row);
}
A seam for people extending CGridView to be able to hook onto the data cell rendering process.
By overriding only this method we will not need to copypaste and modify the whole entirety of `renderTableRow`.
Or override `renderDataCell()` method of all possible CGridColumn descendants.
public void renderFilter()
|
public function renderFilter()
{
if($this->filter!==null)
{
echo "<tr class=\"{$this->filterCssClass}\">\n";
foreach($this->columns as $column)
$column->renderFilterCell();
echo "</tr>\n";
}
}
Renders the filter.
public void renderItems()
|
public function renderItems()
{
if($this->dataProvider->getItemCount()>0 || $this->showTableOnEmpty)
{
echo "<table class=\"{$this->itemsCssClass}\">\n";
$this->renderTableHeader();
ob_start();
$this->renderTableBody();
$body=ob_get_clean();
$this->renderTableFooter();
echo $body; // TFOOT must appear before TBODY according to the standard.
echo "</table>";
}
else
$this->renderEmptyText();
}
Renders the data items for the grid view.
public void renderTableBody()
|
public function renderTableBody()
{
$data=$this->dataProvider->getData();
$n=count($data);
echo "<tbody>\n";
if($n>0)
{
for($row=0;$row<$n;++$row)
$this->renderTableRow($row);
}
else
{
echo '<tr><td colspan="'.count($this->columns).'" class="empty">';
$this->renderEmptyText();
echo "</td></tr>\n";
}
echo "</tbody>\n";
}
Renders the table body.
public void renderTableFooter()
|
public function renderTableFooter()
{
$hasFilter=$this->filter!==null && $this->filterPosition===self::FILTER_POS_FOOTER;
$hasFooter=$this->getHasFooter();
if($hasFilter || $hasFooter)
{
echo "<tfoot>\n";
if($hasFooter)
{
echo "<tr>\n";
foreach($this->columns as $column)
$column->renderFooterCell();
echo "</tr>\n";
}
if($hasFilter)
$this->renderFilter();
echo "</tfoot>\n";
}
}
Renders the table footer.
public void renderTableHeader()
|
public function renderTableHeader()
{
if(!$this->hideHeader)
{
echo "<thead>\n";
if($this->filterPosition===self::FILTER_POS_HEADER)
$this->renderFilter();
echo "<tr>\n";
foreach($this->columns as $column)
$column->renderHeaderCell();
echo "</tr>\n";
if($this->filterPosition===self::FILTER_POS_BODY)
$this->renderFilter();
echo "</thead>\n";
}
elseif($this->filter!==null && ($this->filterPosition===self::FILTER_POS_HEADER || $this->filterPosition===self::FILTER_POS_BODY))
{
echo "<thead>\n";
$this->renderFilter();
echo "</thead>\n";
}
}
Renders the table header.
public void renderTableRow(integer $row)
| ||
$row | integer | the row number (zero-based). |
public function renderTableRow($row)
{
$htmlOptions=array();
if($this->rowHtmlOptionsExpression!==null)
{
$data=$this->dataProvider->data[$row];
$options=$this->evaluateExpression($this->rowHtmlOptionsExpression,array('row'=>$row,'data'=>$data));
if(is_array($options))
$htmlOptions = $options;
}
if($this->rowCssClassExpression!==null)
{
$data=$this->dataProvider->data[$row];
$class=$this->evaluateExpression($this->rowCssClassExpression,array('row'=>$row,'data'=>$data));
}
elseif(is_array($this->rowCssClass) && ($n=count($this->rowCssClass))>0)
$class=$this->rowCssClass[$row%$n];
if(!empty($class))
{
if(isset($htmlOptions['class']))
$htmlOptions['class'].=' '.$class;
else
$htmlOptions['class']=$class;
}
echo CHtml::openTag('tr', $htmlOptions)."\n";
foreach($this->columns as $column)
$this->renderDataCell($column, $row);
echo "</tr>\n";
}
Renders a table body row.
public void setFormatter(CFormatter $value)
| ||
$value | CFormatter | the formatter instance |
public function setFormatter($value)
{
$this->_formatter=$value;
}
Using With CSqlDataProvider
If you use this with CSqlDataProvider note that the $data will be an array, instead of an object. So, for example, to make an email link the code will be of the form:
The only place this appears to be documented is in a Forum reply.
Similarly, if you wish to use the standard buttons you will need code of the form:
'class'=>'CButtonColumn', 'viewButtonUrl'=>'Yii::app()->createUrl("/controllername/view", array("id" => $data\["id"\]))', 'deleteButtonUrl'=>'Yii::app()->createUrl("/controllername/delete", array("id" => $data\["id"\]))', 'updateButtonUrl'=>'Yii::app()->createUrl("/controllername/update", array("id" => $data\["id"\]))', ),
change the column header
If you want to change the column header in your grid view:
array( // display 'category.name' using an 'Category' as header 'name'=>'category.name', 'header'=>'Category', ),
Using With CArrayDataProvider
Please refer to comment by thinkingspace at 2010/10/15 02:44am
The same rules apply to $data when CArrayDataProvider is used.
In this case $data is an array, not an object.
Formatting column with date in different format
In the beginning of this page there is only an example of formatting column with date, using PHP date() function, therefore requiring a timestamp (integer, number of seconds that passed since Unix Epoch, see PHP manual for more details).
Here is an example how to format column, when you receive date in it and you only want to reformat it (as converting received date to timestamp and them back to date with different format might be a real pain in the a..). It is using procedural approach to PHP's DateTime class:
$this->widget('zii.widgets.grid.CGridView', array ( 'id'=>'zlecenia-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array ( 'ID', array ( 'name'=>'DATR', 'htmlOptions'=>array('style'=>'text-align: center'), 'value'=>'date_format(date_create($data->DATR), "Y-m-d H:i:s")', ), ), ));
working example with filter field and link from foreign key
array( 'type'=>'raw', 'value'=>'CHtml::link($data->owner->email, array("developers/update", "id"=>$data->owner->id));', 'name'=>'developers_id', /<-- this must be defined so the ajax filter to show up ),
How to set a css class to a specific row
Pulling together bits and pieces of code addressing this issue, here is one example of how to solve this problem:
<?php function evenOdd($num) { ($num % 2==0) ? $class = 'odd' : $class = 'even'; return $class; } $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'name-of-your-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'rowCssClassExpression'=>'($data->my_id=="default") ? "$data->my_id, odd" : evenOdd($row)', 'columns'=>array( 'my_id', 'another_column', array(....
Filtering and sorting in ajax mode
I've been facing problems with filtering and sorting in ajax mode. It took me some time to find the right answer on forums. I think it's worth mentioning here.
An answer by Qiang:
For gridview to work properly in ajax mode, you have to add a URL rule like the following if you use "path" format:
'<controller:\w+>/<action:\w+>' => '<controller>/<action>'
This will put all filter conditions into the query string part instead of the pathinfo part.
Eager loading related records correctly
If you have a grid view and want to list records together with related records, like this:
| Username | Groups | | [......] | [.......................] | <--search bar ---------------------------------------- | user1 | Admins, Users, Moderators | [x] | user2 | Users, Moderators | [x] | user3 | Users | [x]
Two problems might occur:
To solve this correctly, create your criteria like this:
$criteria=new CDbCriteria; $criteria->with = array('groups' => array('select' => false)); // will lazy load groups when displaying user table row $criteria->together = true; $criteria->group = 't.id'; // correctly group records $criteria->compare('t.username', $username, true); $criteria->compare('groups.name', $searchGroups, true);
Signup or Login in order to comment.