Validate in CModel

Hey! One fast question:

When the validation fails with validate(), in CModel, does it return null? I ask this because when it fails here, seems the returned value is null…but i didn’t find any reference to this null value in the API. :mellow:

so…is it normal or should it return false or 0?

CModel::validate() always returns a boolean, i.e. true or false. If you see a null value, the validate() method probably is not executed.

Thanks for explaining. :)

I have the following code:




class RegisterUserForm extends CFormModel{

	

	/**

	 * Reordenar os atributos para serem lidos no controlador

	 * Verificar se a password ´e igual ´a confirmaçao

	 * Verificar se o email ´e valido

	 * Verificar se a data de nascimento est´a no formato correcto

	 */

	

	public $isInternal;

	public $identifier; //username

	public $internalID; //CLIP

	public $name;

	public $email;

	public $sex;

	public $password;

	public $confirmPassword;

	public $photo;

	public $location;

	public $birthday;

	public $verifyCode;

	

	

	public function rules(){

		

		return array(

		

			array('email','required'),

			

			array('email','email'),

			

			//array('sex','in','range'=>array('masculino','feminino')),

			

			//array('password', 'compare', 'compareAttribute'=>'confirmPassword'),

			

			//array('identifier','clipIDValidate'),

			

			//array('emails','email'),

			

			//array('photo','url'),

			

			//array('birthday','myCheckDate'),

			

			//array('verifyCode', 'captcha', 'allowEmpty'=>!extension_loaded('gd'))

		

		);

	}








<?php


class UserController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to 'column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='column2';


	/**

	 * @var CActiveRecord the currently loaded data model instance.

	 */

	private $_model;


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}

	

	public function actions()

	{

		return array(

			// captcha action renders the CAPTCHA image displayed on the contact page

			'captcha'=>array(

                'class'=>'CCaptchaAction',

				'backColor'=>0xFFFFFF,

			),

			'page'=>array(

				'class'=>'CViewAction',

			),

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view','captcha','info'),

				'users'=>array('*'),

			),

			array('allow',

				'actions'=>array('activateUser','registerUser'),

				'users'=>array('?'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 */

	public function actionView()

	{

		$this->render('view',array(

			'model'=>$this->loadModel(),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new User;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['User']))

		{

			$model->attributes=$_POST['User'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

				

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionUpdate()

	{

		$model=$this->loadModel();


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['User']))

		{

			$model->attributes=$_POST['User'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'index' page.

	 */

	public function actionDelete()

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel()->delete();


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(array('index'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('User');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new User('search');

		if(isset($_GET['User']))

			$model->attributes=$_GET['User'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 */

	public function loadModel()

	{

		if($this->_model===null)

		{

			if(isset($_GET['id']))

				$this->_model=User::model()->findbyPk($_GET['id']);

			if($this->_model===null)

				throw new CHttpException(404,'The requested page does not exist.');

		}

		return $this->_model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

	

	/*

	 * Quando entra no sistema ou quando muda de contexto de edição de comunidade

	 */

	public function changeUserPermissions(){

		

	}

	

	/*

	 * Usada por utilizadores sem login feito

	 * Registo de um novo utilizador no sistema

	 */

	public function actionRegisterUser(){

		/*

		 * Verifica se o identificador é interno

		 */

		

		

		$regForm = new RegisterUserForm;

		

		if(isset($_POST['RegisterUserForm'])){

			UserController::echoVector($_POST['RegisterUserForm']);

			$regForm->attributes = $_POST['RegisterUserForm'];

			echo $regForm->validate();

		}

		

		$this->render('registerUser',array('model'=>$regForm));

		

	}

	

	public function actionInfo(){

		echo phpinfo();

	}

	

	/*

	 * Usada por utilizadores sem login feito

	 */

	public function actionActivateUser(){

		

		/**

		 * Procurar na tabela TemporaryUser pela activationKey

		 *  e adicionar essa row à tabela User

		 */

		/**

		 * Modificar para não sofrer SQL Injection

		 */

		if(isset($_GET['activationKey'])){

			$temporaryuser = TemporaryUser::model()->findByPk($_GET['activationkey']);

			

			$activateduser = new User;

			

			$activateduser->identifier = $temporaryuser->identifier;

			$activateduser->password = $temporaryuser->password;

			$activateduser->name = $temporaryuser->name;

			$activateduser->photo = $temporaryuser->photo;

			$activateduser->location = $temporaryuser->location;

			$activateduser->birthday = $temporaryuser->birthday;

			

			$activateduser->save();

		}

	}

	

	private function echoVector($vec){

		foreach($vec as $k => $v)

			echo $k . "	" .$v. "\n";

	}

}










[code]

<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'user-form',

	'enableAjaxValidation'=>false,

)); ?>

<?php echo $form->errorSummary($model); ?>




	<div class="row">

		<?php echo $form->labelEx($model,'Email'); ?>

		<?php echo $form->textField($model,'email'); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>




	<div class="row buttons">

		<?php echo CHtml::submitButton('Registar'); ?>

	</div>

<?php $this->endWidget(); ?>


When i write, for example, mine@mail.com, it works fine and validates as an email and print 1 in the view. But when i write, for example, minemail.pt, it prints nothing when the program reach to "echo $regForm->validate();"...


so, can someone tell me what am i doing wrong?


Thanks



[/code]

Seems to work as expected




<?php 

  echo 'false:>'.false.'<<br/>';

  echo 'true:>'.true.'<<br/>';

?>



/Tommy

Uhm? What does that code have to do with mine? :huh: yeah…it prints true or false…so? :( I’m not quite following you…

Did you actually check what’s returned from validate(), before any implicit type conversion? Try assigning the return value to a variable and use print_r() for displaying it.

/Tommy





public function actionRegisterUser(){

		/*

		 * Verifica se o identificador é interno

		 */

		

		

		$regForm = new RegisterUserForm;

		

		if(isset($_POST['RegisterUserForm'])){

			UserController::echoVector($_POST['RegisterUserForm']);

			$regForm->attributes = $_POST['RegisterUserForm'];

			$v = $regForm->validate();

			print_r($v);

		}

		

		$this->render('registerUser',array('model'=>$regForm));

		

	}




Gives me the same result…

here is a visual example

when i insert a valid email, the program writes 1 next to the email, on top.

when i insert an invalid email address, there isn’t anything next to the email!

Implicit type conversion or not, what is the real problem here?

I just checked what’s returned from CModel::validate() in 1.1.2+




return !$this->hasErrors();

or

return false;



/Tommy

the real problem is that if it writes nothing, what is returned? Thaaaat’s the issue! :unsure:

I see that in 1.1.2+, the code is that. But, in my example, the output isn’t 1 and 0…it’s more like 1 and nothing. That’s why i’m asking this. :)




<?php

  echo 'false:>'.(int)false.'<<br/>';

  echo 'true:>'.(int)true.'<<br/>';

?>



Better?

/Tommy

yes…the true value is like i expected but, still, there is the problem about the false int value…That’s just that, nothing more

Still don’t get, what your problem is exactly. What does not work?

If you’re concerned about a “false” expression not being identical to false but 0, null, ‘’, whatever, read this:

http://de.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

To view the value (and type) of a variable, don’t use print_r but use this (to view variable $v):




CVarDumper::dump($v);



this works like the php var_dump() function, only things are printed in a nicer structure.

In your case this will print if the variable is simply null, boolean false, or whatever else it can be.

Thanks for the advice!!!