Hide CGridview Delete Button If the Record is used

In my project, I have to hide the delete button from ‘CGridview’ If the record is not related to any other records or table and i have to check the record id, Is it possible or not to delete. Now i created one function ‘is_used()’ in model. This function check this record ‘ID’ is existed in relation table. If it is existed, it will return TRUE otherwise we will get FALSE statement.

After created this function, i will call it from ‘CGridview’ widget for every record. See the below code to run this concept.

User Model

<?php
class User extends CActiveRecord
{
	....................
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'userComments' => array(self::HAS_MANY, 'UserComments', 'user_id'),
			'user' => array(self::HAS_MANY, 'User', 'createdby'),
		);
	}
	// we have to call this from CGridview
	public function is_used(){
		if($this->userComments)
			return true;
		else if($this->user)
			return true;
		else
			return false;
	}
	....................
}
?>

User CGridView

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'user-grid',
	'dataProvider'=>$model->search(),
	//'filter'=>$model,
	'columns'=>array(
		......
		'username',
		......
		array(
			'class'=>'CButtonColumn',
			'buttons'=>array(
				'delete'=>array(
					'visible'=>'$data->is_used()?false:true'
				),
			),
		),
	),
)); ?>

Delete Action In User Controller

<?php 
class UserController extends Controller
{
	...............
	public function actionDelete($id)
	{
		$model=$this->loadModel($id);
		if($model->is_used()==false)
			$model->delete();
		else
			throw new CHttpException(404,'We cant delete this record.');

		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	...............
}
 ?>

Leave a Reply

Your email address will not be published. Required fields are marked *