CActiveForm DropDownList Unselected Item

This question is rather simple but I can’t seem to figure out how to do it. Is there a way to add an item to a CActiveForm DropDown at the beginning and have it selected called something like “Not Selected”? The code listed below is for update which works great. I’d like to have an “Not Selected” for the create view.




<?php

//View 

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

'id'=>'start-end-update-form',

'enableAjaxValidation'=>false,

 )); 

	

echo '<div class="row">';

echo $form->labelEx($model,'user_id');

echo $form->dropDownList($model, 'user_id', TimeSheetController::getUserOptionList());

echo $form->error($model,'user_id');

echo '</div>';

?>


//Controller

<?php

public static function getUserOptionList() {

	$criteria=new CDbCriteria;

	$criteria->select = 'id, user_name'; 

	$criteria->condition = 'user_level<='.Yii::app()->user->user_identity->user_level;

	$criteria->condition = 'company_id='.Yii::app()->user->user_identity->company_id;

	$models = User::model()->findAll($criteria);

	return CHtml::listData($models, 'id', 'user_name');

}

?>



Check whether the following is helpful.

FORM:




<div class="row">

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

		<?php echo $form->dropDownList($model,'username',User::getIdUsername()); ?>

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

	</div>



METHOD IN AR:




public function getIdUsername(){

	$arr=array(0=>'');

	$userObjects=User::model()->findAll(array(

	'condition'=>'status=2'

	));

	foreach($userObjects as $userObject) {

	$arr[$userObject->id]=$userObject->username;

	}

	return $arr;

	}



CONTROLLER:




//Put some logic to avoid $_POST['username[0]']



Seenivasan,

This worked out great and I’m a little embarrassed I didn’t think to assemble the array myself with a leading item. Thank you!

Or just use the ‘prompt’ or ‘empty’ options of $htmlOptions array:


<?php echo $form->dropDownList($model, 'user_id',

                               TimeSheetController::getUserOptionList(),

                               array('prompt' => 'Not selected')); ?>

This is an easier option while allowing CHtml::listData to generate the array for you. Nice one. :)