API调用移至Controller后视图国家下拉框无法加载问题排查
问题解决步骤
核心原因
你把API请求移到Controller后,create.php渲染_form.php时没有将$countries变量传递给子视图,导致_form.php里的$countries未定义,触发了No countries found的分支。
解决方案
1. 修改create.php,传递变量给子视图
确保create.php在渲染_form.php时,把Controller传来的$countries(或处理后的列表)一并传递:
<?php // create.php中的渲染代码 echo $this->render('_form', [ 'model' => $model, 'countries' => $countries, // 新增此行,传递国家数据 ]); ?>
2. 清理_form.php,移除冗余代码
删除_form.php中原有的API请求代码,直接使用传递过来的$countries变量:
<div class="card styled-card"> <div class="card-body"> <div class="people-form"> <?php $form = ActiveForm::begin(); ?> <!-- 其他表单字段代码 --> <?php if (!empty($countries)): $countryList = []; foreach ($countries as $country) { if (isset($country['name']['common'])) { $countryList[] = $country['name']['common']; } } asort($countryList); ?> <?= $form->field($model, 'nation')->dropDownList( array_combine($countryList, $countryList), ['prompt' => 'Select a Country'] )->label('Nation') ?> <?php else: ?> <p>No countries found.</p> <?php endif; ?> <!-- 提交按钮代码 --> <?php ActiveForm::end(); ?> </div> </div> </div>
优化建议(可选,更符合MVC规范)
可以直接在Controller中处理国家列表的格式化和排序,减少视图层的逻辑:
修改后的actionCreate方法
public function actionCreate() { $model = new People(); // 调用API获取国家数据 $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://restcountries.com/v3.1/all?fields=name', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', )); $response = curl_exec($curl); curl_close($curl); $countries = json_decode($response, true); // 提前处理国家列表 $countryList = []; if (!empty($countries)) { foreach ($countries as $country) { if (isset($country['name']['common'])) { $countryList[] = $country['name']['common']; } } asort($countryList); } // 表单提交逻辑 if ($this->request->isPost) { if ($model->load($this->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } } else { $model->loadDefaultValues(); } // 传递处理后的列表给视图 return $this->render('create', [ 'model' => $model, 'countryList' => $countryList, ]); }
对应的create.php传递代码
<?php echo $this->render('_form', [ 'model' => $model, 'countryList' => $countryList, ]); ?>
简化后的_form.php国家选择部分
<?php if (!empty($countryList)): ?> <?= $form->field($model, 'nation')->dropDownList( array_combine($countryList, $countryList), ['prompt' => 'Select a Country'] )->label('Nation') ?> <?php else: ?> <p>No countries found.</p> <?php endif; ?>
内容的提问来源于stack exchange,提问作者chickenzz
相关产品推荐
相关产品推荐

