Displaying all database records in a dropdown in Yii

I will show you how to display all database records of a certain table in a dropdownlist in Yii.

Model Code:

class UserType extends CActiveRecord {
     public function GetUserType(){
	$command= $connection->createCommand("SELECT * FROM ".$this->tableName());
	$rows = $command->queryAll(); 
	return CHtml::listData($rows,'id', 'type');

View Code:

echo $form->dropDownList($model,'user_type_id',UserType::model()->GetUserType());

The CHTML::listData() takes 3 parameters.
1st is the result of the row of your sql
2nd parameter is the value of your option. So it’s something like this <option value=”value here“>
3rd parameter is the value between <option>value here</option>

Yii Date validation in rules

Here’s how to specify a date validation rules in the Model.

The idea here is that “Date To” should always be greater than “Date From”. Here’s how to do that

public function rules()
   return array(
	array( 'date_to','compare','compareAttribute' => 'date_from','operator'=>'>', 'allowEmpty'=>'false', 'message' => '{attribute} should be greater than "{compareValue}".'),

Piece of cake eh?

Have a happy coding! :)