Versions
Look up a class, method, property or event

CButtonColumn

Package zii.widgets.grid
Inheritance class CButtonColumn » CGridColumn » CComponent
Since 1.1
Source Code framework/zii/widgets/grid/CButtonColumn.php
CButtonColumn represents a grid view column that renders one or several buttons.

By default, it will display three buttons, "view", "update" and "delete", which triggers the corresponding actions on the model of the row.

By configuring buttons and template properties, the column can display other buttons and customize the display order of the buttons.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
afterDelete string a javascript function that will be invoked after the delete ajax call. CButtonColumn
buttons array the configuration for buttons. CButtonColumn
cssClassExpression string a PHP expression that is evaluated for every data cell and whose result is used as the CSS class name for the data cell. CGridColumn
deleteButtonImageUrl string the image URL for the delete button. CButtonColumn
deleteButtonLabel string the label for the delete button. CButtonColumn
deleteButtonOptions array the HTML options for the delete button tag. CButtonColumn
deleteButtonUrl string a PHP expression that is evaluated for every delete button and whose result is used as the URL for the delete button. CButtonColumn
deleteConfirmation string the confirmation message to be displayed when delete button is clicked. CButtonColumn
filterHtmlOptions array the HTML options for the filter cell tag. CGridColumn
footerHtmlOptions array the HTML options for the footer cell tag. CButtonColumn
grid CGridView the grid view object that owns this column. CGridColumn
hasFooter boolean whether this column has a footer cell. CGridColumn
headerHtmlOptions array the HTML options for the header cell tag. CButtonColumn
htmlOptions array the HTML options for the data cell tags. CButtonColumn
id string the ID of this column. CGridColumn
template string the template that is used to render the content in each data cell. CButtonColumn
updateButtonImageUrl string the image URL for the update button. CButtonColumn
updateButtonLabel string the label for the update button. CButtonColumn
updateButtonOptions array the HTML options for the update button tag. CButtonColumn
updateButtonUrl string a PHP expression that is evaluated for every update button and whose result is used as the URL for the update button. CButtonColumn
viewButtonImageUrl string the image URL for the view button. CButtonColumn
viewButtonLabel string the label for the view button. CButtonColumn
viewButtonOptions array the HTML options for the view button tag. CButtonColumn
viewButtonUrl string a PHP expression that is evaluated for every view button and whose result is used as the URL for the view button. CButtonColumn
visible boolean whether this column is visible. CGridColumn

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CGridColumn
__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
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
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
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
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getHasFooter() Returns whether this column has a footer cell. This is determined based on whether footer is set. CGridColumn
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 column. CButtonColumn
raiseEvent() Raises an event. CComponent
renderDataCell() Renders a data cell. CGridColumn
renderFilterCell() Renders the filter cell. CGridColumn
renderFooterCell() Renders the footer cell. CGridColumn
renderHeaderCell() Renders the header cell. CGridColumn

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
initDefaultButtons() Initializes the default buttons (view, update and delete). CButtonColumn
registerClientScript() Registers the client scripts for the button column. CButtonColumn
renderButton() Renders a link button. CButtonColumn
renderDataCellContent() Renders the data cell content. CButtonColumn
renderFilterCellContent() Renders the filter cell content. CGridColumn
renderFooterCellContent() Renders the footer cell content. CGridColumn
renderHeaderCellContent() Renders the header cell content. CGridColumn

Property Details

afterDelete property
public string $afterDelete;

a javascript function that will be invoked after the delete ajax call. This property is used only if $this->buttons['delete']['click'] is not set.

The function signature is function(link, success, data)

  • link references the delete link.
  • success status of the ajax call, true if the ajax call was successful, false if the ajax call failed.
  • data the data returned by the server in case of a successful call or XHR object in case of error.
Note that if success is true it does not mean that the delete was successful, it only means that the ajax call was successful.

Example:
 array(
    class'=>'CButtonColumn',
    'afterDelete'=>'function(link,success,data){ if(success) alert("Delete completed successfuly"); }',
 ),

buttons property
public array $buttons;

the configuration for buttons. Each array element specifies a single button which has the following format:

'buttonID' => array(
    'label'=>'...',     // text label of the button
    'url'=>'...',       // a PHP expression for generating the URL of the button
    'imageUrl'=>'...',  // image URL of the button. If not set or false, a text link is used
    'options'=>array(...), // HTML options for the button tag
    'click'=>'...',     // a JS function to be invoked when the button is clicked
    'visible'=>'...',   // a PHP expression for determining whether the button is visible
)


