2

i'm struggling to get my beforesave in Yii Framework working this way:

when the user sends the form, beforesave() should fetch the highest number in a column called 'order' and insert a value of order+1 into current 'order' field.

After a few hours spent here reading posts i managed to compile this thing:

 public function beforeSave()

 {

   if (parent::beforeSave())
   {

        if($this->isNewRecord)
        {

             $criteria->select='max(order) as myMaxOrder';

             $get_it= new CActiveDataProvider(get_class($this), 
             array('criteria'=>$criteria,));

             $got_it=$get_it->getData();

             $whatweneed=$got_it[0]['myMaxOrder'];

             $this->order=(int)$whatweneed+1;

        }

        return true;
    }
    else
    return false;
 }

The code gets the MAX from 'order' but i really did't know how to deal properly with the YII's getData() method, so i var_dumped it and saw that what i was looking was there but i still don't know how to access this value apart from doing

 $whatweneed=$got_it[0]['myMaxOrder'];

Could you tell me how to do it right?

ok_computer
  • 67
  • 1
  • 2
  • 8

1 Answers1

9

If you set up your database so that the Order id is the Primary Key (it should already be anyway), just set it to "Auto Increment". If Auto Increment is set on your Primary Key (id), then when you save() a Model in Yii without an id it will automatically save it with an id one higher than the max. You won't need to do anything in beforeSave() at all! It is free functionality.

But perhaps I am totally misunderstanding your question. Maybe this is not an auto-incrementing primary key column for some reason. In that case, something like this should work (assuming your model is Order and you column is also, for some reason, called "order"):

$maxOrderNumber = Yii::app()->db->createCommand()
  ->select('max(order) as max')
  ->from('order')
  ->queryScalar();
$this->order = $maxOrderNumber + 1;

Good luck!

thaddeusmt
  • 15,410
  • 9
  • 67
  • 67
  • 1
    Hi Thaddeusmt! Many thanks for you explanation, the second part of your answer was what i was trying to achieve. It was supposed to be a part of a 'ordering' mechanism with jQuery.sortable UI which would allow the user to drag'n'drop the
  • elements in specific order. Now works like charm :) THanks again!
  • – ok_computer May 05 '11 at 22:30
  • 1
    Hmm that makes sense, storing a sort order. Glad I could help out! – thaddeusmt May 05 '11 at 22:39