How To How To Validate Dropdownlist With The Value From Database

Hi, I am new to Yii Framework and I need to use it for my current project.

In my login form, I have a dropdownlist of ‘User Type’ , textfield of ‘Username’ and textfield of ‘Password’.

I have successfully to validate the user input of username and password with the value of database.

My problem is I cant validate the dropdownlist that has been selected by user with the value of database.

Can anyone help me?? I really have no idea how to solve it~ Please help me…

My database looks like this:

id | user_type | username | password

1 | admin | test1 | pass1

color="#FF0000":[/color]

class User extends CActiveRecord

{

public function tableName()


{


	return 'user';


}

public function rules()

{


	return array(


		array('user_type, username, password, email', 'required'),


		array('user_type', 'length', 'max'=>20),


		array('username, password, email', 'length', 'max'=>128),


		array('id, user_type, username, password, email', 'safe', 'on'=>'search'),


	);


}

public function relations()

{


	return array(


	);


}





public function attributeLabels()


{


	return array(


		'id' => 'ID',


		'user_type' => 'User Type',


		'username' => 'Username',


		'password' => 'Password',


		'email' => 'Email',


	);


}





public function search()


{


	// @todo Please modify the following code to remove attributes that should not be searched.





	$criteria=new CDbCriteria;





	$criteria->compare('id',$this->id);


	$criteria->compare('user_type',$this->user_type,true);


	$criteria->compare('username',$this->username,true);


	$criteria->compare('password',$this->password,true);


	$criteria->compare('email',$this->email,true);





	return new CActiveDataProvider($this, array(


		'criteria'=>$criteria,


	));


}





public static function model($className=__CLASS__)


{


	return parent::model($className);


}

}

color="#FF0000":[/color]

class LoginForm extends CFormModel

{

public $user_type;


public $username;


public $password;


public $rememberMe;





private $_identity;


public function rules()


{


	return array(


		// username and password are required


		array('user_type, username, password', 'required'),


		// rememberMe needs to be a boolean


		array('rememberMe', 'boolean'),


		// password needs to be authenticated


		array('password', 'authenticate'),


	);


}





public function attributeLabels()


{


	return array(


		'rememberMe'=>'Remember me next time',


	);


}





public function authenticate($attribute,$params)


{


	


	if(!$this->hasErrors())


	{


		$this->_identity=new UserIdentity($this->username,$this->password);


		if(!$this->_identity->authenticate())


			$this->addError('password','Incorrect username or password.');


	}


}





public function login()


{


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


	{


		$this->_identity=new UserIdentity($this->user_type,$this->username,$this->password);


		$this->_identity->authenticate();


	}


	if($this->_identity->errorCode===UserIdentity::ERROR_NONE)


	{


		$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days


		Yii::app()->user->login($this->_identity,$duration);


		return true;


	}


	else


		return false;


}

}

color="#FF0000"[/color]:

class UserIdentity extends CUserIdentity

{

public function authenticate()


{


    $record1=User::model()->findByAttributes(array('user_type'=>$this->user_type));


    if($record1=='admin') // This is front login


    {


        // check if login details exists in database


        $record=User::model()->findByAttributes(array('username'=>$this->username)); 


		if($record===null)


        { 


            $this->errorCode=self::ERROR_USERNAME_INVALID;


        }


        else if($record->password!==$this->password)      // here I compare db password with password field


        { 


            $this->errorCode=self::ERROR_PASSWORD_INVALID;


        }


        else


        {  


            $this->errorCode=self::ERROR_NONE;


        }


        return !$this->errorCode;


    }

color="#FF0000":[/color]

public function actionLogin()

{


    


	$model=new LoginForm;





	// if it is ajax validation request


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


	{


		echo CActiveForm::validate($model);


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


	}





	// collect user input data


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


	{


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


		// validate user input and redirect to the previous page if valid


		if($model->validate() && $model->login())


			$this->redirect(Yii::app()->user->returnUrl);


	}


	// display the login form


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


}





public function actionLogout()


{


	Yii::app()->user->logout();


	$this->redirect(Yii::app()->homeUrl);


}

color="#FF0000":[/color]

<div class="row">

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'user_type'); ?&gt;


	&lt;?php echo &#036;form-&gt;dropdownList(&#036;model,'user_type', 


	CHtml::listData(User::model()-&gt;findAll(), 'id', 'user_type'), array('prompt'=&gt;'---Please Select---'));?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'user_type'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'username'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'username'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'username'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'password'); ?&gt;


	&lt;?php echo &#036;form-&gt;passwordField(&#036;model,'password'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'password'); ?&gt; 

eventually, it returns error :

CException

Property "UserIdentity.user_type" is not defined.

Please help me~~~~ thanks in advance…

UserIdentity extends CUserIdentity, but CUserIdentity do not have user_type.

So you need add add public user_type for UserIdentity.




class UserIdentity extends CUserIdentity

{ 

	/**

	* @var string user_type

	*/

	public $user_type;


	public function __construct($user_type;$username,$password)

	{

	$this->user_type=$user_type;	

	$this->username=$username;

	$this->password=$password;

	}



Hi Johnny Gan,first of all thanks for your reply and help. It works well to me after I add the public user_type for UserIdentity.

But the dropdownlist of ‘User Type’ still can’t be validated.

My database:

id |user_type| username| password

1 |admin | test1 | pass1

2 |lecturer | test2 | pass2

So, when I select ‘lecturer’ from the dropdownlist and input username: test1 and password:pass1, the user can login into the system. It is suppose to return an error because the user should select ‘admin’ instead of ‘lecturer’.

Please help me…

Check your code logic in authenticate function below. When you verify the user, you need combine user_type, username and password together, not just one after one.




public function authenticate()

{

$record1=User::model()->findByAttributes(array('user_type'=>$this->user_type));

if($record1=='admin') // This is front login

{

// check if login details exists in database

$record=User::model()->findByAttributes(array('username'=>$this->username));

if($record===null)

{

$this->errorCode=self::ERROR_USERNAME_INVALID;

}

else if($record->password!==$this->password) // here I compare db password with password field

{

$this->errorCode=self::ERROR_PASSWORD_INVALID;

}

else

{

$this->errorCode=self::ERROR_NONE;

}

return !$this->errorCode;

}