Codeigniter 4 - Dynamic Dependent Dropdown Tutorial

Apr 22, 2022 . Admin



Hello Friends,

In this short tutorial we will cover an dynamic dependent dropdown in codeigniter example. this example will help you dynamic dependent dropdown in codeigniter 4 with ajax. you will learn codeigniter dynamic dependent select box using ajax. This article goes in detailed on codeigniter 4 dynamic dropdown from database.

So, Let,s started full example..

Step 1: Install Codeigniter 4

In this first step if you have not created the codeigniter app, then you maygo ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2 : Basic Configurations

So in this step we will now set basic configuration on the app/config/app.php file, so let’s implement to application/config/config.php and open this file on text editor.

app/config/app.php
public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/example/';
Step 3 : Database Configurations
CREATE TABLE `city` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `cityname` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
CREATE TABLE `department` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `depart_name` varchar(80) NOT NULL,
  `city` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
CREATE TABLE `user_depart` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL,
  `department` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 4 : Database Configurations application/config/database.php
public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];
Step 5 : Create Model File

In this step now here we go visit app/Models/ and create here one model named Dropdown.php. Then add the following code into your Dropdown.php file:

app/Models/Dropdown.php
<?php
namespace App\Models;
use CodeIgniter\Model;
 
class Dropdown extends Model {
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getCity() {
 
       $query = $this->db->query('select * from city');
       return $query->getResult();
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getCityDepartment($postData) {
      $sql = 'select * from department where city ='.$postData['city'] ;
      $query =  $this->db->query($sql);
       
      return $query->getResult();
    }    
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getDepartmentUsers($postData) {
      $sql = 'select * from user_depart where department ='.$postData['department'] ;
      $query =  $this->db->query($sql);
       
      return $query->getResult();
    }
 
}
Step 6 : Set Up Controller

So, We will create new controller that manages the dropdown get record from the database, hence create a DropdownController.php file and append the example code in.

app/Controllers/DropdownController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Dropdown;
 
class DropdownController extends Controller {
 
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index() {
         
        helper(['form', 'url']);
        $this->Dropdown = new Dropdown();
        $data['cities'] = $this->Dropdown->getCity();
        return view('dropdown-view', $data);
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getCityDepartment() {
 
        $this->Dropdown = new Dropdown();
 
        $postData = array(
            'city' => $this->request->getPost('city'),
        );
 
        $data = $this->Dropdown->getCityDepartment($postData);
 
        echo json_encode($data);
    }    
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getDepartmentUsers() {
 
        $this->Dropdown = new Dropdown();
 
        $postData = array(
            'department' => $this->request->getPost('department'),
        );
 
        $data = $this->Dropdown->getDepartmentUsers($postData);
 
        echo json_encode($data);
    }
 
}
Step 7 : Set Up View

In this step go to application/views/ folder, create a new dropdown-view file. Likewise, open and add the suggested code example in application/views/dropdown-view.php file:

application/views/dropdown-view.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="content">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Codeigniter 4 Ajax Dependent Dropdown List - MyWebtuts.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h2 class="text-success">Codeigniter 4 Dynamic Dependent Dropdown with Ajax - MyWebtuts.com</h2>
                </div>
                <div class="card-body">
                    <form>
                        <div class="form-group">
                            <label for="country">City</label>
                            <select class="form-control" id="sel_city">
                                <option value="">Select City</option>
                                <?php foreach($cities as $city){?>
                                <option value="<?php echo $city->id;?>"><?php echo $city->cityname;?></option>"
                                <?php }?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="state">Departments</label>
                            <select class="form-control" id="sel_depart"></select>
                        </div>                        
                        <div class="form-group">
                            <label for="city">Users</label>
                            <select class="form-control" id="sel_user"></select>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type='text/javascript'>

/*------------------------------------------
--------------------------------------------
baseURL variable 
--------------------------------------------
--------------------------------------------*/
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){

    /*------------------------------------------
    --------------------------------------------
    City Change
    --------------------------------------------
    --------------------------------------------*/
    $('#sel_city').change(function(){
        var city = $(this).val();

        $.ajax({
            url:'<?=base_url()?>index.php/User/getCityDepartment',
            method: 'post',
            data: {city: city},
            dataType: 'json',
            success: function(response){
                $('#sel_user').find('option').not(':first').remove();
                $('#sel_depart').find('option').not(':first').remove();
                $.each(response,function(index,data){
                $('#sel_depart').append('<option value="'+data['id']+'">'+data['depart_name']+'</option>');
                });
            }
        });
    });

    /*------------------------------------------
    --------------------------------------------
    Department Change 
    --------------------------------------------
    --------------------------------------------*/
    $('#sel_depart').change(function(){
        var department = $(this).val();

        $.ajax({
            url:'<?=base_url()?>index.php/User/getDepartmentUsers',
            method: 'post',
            data: {department: department},
            dataType: 'json',
            success: function(response){
                $('#sel_user').find('option').not(':first').remove();
                $.each(response,function(index,data){
                $('#sel_user').append('<option value="'+data['id']+'">'+data['name']+'</option>');
                });
            }
        });
    });
});
</script>
</body>
</html>
Step 8 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost/demo/public/index.php/dropdown

I hope it can help you...

#Codeigniter 4