Behavior Property Problem

I want to extract the maximum value in a certain table column called ‘order’. To do this, I use a function in a bahavior which is attached to the model.




class mybehavior extends CActiveRecordBehavior

{	

	public $maxColumn = 0;

    

	public function getMaxOrder()

	{

		$model			= $this->getOwner();

		$criteria		= new CDbCriteria;

		$criteria->select	= 'MAX(t.order) as maxColumn';

		$criteria->condition	= 't.business = :parm';

		$criteria->params = array(

			':parm' => Yii::app()->user->getState('businessID')

		);

		

		$maxmodel = $model->find($criteria);

		$max   	  = $maxmodel['maxColumn'];

		return $max;

	}

}



The above code does not work - the value of $maxColumn stays 0.

But if I remove ‘public $maxColumn = 0;’ from the behavior and put it in the model, then the above code works.

Any ideas how to get the code to work with $maxColumn being defined in the behavior and not in the model?

Thanx

because you are working with model and hence keeping the model related variables inside the model is good one so u keep it up…

Hi Ahamed

Ya, but shouldn’t the behavior be more independent - having its own properties defined inside its own boundaries?

How else are you going to re-use the behavior if it does not define its own properties?

yes you are right I agree. but doing so is not works as expected in the behavior so what can we do?

I would do it like this:




class mybehavior extends CActiveRecordBehavior

{       

        public $maxColumn = 0;

    

        public function getMaxOrder()

        {

                $criteria = new CDbCriteria;

                $criteria->select = 'MAX(t.order)';

                $criteria->condition = 't.business = :parm';

                $criteria->params = array(

                        ':parm' => Yii::app()->user->getState('businessID')

                );


                return $this->maxColumn = $this->getOwner()->getCommandBuilder()->createFindCommand($this->getOwner()->tableName(), $criteria)->queryScalar();

        }

}



Thanx Andy

Will try that.