Sqlcommand In Beforsave Of Saved Model

Hi

I’ve got a User model, which has email attribute and company_id. There’s a company table and company_domain table which holds possible domains for company.

Email attribute is checked if it is a valid email, and if it match any domain form company_domain table.

After that validation i would like to set company_id attribute by checking which domain from company_domain it match. I do that in beforeValidate method of User model, but it returns no results no matter if i use find with createria or sqlcommand (select comapny_id from comapny_domain). When i run find code outside beforeValidate method i runs perfectly and finds company_doamin for particular email.

Is before validate blocking other sql statments?

beforeValidate should not be "blocking" any queries as such. Can you paste your code so that we can have a look?

User model:


protected function beforeValidate()

	{

		if(empty($this->errors)&&in_array($this->scenario,array('new','import','signup')))

		{

			preg_match('/@(.*)/',$this->email,$output);

			if(isset($output[1]))

			{

				$domain=CompanyDomain::model()->find('content=:content',array(':content'=>$output[1]));

				if($domain) 

				{

					$this->company_id=$domain->company_id;

				}

			} 

		}

		parent::beforeValidate();

	}

Import command:


$this->outputln("Starting import");

		$dir=Yii::getPathOfAlias('application.data');

		$file=$dir . DIRECTORY_SEPARATOR . $file;

		if (is_file($file))

		{

			$employees=file_get_contents($file);

			$rows=explode("\n",$employees);

			$i=0;

			foreach($rows as $row)

			{

				$model=new User;

				$model->active=false;

				$model->role=Rbac::getRoleValue(Rbac::ROLE_EMPLOYEE);

				$model->email=$row;

				$model->setScenario('import');

				if($model->save())

				{

					$i++;

					$this->outputln('[OK] '.$row,'green');

					$model->onUserRegistered=array(new UserEvents,'sendConfirmationLink');

					$e=new CEvent($this,array('user'=>$model,'messageTpl'=>'newUserImported'));

				    $model->onUserRegistered($e);

				} else {

					$this->outputln('[FAIL] '.$row,'red');

				};

			}

			$this->outputln($i." accounts created");

		} else

		{

			$this->outputln("No file found in ".$dir." dir");

		}

So in beforValidate $domain=CompanyDomain::model()->find(‘content=:content’,array(’:content’=>$output[1]));

returns nothing (but runnig find code anywhere elsewere finds records matched to domain)

???

http://www.yiiframework.com/doc/api/1.1/CModel#beforeValidate-detail:


 protected boolean beforeValidate()

{return} 	boolean 	whether validation should be executed. Defaults to true. If false is returned, the validation will stop and the model is considered invalid.

Make sure the parent implementation is invoked so that the event can be raised.

Try this:


return parent::beforeValidate();

Thank’s!

It works like a charm!