Searching by unbound model property

Hi, I’m new in yii and I’m trying to write a simple web app but having some troubles. I added a model property that is not bounded to mysql through active record. Working ok but not being able to filter through this property in a CGridView.

In the model I added:





public function getTotal()

{

	$total=0;

	foreach ($this->items as $item){

		$total += $item->quantity * $item->product->price;

	}

	return $total;

}




The view:





<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'pedido-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'id',

		'date',

		'user',

                'total',

		array(

			'class'=>'CButtonColumn',

			'template'=>'{view}{delete}',

		),

	),

)); ?>



This Is working ok, showing the total but I cannot filter by “total column”. Is there any way to don’t let the user filter by this column? Or, much better, to make the filter work properly?




public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('date',$this->date,true);

		$criteria->compare('user',$this->user,true);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}



Thanks and regards!

I think (I am not shure) you cannot filter due to the total column is not part of the model. If you see, ‘filter’ is set to the model:




<?php $this->widget('zii.widgets.grid.CGridView', array(

        [...]

        'filter'=>$model,

        [...]

)); ?>



So, you can also write




<?php $this->widget('zii.widgets.grid.CGridView', array(

        [...]

        'filter'=>YourModel::model(),

        [...]

)); ?>



I think you have to manipulate filter property. But I dont know how =(

Set the CDataColumn filter property to false




  ...

  'user',

  array(

    'value'=>'$data->total',

    'filter'=>false,

  ),

  ...



For make the filter work, you probably can specify the calculation in the condition property of the db criteria (not only in the select property since, IIRC, a SQL column alias isn’t allowed in the WHERE clause).

@sensorario, if you don’t want to specify a filter instance at CGridview level, you can use null. No need to specify the semi-static class instance of the model.

/Tommy