In the PHP expression for the 'url' option and/or 'visible' option, the variable $row refers to the current row number (zero-based), and $data refers to the data model for the row. 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.

If the 'buttonID' is 'view', 'update' or 'delete' the options will be applied to the default buttons.

Note that in order to display non-default buttons, the template property needs to be configured so that the corresponding button IDs appear as tokens in the template.

deleteButtonImageUrl property
public string $deleteButtonImageUrl;

the image URL for the delete button. If not set, an integrated image will be used. You may set this property to be false to render a text link instead.

deleteButtonLabel property
public string $deleteButtonLabel;

the label for the delete button. Defaults to "Delete". Note that the label will not be HTML-encoded when rendering.

deleteButtonOptions property
public array $deleteButtonOptions;

the HTML options for the delete button tag.

deleteButtonUrl property
public string $deleteButtonUrl;

a PHP expression that is evaluated for every delete button and whose result is used as the URL for the delete button. In this expression, you can use the following variables:

  • $row the row number (zero-based)
  • $data the data model for the row
  • $this the column 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.

deleteConfirmation property
public string $deleteConfirmation;

the confirmation message to be displayed when delete button is clicked. By setting this property to be false, no confirmation message will be displayed. This property is used only if $this->buttons['delete']['click'] is not set.

footerHtmlOptions property
public array $footerHtmlOptions;

the HTML options for the footer cell tag.

headerHtmlOptions property
public array $headerHtmlOptions;

the HTML options for the header cell tag.

htmlOptions property
public array $htmlOptions;

the HTML options for the data cell tags.

template property
public string $template;

the template that is used to render the content in each data cell. These default tokens are recognized: {view}, {update} and {delete}. If the buttons property defines additional buttons, their IDs are also recognized here. For example, if a button named 'preview' is declared in buttons, we can use the token '{preview}' here to specify where to display the button.

updateButtonImageUrl property
public string $updateButtonImageUrl;

the image URL for the update button. If not set, an integrated image will be used. You may set this property to be false to render a text link instead.

updateButtonLabel property
public string $updateButtonLabel;

the label for the update button. Defaults to "Update". Note that the label will not be HTML-encoded when rendering.

updateButtonOptions property
public array $updateButtonOptions;

the HTML options for the update button tag.

updateButtonUrl property
public string $updateButtonUrl;

a PHP expression that is evaluated for every update button and whose result is used as the URL for the update button. In this expression, you can use the following variables:

  • $row the row number (zero-based)
  • $data the data model for the row
  • $this the column 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.

viewButtonImageUrl property
public string $viewButtonImageUrl;

the image URL for the view button. If not set, an integrated image will be used. You may set this property to be false to render a text link instead.

viewButtonLabel property
public string $viewButtonLabel;

the label for the view button. Defaults to "View". Note that the label will not be HTML-encoded when rendering.

viewButtonOptions property
public array $viewButtonOptions;

the HTML options for the view button tag.

viewButtonUrl property
public string $viewButtonUrl;

a PHP expression that is evaluated for every view button and whose result is used as the URL for the view button. In this expression, you can use the following variables:

  • $row the row number (zero-based)
  • $data the data model for the row
  • $this the column 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.

Method Details

init() method
public void init()
Source Code: framework/zii/widgets/grid/CButtonColumn.php#192 (show)
public function init()
{
    
$this->initDefaultButtons();

    foreach(
$this->buttons as $id=>$button)
    {
        if(
strpos($this->template,'{'.$id.'}')===false)
            unset(
$this->buttons[$id]);
        elseif(isset(
$button['click']))
        {
            if(!isset(
$button['options']['class']))
                
$this->buttons[$id]['options']['class']=$id;
            if(!(
$button['click'] instanceof CJavaScriptExpression))
                
$this->buttons[$id]['click']=new CJavaScriptExpression($button['click']);
        }
    }

    
$this->registerClientScript();
}

Initializes the column. This method registers necessary client script for the button column.

