为什么我的数据 table 在我的模态表单中出现验证错误时无法加载?

why does my data table fail to load when i have validation error in my modal form?

我有一个视图用户,其中包含模态表单和从用户 table 填充的数据 table。我通过按钮访问模态表单。我在代码点火器 4 中进行了一些验证。当我在模式中正确输入所有字段时,数据将发送到数据库,但如果我省略一个字段,在重定向时,我会收到错误 [ErrorException 为用户提供的 foreach() 参数无效] 请帮助。

我的控制器代码 ...

<?php
namespace App\Controllers;
use App\Models\userModel;
class UserController extends BaseController{
    public function getData(){
      $model=new userModel();
      $data['userData']=$model->findAll();
      return view('admin_template/users',$data);
    }
    public function insertUser(){
        helper(['url']);
        if($this->request->getMethod()==='post'){
            $modeluser=new userModel();
            $session=session(); //load session service
            $data=[
                "userName"=>$this->request->getVar("userName"),
                "email"=>$this->request->getVar("email"),
                "slocation"=>$this->request->getVar("slocation"),
                "designation"=>$this->request->getVar("designation"),
                "pwd"=>$this->request->getVar("pwd"),
                "cpwd"=>$this->request->getVar("cpwd")
            ];
            $validationRules=[
                'userName'=>'required|min_length[5]|max_length[100]',
                'email'=>'required|valid_email|is_unique[users.email]',
                'slocation'=>'required',
                'designation'=>'required',
                'pwd'=>'required|min_length[5]|alpha_numeric',
                'cpwd'=>'required|matches[pwd]'
            ];
            $modeluser->setValidationRules($validationRules);
            $fieldValidationMessage=[
                'username'=>[
                    'required'=>'Name is required',
                    'min_length'=>'minimum length of name should be 5 chars',
                    'max_length'=>'maximum length of name should be 5 chars'
                ],
                'email'=>[
                    'required'=>'Email is required',
                    'valid_email'=>'Enter a valid email',
                    'is_unique'=>'Email already exists'
                ],
                'slocation'=>[
                    'required'=>'Location not selected',
                ],
                'designation'=>[
                    'required'=>'Designation not selected',
                ],
                'pwd'=>[
                    'required'=>'Password cannot be empty',
                    'min_length'=>'minimum length of password should be 5 chars',
                    'alpha_numeric'=>'password should contain alpha-numeric characters'
                ],
                'cpwd'=> [
                    'required'=>'Confirm password cannot be empty',
                    'matches'=>' Confirm password does not match'
                ]
            ];
            $modeluser->setValidationMessages($fieldValidationMessage);
            if($modeluser->save($data)===false){
                return view('admin_template/users',[
                    'errors'=>$modeluser->errors()
                ]);
            } else{
                $session->setFlashdata("success","User added successfully");
                return redirect()->to(base_url('user'));
            }
        }

       return view('admin_template/users');
    }
}

我的查看代码

<?php

use Config\Services;

?>

<?= $this->extend('admin_template/index') ?>
    <!-- Begin Page Content -->
   <?= $this->section('content') ?>

    <!-- Modal-->
<div class="card">
    <div class="card-body">
        <?php
        // to print success message
        if(session()->get("success")){
            ?>
            <div class="alert alert-success">
                <?= session()->get("success") ?>
            </div>
        <?php } ?>
        <?php if(!empty($errors)) : ?>
            <div class="alert alert-danger">
                <?php foreach ($errors as $field=>$error):?>
                    <p><?= $error?></p>
                <?php endforeach ?>
            </div>
        <?php endif ?>
    </div>
</div>
 
    <div class="modal fade" id="addUserProfile" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Add User</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
    
    
                    <form  action="<?= base_url('user')?>" method="post">
                         <?=csrf_field()?>
                        <div class="modal-body">
                            <div class="form-group" >
                                <label class="col-form-label">User Name </label>
                                <input type="text"  class="form-control" name="userName" placeholder="Enter Users full name">
                            </div>
                            <div class="form-group">
                                <label class="col-form-label">Email</label>
                                <input type="email" class="form-control" name="email" placeholder="Enter Users email">
                            </div>
                            <div class="form-group ">
                                <label class="col-form-label">Location</label>
                                <select  class="custom-select my-1 mr-2" name="slocation" >
                                    <option selected>Choose Location</option>
                                    <option Value="Mombasa" >Mombasa</option>
                                    <option value="Emali">Emali</option>
                                    <option Value="Mlolongo">Mlolongo</option>
                                    <option Value="Nairobi">Nairobi</option>
                                    <option value="Mai Mahiu">Mai mahiu</option>
                                    <option value="Salgaa">Salgaa</option>
                                    <option value="Eldoret">Eldoret</option>
                                    <option value="Malaba">Malaba</option>
                                </select>
    
                            </div>
                            <div class="form-group">
                                <label class="col-form-label">Designation</label>
                                <select class="custom-select my-1 mr-2" name="designation">
                                    <option selected>Choose Designation</option>
                                    <option value="Admin">Admin</option>
                                    <option value="Technical Support">Technical Support</option>
                                    <option value="Installer">Installer</option>
                                    <option value="Controller">Controller</option>
                                </select>
    
                            </div>
                            <div class="form-group">
                                <label class="col-form-label">Password</label>
                                <input type="password" class="form-control" name="pwd" placeholder="Enter Password" >
    
                            </div>
                            <div class="form-group">
                                <label >Confirm Password</label>
                                <input type="password" class="form-control" name="cpwd" placeholder="Confirm Password">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary"> Save </button>
                        </div>
                </form>
            </div>
    
                </div>
            </div>
    
    
    
        <div class="container-fluid">
            <!-- DataTales Example -->
    
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">User Profile
                        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addUserProfile">
                            Add User
                        </button>
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="dataTable" >
                            <thead>
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Location</th>
                                <th>Designation</th>
                                <th>Created At</th>
                            </tr>
                            </thead>
                            <tbody>
    
                           <?php
                           foreach ($userData as $item):?>
                            <tr>
                                <td><?php echo $item['userid']?></td>
                                <td><?php echo $item['userName']?></td>
                                <td><?php echo $item['email']?></td>
                                <td><?php echo $item['slocation']?></td>
                                <td><?php echo $item['designation']?></td>
                                <td><?php echo $item['created_at']?></td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
    
                </div>
            </div>
    
        </div>
    
    
    <?= $this->endSection() ?>

[错误]

我通过将我的数据传递给 returns 验证错误到视图的方法解决了这个问题。

$modeluser->setValidationMessages($fieldValidationMessage);

$userdata = $this->getData();// called the method to get userdata.
if($modeluser->save($data)===false){
   return view('admin_template/users',[$userdata,
        'errors'=>$modeluser->errors() // Passed userdata to the view. 
   ]);
} else {
    $session->setFlashdata("success","User added successfully");
    return redirect()->to(base_url('user'));
}

return view('admin_template/users');