存储关联表车辆数据时触发Undefined variable $fleet错误
问题:添加车辆时表单验证失败后提示「Undefined variable $fleet」
在向与fleets表存在关联关系的vehicles表存储数据时,点击添加新车辆按钮时无报错,但尝试将数据存入数据库时,触发ErrorException,提示「Undefined variable $fleet」。
视图代码
<div class="col-3"> <label for="fleet_id" class="form-label"> Type </label> <select id="fleet_id" name="fleet_id" required="required" class="form-control"> <option value="" disabled selected>Type</option> <?php foreach ($fleet as $value) : ?> <option value="<?= $value->id ?>"><?= $value->type ?></option> <?php endforeach ?> </select> </div>
控制器代码
public function new() { $data['fleet'] = $this->fleetModel->findAll(); $data['module'] = lang("Localize.fleet") ; $data['title'] = lang("Localize.add_vehicle") ; $data['pageheading'] = lang("Localize.add_vehicle"); echo view($this->Viewpath . '\vehical/new', $data); } public function create() { $imgpath = array(); $imgbus = $this->request->getFileMultiple('busimg'); if (!empty($imgbus)) { foreach ($imgbus as $key => $imgvalue) { if ($imgvalue->isValid() && !$imgvalue->hasMoved()) { $busimag = $this->imgaeCheck($imgvalue); array_push($imgpath, $busimag); } } } $data = array( "fleet_id" => $this->request->getVar('fleet_id'), "reg_no" => $this->request->getVar('reg_no'), // "engine_no" => $this->request->getVar('engine_no'), // "model_no" => $this->request->getVar('model_no'), // "chasis_no" => $this->request->getVar('chasis_no'), "woner" => $this->request->getVar('woner'), "woner_mobile" => $this->request->getVar('woner_mobile'), "company" => $this->request->getVar('company'), "status" => $this->request->getVar('status'), "assign" => $this->request->getVar('assign'), ); if ($this->validation->run($data, 'vehical')) { $vehicleid = $this->vehiclModel->insert($data); if (!empty($imgpath)) { foreach ($imgpath as $key => $imgvalue) { $storedata[$key] = array( "vehicle_id" => $vehicleid, "img_path" => $imgvalue, ); } $this->vImageModel->insertBatch($storedata); } return redirect()->route('index-vehicle')->with("success", "Data Save"); } else { $data['validation'] = $this->validation; $data['module'] = lang("Localize.fleet"); $data['title'] = lang("Localize.add_vehicle"); echo view($this->Viewpath . '\vehical/new', $data); } }
问题原因
问题出在create方法的表单验证失败分支(else块):当表单验证不通过时,你重新渲染了添加车辆的视图,但没有像new方法那样将$fleet数据传入视图。视图中的下拉选择框需要遍历$fleet变量生成选项,变量缺失就会触发「Undefined variable $fleet」错误。
修复方案
在create方法的else块中,添加获取fleet数据的代码,确保渲染视图时包含该变量:
} else { // 新增这一行,获取fleet数据 $data['fleet'] = $this->fleetModel->findAll(); $data['validation'] = $this->validation; $data['module'] = lang("Localize.fleet"); $data['title'] = lang("Localize.add_vehicle"); echo view($this->Viewpath . '\vehical/new', $data); }
这样当验证失败返回表单时,视图就能拿到$fleet变量,下拉框可以正常渲染,错误就会消失。
内容的提问来源于stack exchange,提问作者muhammed alsmawi
相关产品推荐
相关产品推荐