initDefaultButtons() method
protected void initDefaultButtons()
Source Code: framework/zii/widgets/grid/CButtonColumn.php#215 (show)
protected function initDefaultButtons()
{
    if(
$this->viewButtonLabel===null)
        
$this->viewButtonLabel=Yii::t('zii','View');
    if(
$this->updateButtonLabel===null)
        
$this->updateButtonLabel=Yii::t('zii','Update');
    if(
$this->deleteButtonLabel===null)
        
$this->deleteButtonLabel=Yii::t('zii','Delete');
    if(
$this->viewButtonImageUrl===null)
        
$this->viewButtonImageUrl=$this->grid->baseScriptUrl.'/view.png';
    if(
$this->updateButtonImageUrl===null)
        
$this->updateButtonImageUrl=$this->grid->baseScriptUrl.'/update.png';
    if(
$this->deleteButtonImageUrl===null)
        
$this->deleteButtonImageUrl=$this->grid->baseScriptUrl.'/delete.png';
    if(
$this->deleteConfirmation===null)
        
$this->deleteConfirmation=Yii::t('zii','Are you sure you want to delete this item?');

    foreach(array(
'view','update','delete') as $id)
    {
        
$button=array(
            
'label'=>$this->{$id.'ButtonLabel'},
            
'url'=>$this->{$id.'ButtonUrl'},
            
'imageUrl'=>$this->{$id.'ButtonImageUrl'},
            
'options'=>$this->{$id.'ButtonOptions'},
        );
        if(isset(
$this->buttons[$id]))
            
$this->buttons[$id]=array_merge($button,$this->buttons[$id]);
        else
            
$this->buttons[$id]=$button;
    }

    if(!isset(
$this->buttons['delete']['click']))
    {
        if(
is_string($this->deleteConfirmation))
            
$confirmation="if(!confirm(".CJavaScript::encode($this->deleteConfirmation).")) return false;";
        else
            
$confirmation='';

        if(
Yii::app()->request->enableCsrfValidation)
        {
            
$csrfTokenName Yii::app()->request->csrfTokenName;
            
$csrfToken Yii::app()->request->csrfToken;
            
$csrf "\n\t\tdata:{ '$csrfTokenName':'$csrfToken' },";
        }
        else
            
$csrf '';

        if(
$this->afterDelete===null)
            
$this->afterDelete='function(){}';

        
$this->buttons['delete']['click']=<<<EOD
function() {
$confirmation
var th = this,
    afterDelete = 
$this->afterDelete;
jQuery('#
{$this->grid->id}').yiiGridView('update', {
    type: 'POST',
    url: jQuery(this).attr('href'),
$csrf
    success: function(data) {
        jQuery('#
{$this->grid->id}').yiiGridView('update');
        afterDelete(th, true, data);
    },
    error: function(XHR) {
        return afterDelete(th, false, XHR);
    }
});
return false;
}
EOD;
    }
}

Initializes the default buttons (view, update and delete).

registerClientScript() method
protected void registerClientScript()
Source Code: framework/zii/widgets/grid/CButtonColumn.php#290 (show)
protected function registerClientScript()
{
    
$js=array();
    foreach(
$this->buttons as $id=>$button)
    {
        if(isset(
$button['click']))
        {
            
$function=CJavaScript::encode($button['click']);
            
$class=preg_replace('/\s+/','.',$button['options']['class']);
            
$js[]="jQuery(document).on('click','#{$this->grid->id} a.{$class}',$function);";
        }
    }

    if(
$js!==array())
        
Yii::app()->getClientScript()->registerScript(__CLASS__.'#'.$this->idimplode("\n",$js));
}

Registers the client scripts for the button column.

renderButton() method
protected void renderButton(string $id, array $button, integer $row, mixed $data)
$id string the ID of the button
$button array the button configuration which may contain 'label', 'url', 'imageUrl' and 'options' elements. See buttons for more details.
$row integer the row number (zero-based)
$data mixed the data object associated with the row
Source Code: framework/zii/widgets/grid/CButtonColumn.php#335 (show)
protected function renderButton($id,$button,$row,$data)
{
    if (isset(
$button['visible']) && !$this->evaluateExpression($button['visible'],array('row'=>$row,'data'=>$data)))
          return;
    
$label=isset($button['label']) ? $button['label'] : $id;
    
$url=isset($button['url']) ? $this->evaluateExpression($button['url'],array('data'=>$data,'row'=>$row)) : '#';
    
$options=isset($button['options']) ? $button['options'] : array();
    if(!isset(
$options['title']))
        
$options['title']=$label;
    if(isset(
$button['imageUrl']) && is_string($button['imageUrl']))
        echo 
CHtml::link(CHtml::image($button['imageUrl'],$label),$url,$options);
    else
        echo 
CHtml::link($label,$url,$options);
}

Renders a link button.

renderDataCellContent() method
protected void renderDataCellContent(integer $row, mixed $data)
$row integer the row number (zero-based)
$data mixed the data associated with the row
Source Code: framework/zii/widgets/grid/CButtonColumn.php#313 (show)
protected function renderDataCellContent($row,$data)
{
    
$tr=array();
    
ob_start();
    foreach(
$this->buttons as $id=>$button)
    {
        
$this->renderButton($id,$button,$row,$data);
        
$tr['{'.$id.'}']=ob_get_contents();
        
ob_clean();
    }
    
ob_end_clean();
    echo 
strtr($this->template,$tr);
}

