Search code examples
phpjsonyii2active-form

YII2 Dropdownlist from JSON link


How to populate json data to dropdownlist

this is the json link : http://localhost/data

this the json format :

[{"inst_id":"1","inst_code":"001","inst_name":"HARVARD"},{"inst_id":"2","inst_code":"002","inst_name":"UCLA"}]

this the view :

<?= $form->field($model, 'institusi')->dropDownList(); ?>

the dropdown value from "inst_id" and text from "inst_name"

i have the code but it isn't Active form

$url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $inst=array();
        echo "<select>";
        foreach($json as $item) {

            echo "<option value='".$item['inst_id']."'>".$item['inst_name']."</option>";

        }
        echo "</select>";

so how to populate the json data into Activeform Dropdownlist


Solution

  • The easiest way would be to prepare the array for dropDownList just before it

    <?php
            $url = 'http://localhost/data';
            $content = file_get_contents($url);
            $json = json_decode($content, true);
            $instArray = ArrayHelper::map($json,'inst_id','inst_name');
            echo $form->field($model, 'institusi')->dropDownList($instArray);
    ?>
    

    You could also prepare the the same array from controller and pass it to view from render method.

    Other options would be to create a component or add a static method to the model. Both should return the array format of your json data.