2017-07-04 51 views
0

如何填充JSON數據下拉列表YII2 DROPDOWNLIST從JSON鏈接

這是JSON鏈接:http://localhost/data

這個JSON格式:

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

這一觀點:

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

「inst_id」的下拉值和「inst_name」的文本

我的代碼,但它不是主動形式

$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>"; 

所以如何將JSON數據填充到的ActiveForm DROPDOWNLIST

回答

0

最簡單的方法是將之前它準備下拉列表數組

<?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); 
?> 

你也可以從控制器準備相同的數組,並將它傳遞從render方法來查看。

其他選項將創建一個組件或向模型添加靜態方法。兩者都應該返回你的json數據的數組格式。

+0

非常感謝。它工作,你拯救了我的生命 –