yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.91k forks source link

about dropDownList selection #3337

Closed djfly closed 10 years ago

djfly commented 10 years ago

general:

<?= $form->field($model, 'parent')->dropDownList($items) ?>

Practical work:

<div class="form-group field-category-parent">
<?= Html::activeLabel($model, 'parent') ?>
<?= Html::dropDownList('Category[parent]', $parent->id, $items, ['id'=>'category-parent', 'class' => "form-control"]) ?>
<?= Html::error($model, 'parent' ) ?>
</div>

I think this should be better

<?= $form->field($model, 'parent')->dropDownList($items, ['value' => $parent->id]) ?>

Some people experience the same confusion it?

samdark commented 10 years ago

What's the problem exactly?

djfly commented 10 years ago

selected does not depend on model, we can manually set

In my case, $ model-> parent has a value, but I do not want it to display this value, I need to set another value

this is my proposal

<?= $form->field($model, 'parent')->dropDownList($items, ['value' => $parent->id]) ?>
cebe commented 10 years ago

does Category model has a parent_id and is parent the relation?

djfly commented 10 years ago

not relation ,just set a selected value for select

<select id="category-parent" class="form-control" name="Category[parent]">
<option value="34">one</option>
<option value="35">two</option>
<option value="35" selected="">three</option>
</select>

I mean, this function should be added a argument for set selected value https://github.com/yiisoft/yii2/blob/master/framework/widgets/ActiveField.php line 517

public function dropDownList($items, $options = [])
    {
...

one solution is

public function dropDownList($items,$selection)

Another solution is

public function dropDownList($items, ['options' => ['value => xxx]]) ?>
cebe commented 10 years ago

you can do it like this, there is no need for this option:

<?php
$model->parent = $parent->id;
echo $form->field($model, 'parent')->dropDownList($items);
?>