How to make the Yii-CActiveForm not set a list item to selected?

176 Views Asked by At

In a Yii application I have models User and Expert ('expert'=>array(self::BELONGS_TO, 'Expert', 'expert_id'),).

There is a form for creating/editing user data. Now I want to extend it with a drop-down list:

<?php
/**
 * @var $experts Expert[]
 */ 
$expertsDropDownListData = array();
foreach ($experts as $expert) {
    $expertsDropDownListData[$expert->id] = $expert->name;
}
?>
<div class="row">
    <?php
    echo $form->labelEx($user, '', array('label' => Yii::t('app', 'Some text...')));
    ?>
    <?php
    echo $form->dropDownList(
        $user, 'expert[id]', $expertsDropDownListData,
        array(
            'empty' => Yii::t('app', 'Please select an expert.'),
            // 'options' => array('' => array('selected' => 'selected')),
            // 'prompt'=>'Choose One',
        )
    );
    ?>
    <?php echo $form->error($user, 'expert[id]'); ?>
</div>

I want the drop-down list never to have an expert entry as ould default entry. On page load alwys the empty value should be "selected". It works on pages of users, that don't have a related expert (in the users table the columnt expert_id is NULL). But on the pages of the user, that have an expert, the expert entry of the user gets selected.

How to permit the CActiveForm object selecting an antry and display a form without preselected value irrespective of the tables/objects relationships?

1

There are 1 best solutions below

1
On

You can fill the attribute $model->expert with null after load.

// Controller
$user = User::model()->findByPk(1);
...your awesome code here...

// never show a default value
$user->expert=null;

if(isset($_POST)) {
  // $user->expert will be set here with data from view
  $user->attributes = $_POST;
}

...

// View
    <div class="row">
    <?php
    echo $form->labelEx($user, '', array('label' => Yii::t('app', 'Some text...')));
    ?>
    <?php
    echo $form->dropDownList(
        $user, 'expert', CHtml::listData($experts,'id', 'name'),
        array('empty' => Yii::t('app', 'Please select an expert.'),)
    );
    ?>
    <?php echo $form->error($user, 'expert'); ?>
    </div>