Search code examples
javascriptjqueryajaxbootstrap-5codeigniter-4

CodeIgniter 4 No Response on Route if Different Value is Used


I am doing a self study on Code Igniter 4. What I want to do is to insert records regardless of transaction. So I have parameters Add, Edit and Delete. When Add is the value passed, it will insert a record. But when Edit is the value passed, It does not respond.

Below is my Model code:

<?php

namespace App\Models;

use CodeIgniter\Model;

class OfficeModel extends Model
{

    protected $table = 'officeinfo';
    protected $primaryKey = 'recordno';
    protected $allowedFields = [
      'companycode',
      'branchcode',
      'name',
      'shortname',
      'address',
      'ratedistributioncode',
      'transactby',
      'transacttype'
    ];
  
    public function countRec()
    {
      $db = db_connect();

      $table = $db->table($this->table);
      return $table->countAllResults();
    }

}

Below is my View code:

<!doctype html>
<html lang="en">
    <head>
        <?php echo view('head'); ?>
        <title>HRIS: Office</title>
    </head>
    <body>
        <div id="mytask-layout" class="theme-indigo">

            <?php echo view('sidebar'); ?>
            <?php //echo ($data);?>

            <!-- main body area -->
            <div class="main px-lg-4 px-md-4">
                <?php if(session()->getFlashdata('msg')):?>
                <div class="alert alert-info">
                    <?= session()->getFlashdata('msg') ?>
                </div>
                <?php endif;?>
                <?php echo view('body-header'); ?>

                <!-- Body: Body -->
                <div class="body d-flex py-lg-3 py-md-2">
                    <div class="container-xxl">
                        <div class="row align-items-center">
                            <div class="border-0 mb-4">
                                <div
                                    class="card-header py-3 no-bg bg-transparent d-flex align-items-center px-0 justify-content-between border-bottom flex-wrap">
                                    <h3 class="fw-bold mb-0">Offices</h3>
                                    <div class="col-auto d-flex w-sm-100">
                                        <button
                                            type="button"
                                            class="btn btn-dark btn-set-task w-sm-100"
                                            data-bs-toggle="modal"
                                            data-bs-target="#officeadd">
                                            <i class="icofont-plus-circle me-2 fs-6"></i>Add Office</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Row end -->
                        <div class="row clearfix g-3">
                            <div class="col-sm-12">
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <table
                                            id="officeTable"
                                            class="table table-hover align-middle mb-0"
                                            style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Name</th>
                                                    <th>Address</th>
                                                    <th>Active Employees</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                    $ctr = 0;
                                                    foreach ($offices as $office) {
                                                ?>
                                                    <tr>
                                                        <td>
                                                            <span class="fw-bold"><?php echo ++$ctr; ?></span>
                                                        </td>
                                                        <td>
                                                            <img class="avatar rounded-circle" src="<?= base_url() ?>/public/assets/images/xs/avatar1.jpg" alt="">
                                                            <span class="fw-bold ms-1"><?php echo $office['name']; ?></span>
                                                        </td>
                                                        <td>
                                                            <?php echo $office['address']; ?>
                                                        </td>
                                                        <td>
                                                            40
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group" aria-label="Basic outlined example">
                                                                <button
                                                                    type="button"
                                                                    id="officeEdit-<?php echo $office['recordno']; ?>"
                                                                    class="btn btn-outline-secondary editrow"
                                                                    data-bs-toggle="modal"
                                                                    data-bs-target="#depedit">
                                                                    <i class="icofont-edit text-success"></i>
                                                                </button>
                                                                <button type="button" id="officeDelete-<?php echo $office['recordno']; ?>" class="btn btn-outline-secondary deleterow">
                                                                    <i class="icofont-ui-delete text-danger"></i>
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Row End -->
                    </div>
                </div>

                <!-- Modal Members-->
                <?php echo view('modalmembers'); ?>
                
                <!-- Add Office-->
                <div class="modal fade" id="officeadd" tabindex="-1" aria-hidden="true">
                    <div
                        class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                        <div class="modal-content">
                            <form
                                method="post"
                                id="office_add"
                                name="office_add"
                                action="<?= site_url('/office-save/Add') ?>">
                                <div class="modal-header">
                                    <h5 class="modal-title  fw-bold" id="officeaddLabel">
                                        Add Office</h5>
                                    <button
                                        type="button"
                                        class="btn-close"
                                        data-bs-dismiss="modal"
                                        aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label class="form-label">Office Type</label>
                                            <br/>
                                            <label class="fancy-radio">
                                                <input
                                                    id="officemain"
                                                    type="radio"
                                                    name="officetype"
                                                    value="main"
                                                    required="required"
                                                    data-parsley-errors-container="#error-radio">
                                                <span>
                                                    <i></i>Main</span>
                                            </label>
                                            &nbsp;&nbsp;&nbsp;&nbsp;
                                            <label class="fancy-radio">
                                                <input
                                                    id="officebranch"
                                                    type="radio"
                                                    name="officetype"
                                                    value="branch">
                                                <span>
                                                    <i></i>Branch</span>
                                            </label>
                                            &nbsp;&nbsp;&nbsp;&nbsp;
                                            <label class="fancy-radio">
                                                <input
                                                    id="officeclinic"
                                                    type="radio"
                                                    name="officetype"
                                                    value="clinic">
                                                <span>
                                                    <i></i>Clinic</span>
                                            </label>
                                            <p id="error-radio"></p>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="officename" class="form-label">Office Name</label>
                                        <input type="text" class="form-control" id="officename" name="officename">
                                    </div>
                                    <div class="mb-3">
                                        <label for="officeshortname" class="form-label">Short Name</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            id="officeshortname"
                                            name="officeshortname">
                                    </div>
                                    <div class="mb-3">
                                        <label for="officeaddress" class="form-label">Address</label>
                                        <textarea
                                            type="text"
                                            class="form-control"
                                            id="officeaddress"
                                            name="officeaddress"></textarea>
                                    </div>
                                    <!--<div class="deadline-form"> <form> <div class="row g-3 mb-3"> <div
                                    class="col-sm-6"> <label for="depone" class="form-label">Department Head</label>
                                    <input type="text" class="form-control" id="depone"> </div> <div
                                    class="col-sm-6"> <label for="deptwo" class="form-label">Employee
                                    UnderWork</label> <input type="text" class="form-control" id="deptwo"> </div>
                                    </div> </form> </div>-->
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary">Add</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Edit Office-->
                <div class="modal fade" id="depedit" tabindex="-1" aria-hidden="true">
                    <div
                        class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                        <div class="modal-content">
                            <form
                                method="post"
                                id="office_edit"
                                name="office_edit"
                                action="<?= site_url('/office-save/Edit') ?>">
                                <div class="modal-header">
                                    <h5 class="modal-title  fw-bold" id="depeditLabel">Edit Office</h5>
                                    <button
                                        type="button"
                                        class="btn-close"
                                        data-bs-dismiss="modal"
                                        aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                <input type="hidden" class="form-control" id="erecordno" name="erecordno">
                                <input type="hidden" class="form-control" id="ebranchcode" name="ebranchcode">
                                    <div class="mb-3">
                                        <label for="eofficename" class="form-label">Office Name</label>
                                        <input type="text" class="form-control" id="eofficename" name="eofficename">
                                    </div>
                                    <div class="mb-3">
                                        <label for="eofficesname" class="form-label">Short Name</label>
                                        <input type="text" class="form-control" id="eofficesname" name="eofficesname">
                                    </div>
                                    <div class="mb-3">
                                        <label for="eofficeaddress" class="form-label">Address</label>
                                        <textarea type="text" class="form-control" id="eofficeaddress" name="eofficeaddress"></textarea>
                                    </div>
                                    <div class="deadline-form">
                                        <form>
                                            <div class="row g-3 mb-3">
                                                <div class="col-sm-6">
                                                    <!--<label class="form-label">Department Head</label> <select
                                                    class="form-select"> <option selected>Joan Dyer</option> <option value="1">Ryan
                                                    Randall</option> <option value="2">Phil Glover</option> <option value="3">Victor
                                                    Rampling</option> <option value="4">Sally Graham</option> </select>-->
                                                    <!--<label for="ratedistributioncode" class="form-label">Rate
                                                    Distribution</label> <input class="form-control" list="datalistOptions"
                                                    id="ratedistributioncode" placeholder="Type to search..."> <datalist
                                                    id="datalistOptions"> <option value="1 | NCR Rate"> <option value="2 | Cebu
                                                    Rate"> <option value="3 | Contractual Rate"> <option value="4 | Sample Rate">
                                                    </datalist>-->
                                                </div>
                                                <!--<div class="col-sm-6"> <label for="deptwo48" class="form-label">Employee
                                                UnderWork</label> <input type="text" class="form-control" id="deptwo48"
                                                value="40"> </div>-->
                                            </div>
                                        </form>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary">Save</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Jquery Core Js -->
        <script src="<?= base_url() ?>/public/assets/bundles/libscripts.bundle.js"></script>

        <!-- Plugin Js-->
        <script src="<?= base_url() ?>/public/assets/bundles/dataTables.bundle.js"></script>

        <!-- Jquery Page Js -->
        <script src="<?= base_url() ?>/public/assets/js/template.js"></script>
        <script>
            // Sample alert function alert() { var myText = "This can be whatever text you
            // like!"; alert (myText); } project data table
            $(document).ready(function () {
                $('#officeTable')
                    .addClass('nowrap')
                    .dataTable({
                        responsive: true,
                        columnDefs: [
                            {
                                targets: [
                                    -1, -3
                                ],
                                className: 'dt-body-right'
                            }
                        ]
                    });
                $('.deleterow').on('click', function () {
                    var tablename = $(this)
                        .closest('table')
                        .DataTable();
                    tablename
                        .row($(this).parents('tr'))
                        .remove()
                        .draw();
                });
                //Set default value for Office Type
                var cnt = "<?php echo $cntOffice; ?>";
                if (cnt == 0){
                    $('#officebranch').attr( 'disabled', "disabled" );
                    $('#officeclinic').attr( 'disabled', "disabled" );
                    $('#officemain').prop( "checked", true );
                } else {
                    $('#officemain').attr( 'disabled', "disabled" );
                    $('#officebranch').prop( "checked", true );
                }
                //Get Office record and pass it to edit modal
                $(document).on('click','.editrow', function(){
                    var officeRecNo = $(this).attr('id').split('-').pop();
                    //alert(officeRecNo);
                    $.ajax({
                        method: "POST",
                        url: "<?= site_url('/getOffice') ?>",
                        data: {
                            'recordno': officeRecNo
                        },
                        success: function (response) {
                            //console.log(response);
                            $.each(response, function(key, officeVal) {
                                $('#erecordno').val(officeVal['recordno']);
                                $('#ebranchcode').val(officeVal['branchcode']);
                                $('#eofficename').val(officeVal['name']);
                                $('#eofficesname').val(officeVal['shortname']);
                                $('#eofficeaddress').val(officeVal['address']);
                                //$('#office_edit').attr('action', 'https://hris.tst/index.php/office-save/Edit/'+officeVal['recordno']);
                            });
                        }
                    });
                });
            });
        </script>
    </body>
</html>

Below is my Controller code:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\OfficeModel;
use App\Models\CommonModel;

class OfficeController extends Controller
{
    public function index()
    {
        $officeModel = new OfficeModel();
        //$commonModel = new CommonModel();

        $session = session();

        $data = [
            //'qry' => $commonModel->generateCode('officeinfo', 'branchcode'),
            'cntOffice' => $officeModel->countRec(),
            'offices' => $officeModel->orderBy('recordno', 'ASC')->findAll(),
        ];

        echo view('office', $data);
    }

    public function save($txnType = null, $id = null)
    {
        $date = date("m/d/Y H:i:s");
        file_put_contents('form_data.log', print_r($txnType.' '.$date.PHP_EOL, true), FILE_APPEND);
        try {
            $officeModel = new OfficeModel();
            $commonModel = new CommonModel();
            
            $companyCode = '001'; //This will be used for all branches since there is only one main office.
            file_put_contents('form_data.log', print_r('Before If Condition '.$txnType.' '.$date.PHP_EOL, true), FILE_APPEND);
            if ($txnType == 'Add') {
                /*
                Add mode:
                */
                file_put_contents('form_data.log', print_r('Add Condition '.$txnType.' '.$date.PHP_EOL, true), FILE_APPEND);

                if ($officeModel->countRec() == 0) {
                    /*
                    No records yet, meaning a main office must be created.
                    Branch code must be null.
                    */
                    $branchCode = null;
                } elseif ($officeModel->countRec() >= 1) {
                    /*
                    Either only one record exists (main office has just been created) and no branch yet,
                    or several branches has been created. This means that branch code must be generated.
                    */
                    $code = $commonModel->generateCode('officeinfo', 'branchcode');
                    $branchCode = ($code == null ? '001' : sprintf('%03d', $code));
                }
                
                $name = $this->request->getVar('officename');
                $shortname = $this->request->getVar('officeshortname');
                $address = $this->request->getVar('officeaddress');

            } elseif ($txnType == 'Edit') {
                /*
                Edit or Delete mode:
                $tnxType must have a value assigned when this save function is called
                */
                file_put_contents('form_data.log', print_r('Edit Condition '.$txnType.' '.$date.PHP_EOL, true), FILE_APPEND);
                $brCode = $this->request->getVar('ebranchcode');
                $branchCode = ($brCode == '' ? null : $brCode);
                $name = $this->request->getVar('eofficename');
                $shortname = $this->request->getVar('eofficesname');
                $address = $this->request->getVar('eofficeaddress');
            }
            file_put_contents('form_data.log', print_r('before data array '.$txnType.' '.$date.PHP_EOL, true), FILE_APPEND);
            $data = [
                'companycode' => $companyCode,
                'branchcode' => $branchCode,
                'name' => $name,
                'shortname' => $shortname,
                'address' => $address,
                //'ratedistributioncode' => $this->request->getVar('ratedistributioncode'),
                'transactby'=> session()->get('userid'),
                'transacttype' => $txnType,
            ];
            $officeModel->insert($data);
            return redirect()->to('/office');

        } catch (\Exception $e) {
            file_put_contents('form_data.log', print_r('Exception '.$txnType.' '.$e->getMessage().' '.$date.PHP_EOL, true), FILE_APPEND);
            exit($e->getMessage());
        }
    }

    public function getOffice()
    {
        $officeModel = new officeModel();
        $recordno = $this->request->getPost('recordno');
        $data['office_obj'] = $officeModel->where('recordno', $recordno)->first();
        return $this->response->setJSON($data);
    }
}

and below is a portion of route code:

/*
 * --------------------------------------------------------------------
 * Route Definitions for Office
 * --------------------------------------------------------------------
 */
$routes->post('office-save/(:alpha)', 'OfficeController::save/$1');
$routes->match(['get', 'post'], 'OfficeController/countOffice', 'OfficeController::countOffice');
$routes->match(['get', 'post'], 'getOffice', 'OfficeController::getOffice');
/*

I tried to change it to (:num) i.e.: 1 - Add, 2-Edit, 3-Delete. But when 2 is defined, it does not respond.


Solution

  • I got it. on my html file (View). I overlooked a nested form. I just remove the nested form and it works.