2>/dev/null

CButtonColumn extension for Yii Framework

Summary:

Useful for CGridView tables for data with a composite primary key, and/or data whose type doesn’t match the current controller

One of the built-in widgets in Yii Framework is CGridView, used in index and admin views in the code generated by the yiic tool. This in turn makes use of CButtonColumn to add standard View/Edit/Delete buttons to the CGridView table. Very handy.

The default URLs for the buttons are based two rather limiting assumptions: that the data model for the table uses a single-column primary key, and that the model belongs to the current controller. While you can override these URLs on an individual basis, for my current project it made sense to extend CButtonColumn instead:

<?php
/**
 * ButtonColumn class file.
 * ButtonColumn is a simple extension of CButtonColumn.
 * It correctly sets button URLs in the following cases:
 * * data has composite primary keys;
 * * data model does not belong to current controller.
 *
 * @author Jeff Soo
 */

class ButtonColumn extends CButtonColumn
{
	protected function initDefaultButtons()
	{	
		$modelClass=$this->grid->dataProvider->modelClass;
		$controller=strtolower($modelClass);

		if(is_array($modelClass::model()->primaryKey))
			$paramExpression='",$data->primaryKey)';
		else
			$paramExpression='",array("id"=>$data->primaryKey))';

		foreach(array('view','update','delete') as $id)
			$this->{$id.'ButtonUrl'}= 
			    'Yii::app()->urlManager->createUrl("'."$controller/$id$paramExpression";
		parent::initDefaultButtons();
	}
}

Posted 2010-03-16 (last modified 2017-02-18) under ,