override init CActiveRecord

Hi

I have a problem redefining the init method in one of my models extending CActiveRecord class

The init method does not execute when I do a find (but it executes when I do a new)

The problem: public function __construct

When I call a find method, this condition is true and return before call the init()




if($scenario===null) // internally used by populateRecord() and model()

                        return;



Why?

I’m redefining the scenario in the init




// init in my model

public function init()

    {

      

      if($condition))

          $this->scenario='scenario1';

      else

          $this->scenario='scenario2';


      return parent::init();

    }



What can I do?

I’ve run into the same problem and created a change request on the google code Yii project, but Qiang has denied my request.

I’ve simply overridden the __constructor in my class like this:




class UserModel extends CActiveRecord

{

	...


	public function __construct($scenario='insert')

	{

		parent::__construct($scenario);


		// Fix problem for creation by instantiate()

		if($scenario===null){ // internally used by populateRecord() and model()

			$this->init();


			$this->attachBehaviors($this->behaviors());

			$this->afterConstruct();

		}

	}


	...

}



As you can tell from this code fragment the attachBehaviors and afterConstruct are also not called by the default constructor when calling the model() method.

Hi, thanks for reply

why?

which was the answer or the reason?

What solution he proposes?

Remember the issue ?

greetings

Here’s the answer he added when closing my request:

I wasn’t satisfied with this answer but have been too busy to work on my project, therefore I never reacted on this mail (maybe I’ll do so, later, sometime).

maybe the solution (for me)

is use afterFind and not init for set the scenario

Solved for the master :rolleyes: in 1.1.1

  • Chg #949: The init() method will be invoked after an AR instance is created by the find methods (Qiang)