Renders the data cell content. This method renders the view, update and delete buttons in the data cell.

Total 6 comments

#15587 report it
haymps at 2013/11/26 12:13pm
Re:buttonUrl example

If you used Gii to create your application, then your id column will be named id.

So use $data->id in the above example

'viewButtonUrl'=>'Yii::app()->createUrl("/project/viewNewReport", array("id" => $data->id))',

#10714 report it
Milind R at 2012/11/18 06:43pm
Which models do the CGridView buttons operate on...

An important point to note is that these buttons operate by using Yii::app()->controller->createUrl and NOT from the supplied CActiveDataProvider , which means that it uses the current controller, which is assumed to be operating on its own model.

This could cause confusion when creating a nested CGridView s inside CListView for displaying and managing relational models as well.

#8598 report it
somethingkindawierd at 2012/06/13 04:09pm
Using php 5.3 callback functions.

The parameters for the callback functions are not always in the same order.

Notice in the example below that the url takes in ($data, $row) and that visible takes in ($row, $data).

You can see this viewing the source of renderButton

'columns'=>array(
    ...
    array(
            'class'=>'CButtonColumn',
                'buttons'=>array(
                    'view'=>array(
                    'url'=>function ($data, $row) { 
                        // work here
                    },
                    'visible'=>function($row, $data) { 
                        // work here
                    },
                    ),
                ),
            ),
        ),
    ...
)
#3145 report it
Steve Friedl at 2011/03/21 11:02am
Setting 'visible' attributes of existing buttons

The API documentation suggests that the 'buttons' => array(...) is for additional buttons, but it can be used to provide data about existing ones too. This is where the visible attribute can be defined, and it's evaluated for every row by passing $data to it.

...
    array(
        'class'    => 'CButtonColumn',
        'template' => '{view} {update} {delete}',
        ...
        'buttons'  => array(
            'delete' => array(
                'visible' => '$data->canDelete', // assumes model has canDelete attribute
            )
         ),

Note that canDelete is not a native Yii attribute, but one provided by the model's author in order to make this visible assignment easier.

The 'buttons' array values are merged with other values explicitly assigned, such as deleteButtonUrl to make a unified array of settings.

Note further that options is for HTML options, and visible is not one of them.

#719 report it
backwardselvis at 2010/03/11 11:01pm
specifying buttons and their attributes


<?php
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'firstName',
        'middleInitial',
        'lastName',
        array(
            'class'=>'CButtonColumn',
                        'template' => '{postview} {preview}',
                        'buttons' => array(
                            'postview' => array(
                    'label'=>'...',     // text label of the button
                    'url'=>'...',       // the PHP expression for generating the URL of the button
                    'imageUrl'=>'...',  // image URL of the button. If not set or false, a text link is used
                    'options'=>array(...), // HTML options for the button tag
                    'click'=>'...',     // a JS function to be invoked when the button is clicked
                            ),
                            'preview' => array(
                    'label'=>'...',     // text label of the button
                    'url'=>'...',       // the PHP expression for generating the URL of the button
                    'imageUrl'=>'...',  // image URL of the button. If not set or false, a text link is used
                    'options'=>array(...), // HTML options for the button tag
                    'click'=>'...',     // a JS function to be invoked when the button is clicked
                            ),
                            
                        ),
                        
        ),
    ),
)); ?>

And remember, the Markdown syntax is your friend. use the PRE and CODE tags for readability.

Note: Replace [ ] with < >

[pre][code] PHP code goes here [/code][/pre]

#881 report it
luoshiben at 2010/02/13 12:04am
buttonUrl example

Since an example is worth a thousand words, here's how to set the url for CButtonColumn buttons:

<?php
$this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider'=>$dataProvider,
  'columns'=>array(
    'attribute1_name',
    'attribute2_name',
    array(
      'class'=>'CButtonColumn',
      'viewButtonUrl'=>'Yii::app()->createUrl("/controllername/view", array("id" => $data->model_id))',
      'deleteButtonUrl'=>'Yii::app()->createUrl("/controllername/delete", array("id" => $data->model_id))',
      'updateButtonUrl'=>'Yii::app()->createUrl("/controllername/update", array("id" => $data->model_id))',
    ),
  ),
));
?>

Leave a comment

Please to leave your comment.