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

Time:02-20

I have a view users where I have included both a modal form and a data table which populates from users table. I access the modal form via button. I have some validation in code igniter 4. When i enter all the fields correctly in the modal, the data is sent to the db but if i omit one field, upon redirection, I get an error [ErrorException Invalid argument supplied for foreach() on the users ] kindly help.

My Controller code ...

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

My View Code

<?php

use Config\Services;

?>

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

    <!-- Modal-->
<div >
    <div >
        <?php
        // to print success message
        if(session()->get("success")){
            ?>
            <div >
                <?= session()->get("success") ?>
            </div>
        <?php } ?>
        <?php if(!empty($errors)) : ?>
            <div >
                <?php foreach ($errors as $field=>$error):?>
                    <p><?= $error?></p>
                <?php endforeach ?>
            </div>
        <?php endif ?>
    </div>
</div>
 
    <div  id="addUserProfile" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div >
                <div >
                    <div >
                        <h5  id="exampleModalLabel">Add User</h5>
                        <button type="button"  data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
    
    
                    <form  action="<?= base_url('user')?>" method="post">
                         <?=csrf_field()?>
                        <div >
                            <div  >
                                <label >User Name </label>
                                <input type="text"   name="userName" placeholder="Enter Users full name">
                            </div>
                            <div >
                                <label >Email</label>
                                <input type="email"  name="email" placeholder="Enter Users email">
                            </div>
                            <div >
                                <label >Location</label>
                                <select   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 >
                                <label >Designation</label>
                                <select  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 >
                                <label >Password</label>
                                <input type="password"  name="pwd" placeholder="Enter Password" >
    
                            </div>
                            <div >
                                <label >Confirm Password</label>
                                <input type="password"  name="cpwd" placeholder="Confirm Password">
                            </div>
                        </div>
                        <div >
                            <button type="button"  data-dismiss="modal">Close</button>
                            <button type="submit" > Save </button>
                        </div>
                </form>
            </div>
    
                </div>
            </div>
    
    
    
        <div >
            <!-- DataTales Example -->
    
            <div >
                <div >
                    <h6 >User Profile
                        <button type="button"  data-toggle="modal" data-target="#addUserProfile">
                            Add User
                        </button>
                    </h6>
                </div>
                <div >
                    <div >
                        <table  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() ?>

[The error]

CodePudding user response:

I solved the issue by passing my data to the method that returns validation errors to the view.

$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');
  • Related