0

I'm trying to create a dropdown select list in Yii2 but am finding the documentation for it a bit confusing considering there are no examples.

Could someone attempt to explain it a bit better with some examples, like if I wanted to create a dropdown list like the below how would I do it?

Sample:

<select name="foo" id="bar" onchange="run()">
    <option value="">Select Pet Type</option>
    <option value="fish">Fish</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="lizard">Lizard</option>
</select>

3 Answers 3

1

You could simply try this :

<?= Html::dropDownList('foo', null, [
    'fish' => 'Fish',
    'dog' => 'Dog',
], ['id' => 'bar', 'prompt'=>'Select Pet Type', 'onchange' => 'run()']) ?>

Or with a form and model :

<?= $form->field($model, 'attribute')->dropDownList([
    'fish' => 'Fish',
    'dog' => 'Dog',
], ['id' => 'bar', 'prompt'=>'Select Pet Type', 'onchange' => 'run()']) ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I just got a bit confused with what went where with regards to the items and options parts as I didn't find it very clear.
0

You can also check this, it will run.

<?php $dataList = Array('fish' => "Fish", 'dog' => "Dog", 'cat' => "Cat", 'lizard' => "Lizard"); ?>
<?php echo Html::dropDownList('foo', null, $dataList, [
    'class' => 'form-control',
    'id' => 'bar',
    'prompt' => 'Select Pet Type',
    'onchange' => 'run()'
]); ?>

Comments

0

You can go with the model as it will be helpful for you to assign the values and perform validations and other useful functions like beforeSave or beforeValidate using model. So following code will work for you.

           <?php
           echo $form->field($model, 'foo')
                ->dropDownList(
                    ['fish' => 'Fish', 'dog' => 'Dog', 'cat' => 'Cat', 'lizard' => 'Lizard'],
                    ['prompt' => 'Select Pet Type', 'id' => 'bar']
                );
            ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.