About Lesson
To create a select2 with server-side in CodeIgniter 4, follow these steps:
Step 1: Database Setup
CREATE TABLE `state_info` ( `id` int(11) NOT NULL, `country_id` varchar(10) NOT NULL, `name` varchar(100) NOT NULL, `tin` varchar(10) NOT NULL, `code` varchar(100) NOT NULL, `ip_address` varchar(100) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `status` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
ALTER TABLE `state_info` ADD PRIMARY KEY (`id`);
Step 2: Controller
Create a controller to handle CRUD operations. Create a new file named Crud.php
in the app/Controllers/crud
folder.
<?php
namespace App\Controllers\crud;
use App\Controllers\BaseController;
use App\Models\state\StateModel;
class Crud extends BaseController {
public function __construct() {
$db = db_connect();
$this->state = new StateModel($db);
}
public function index() {
$this->find();
}
public function find() {
$data = [];
$data ['content_title'] = "Find State";
$data ['state_dropdown'] = $this->stateDropdown();
echo view('crud/find', $data);
}
public function search() {
$search = $this->request->getPost('search');
$where = 'name LIKE "%'.$search.'%"';
$result = $this->state->getEntryList($where);
$list = [];
foreach($result as $row) {
// $list [$row->name] = $row->name;
$list [] = [
'id' => $row->name,
'text' => $row->name,
];
}
echo json_encode($list);
}
}
Step 3: Model
Create a model to handle database operations. Create a new file named StateModel.php
in the app/Models/state
folder.
<?php
namespace App\Models\state;
use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;
class StateModel extends Model {
protected $db;
public function __construct(ConnectionInterface &$db) {
$this->db =& $db;
$this->table = 'state_info';
}
public function addEntry($data) {
$this->db->table($this->table)
->insert($data);
return $this->db->insertID();
}
public function getEntry($where) {
return $this->db->table($this->table)
->where($where)
->get()
->getRow();
}
public function getEntryList($where = 0) {
if($where) {
return $this->db->table($this->table)
->where($where)
->get()
->getResult();
} else {
return $this->db->table($this->table)
->get()
->getResult();
}
}
public function updateEntry($where, $data) {
return $this->db->table($this->table)
->where($where)
->set($data)
->update();
}
public function deleteEntry($where) {
return $this->db->table($this->table)
->where($where)
->delete();
}
}
Step 4: Create Views
Create views (find.php) in the app/Views/crud
folder for listing, creating, updating, and deleting records.
find.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $content_title; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Select2 Example </h1>
<p>CodeIgniter 4.</p>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>State</label>
<?php
$options = [
'1' => 'One',
'2' => 'Two',
];
echo form_dropdown(['name' => 'state', 'id' => 'state', 'class' => 'form-control get_state_list', 'options' => $state_dropdown]);
?>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
// select2
$(".select2").select2();
$('.get_state_list').select2({
ajax: {
url: '<?php echo base_url('crud/search'); ?>',
dataType: 'json',
method: 'POST',
delay: 250,
data: function (params) {
return {
search: params.term
}
},
processResults: function (response) {
return {
results: response
}
},
cache: true
},
minimumInputLength: 1,
placeholder: 'Enter query'
});
});
</script>
</body>
</html>
Step 5: Set Up Routes
Edit the app/config/Routes.php
file to define routes for your controller.
// select2
$routes->get('crud/find', 'crud\Crud::find');
$routes->post('crud/search', 'crud\Crud::search');