Dari artikel sebelumnya yang berjudul Membuat Combo Box Bertingkat dengan Plugin Select 2 pada Codeigniter 3, banyak sekali komentar dan pertanyaan terkait proses editing data. Pada kesempatan kali ini sekaligus akan kita buat tutorial lengkap dari input data, edit data dan delete data. Untuk read data tidak perlu kita bahas di sini, karena tentunya lebih mudah dan pembaca mungkin sudah tidak mengalami kesulitan terkait hal ini. Artikel ini juga mengacu pada artikel sebelumnya CodeIgniter 3 – Membuat Datatables Server Side untuk menampilkan hasil inputan ke dalam format datatables serverside.
Hal yang pertama kita lakukan adalah pembuatan database/tabel. Untuk yang sudah mengikuti artikel Membuat Combo Box Bertingkat dengan Plugin Select 2 pada Codeigniter 3, mungkin sudah mempunyai tabel daerah.sql atau dapat diunduh pada menu download.
Membuat Tabel
Tabel yang kita buat diberi nama crud_select2, untuk penamaan tabel silahkan disesuaikan dengan kebutuhan.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for crud_select2 -- ---------------------------- DROP TABLE IF EXISTS `crud_select2`; CREATE TABLE `crud_select2` ( `id` varchar(15) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, `alamat` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL, `id_prov` char(2) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL, `id_kab` char(4) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL, `id_kec` char(6) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL, `id_kel` char(10) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL, `create_date` datetime(0) NULL DEFAULT NULL, `last_update` datetime(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; |
Membuat Model
Buat model dengan nama Crud_select2_model.php, kemudian ketikkan script dibawah
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Crud_select2_model extends CI_Model { // list data serverside var $column_order = array(null, 'alamat', 'kelurahan.nama', 'kecamatan.nama', 'kabupaten.nama', 'provinsi.nama'); var $column_search = array('alamat', 'kelurahan.nama', 'kecamatan.nama', 'kabupaten.nama', 'provinsi.nama'); var $order = array('id_kel' => 'asc'); private function _get_datatables_query() { $this->db->select('id, alamat, kelurahan.nama AS nm_kel, kecamatan.nama AS nm_kec, kabupaten.nama AS nm_kab, provinsi.nama AS nm_prov, crud_select2.last_update'); $this->db->from('crud_select2'); $this->db->join('kelurahan', 'kelurahan.id_kel = crud_select2.id_kel', 'left'); $this->db->join('kecamatan', 'kecamatan.id_kec = crud_select2.id_kec', 'left'); $this->db->join('kabupaten', 'kabupaten.id_kab = crud_select2.id_kab', 'left'); $this->db->join('provinsi', 'provinsi.id_prov = crud_select2.id_prov', 'left'); $i = 0; foreach ($this->column_search as $item) { if ($_POST['search']['value']) { if ($i === 0) { $this->db->group_start(); $this->db->like($item, $_POST['search']['value']); } else { $this->db->or_like($item, $_POST['search']['value']); } if (count($this->column_search) - 1 == $i) $this->db->group_end(); } $i++; } if (isset($_POST['order'])) { $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']); } else if (isset($this->order)) { $order = $this->order; $this->db->order_by(key($order), $order[key($order)]); } } function get_datatables() { $this->_get_datatables_query(); if ($_POST["length"] != -1) { $this->db->limit($_POST['length'], $_POST['start']); } $query = $this->db->get(); return $query->result(); } public function count_filtered() { $this->_get_datatables_query(); $query = $this->db->get(); return $query->num_rows(); } public function count_all() { $this->db->from('crud_select2'); return $this->db->count_all_results(); } // end list data public function get_alamat_by_id($id) { $this->db->select('id, alamat, crud_select2.id_kel, crud_select2.id_kec, crud_select2.id_kab, crud_select2.id_prov, kelurahan.nama AS nm_kel, kecamatan.nama AS nm_kec, kabupaten.nama AS nm_kab, provinsi.nama AS nm_prov'); $this->db->where('id', $id); $this->db->from('crud_select2'); $this->db->join('kelurahan', 'kelurahan.id_kel = crud_select2.id_kel', 'left'); $this->db->join('kecamatan', 'kecamatan.id_kec = crud_select2.id_kec', 'left'); $this->db->join('kabupaten', 'kabupaten.id_kab = crud_select2.id_kab', 'left'); $this->db->join('provinsi', 'provinsi.id_prov = crud_select2.id_prov', 'left'); $query = $this->db->get(); return $query->row(); } function getprov($searchTerm = "") { $this->db->select('id_prov, nama'); $this->db->where("nama like '%" . $searchTerm . "%' "); $this->db->order_by('id_prov', 'asc'); $fetched_records = $this->db->get('provinsi'); $dataprov = $fetched_records->result_array(); $data = array(); foreach ($dataprov as $prov) { $data[] = array("id" => $prov['id_prov'], "text" => $prov['nama']); } return $data; } function getkab($id_prov, $searchTerm = "") { $this->db->select('id_kab, nama'); $this->db->where('id_prov', $id_prov); $this->db->where("nama like '%" . $searchTerm . "%' "); $this->db->order_by('id_kab', 'asc'); $fetched_records = $this->db->get('kabupaten'); $datakab = $fetched_records->result_array(); $data = array(); foreach ($datakab as $kab) { $data[] = array("id" => $kab['id_kab'], "text" => $kab['nama']); } return $data; } function getkec($id_kab, $searchTerm = "") { $this->db->select('id_kec, nama'); $this->db->where('id_kab', $id_kab); $this->db->where("nama like '%" . $searchTerm . "%' "); $this->db->order_by('id_kec', 'asc'); $fetched_records = $this->db->get('kecamatan'); $datakec = $fetched_records->result_array(); $data = array(); foreach ($datakec as $kec) { $data[] = array("id" => $kec['id_kec'], "text" => $kec['nama']); } return $data; } function getkel($id_kec, $searchTerm = "") { $this->db->select('id_kel, nama'); $this->db->where('id_kec', $id_kec); $this->db->where("nama like '%" . $searchTerm . "%' "); $this->db->order_by('id_kel', 'asc'); $fetched_records = $this->db->get('kelurahan'); $datakel = $fetched_records->result_array(); $data = array(); foreach ($datakel as $kel) { $data[] = array("id" => $kel['id_kel'], "text" => $kel['nama']); } return $data; } public function insert($data) { $this->db->insert('crud_select2', $data); return $this->db->insert_id(); } public function update($id, $data) { $this->db->where('id', $id); return $this->db->update('crud_select2', $data); } public function delete($id) { $this->db->where('id', $id); return $this->db->delete('crud_select2'); } } |
Pada model di atas, dapat kita bagi menjadi 3 bagian besar function, yaitu untuk menampilkan data transaksi menggunakan datatables serverside, menampilkan combo box select2, dan proses insert, update dan delete data.
Membuat Controller
Buat controller dengan nama Crud_select2.php, kemudian ketikkan script dibawah
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Crud_select2 extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Crud_select2_model', 'CRUD'); $this->load->library('form_validation'); $this->load->library('session'); } public function index() { $this->load->view('crud_select2_list'); } // list data public function listdata() { $list = $this->CRUD->get_datatables(); $data = array(); $no = $_POST['start']; if (isset($_POST['start']) && isset($_POST['draw'])) { $no = $_POST['start']; } else { die(); }; foreach ($list as $dt) { $edit = '<a href="' . base_url('crud_select2/update/' . $dt->id) . '" class ="btn btn-sm btn-warning">Ubah</a>'; $delete = '<a href="' . base_url('crud_select2/delete/' . $dt->id) . '" class ="btn btn-sm btn-danger">Hapus</a>'; $no++; $row = array(); $row[] = $no; $row[] = $dt->alamat; $row[] = $dt->nm_kel; $row[] = $dt->nm_kec; $row[] = $dt->nm_kab; $row[] = $dt->nm_prov; $row[] = $dt->last_update; $row[] = $edit . ' | ' . $delete; $data[] = $row; } $output = array( "draw" => $_POST['draw'], "recordsTotal" => $this->CRUD->count_all(), "recordsFiltered" => $this->CRUD->count_filtered(), "data" => $data, ); echo json_encode($output); } public function create() { $this->_rules(); if ($this->form_validation->run() == false) { $data = array( 'action' => site_url('crud_select2/create'), 'alamat' => set_value('alamat', $this->input->post('alamat')), ); $this->load->view('crud_select2_form', $data, false); } else { $data = array( 'id' => uniqid(), 'alamat' => $this->input->post('alamat'), 'id_prov' => $this->input->post('provinsi'), 'id_kab' => $this->input->post('kabupaten'), 'id_kec' => $this->input->post('kecamatan'), 'id_kel' => $this->input->post('kelurahan'), 'create_date' => date('Y-m-d H:i:s'), 'last_update' => date('Y-m-d H:i:s'), ); $this->CRUD->insert($data); $this->session->set_flashdata('message', 'Tambah alamat berhasil'); redirect('crud_select2', 'refresh'); } } public function update($id) { $this->_rules(); $row = $this->CRUD->get_alamat_by_id($id); if ($row) { if ($this->form_validation->run() == false) { $data = array( 'action' => site_url('crud_select2/update/' . $id), 'alamat' => set_value('alamat', $row->alamat), 'id_prov' => set_value('id_prov', $row->id_prov), 'nm_prov' => set_value('nm_prov', $row->nm_prov), 'id_kab' => set_value('id_kab', $row->id_kab), 'nm_kab' => set_value('nm_kab', $row->nm_kab), 'id_kec' => set_value('id_kec', $row->id_kec), 'nm_kec' => set_value('nm_kec', $row->nm_kec), 'id_kel' => set_value('id_kel', $row->id_kel), 'nm_kel' => set_value('nm_kel', $row->nm_kel), ); $this->load->view('crud_select2_form', $data, false); } else { $data = array( 'alamat' => $this->input->post('alamat'), 'id_prov' => $this->input->post('provinsi'), 'id_kab' => $this->input->post('kabupaten'), 'id_kec' => $this->input->post('kecamatan'), 'id_kel' => $this->input->post('kelurahan'), 'last_update' => date('Y-m-d H:i:s'), ); $this->CRUD->update($id, $data); $this->session->set_flashdata('message', 'Ubah alamat berhasil'); redirect('crud_select2', 'refresh'); } } else { $this->session->set_flashdata('message', 'Data tidak ditemukan'); redirect('crud_select2', 'refresh'); } } public function delete($id) { $row = $this->CRUD->get_alamat_by_id($id); if ($row) { $this->CRUD->delete($id); $this->session->set_flashdata('message', 'Data berhasil dihapus'); redirect(site_url('crud_select2')); } else { $this->session->set_flashdata('message', 'Data tidak ditemukan'); redirect(site_url('crud_select2')); } } // Provinsi public function getdataprov() { $searchTerm = $this->input->post('searchTerm'); $response = $this->CRUD->getprov($searchTerm); echo json_encode($response); } // Kabupaten public function getdatakab($id_prov) { $searchTerm = $this->input->post('searchTerm'); $response = $this->CRUD->getkab($id_prov, $searchTerm); echo json_encode($response); } // Kecamatan public function getdatakec($id_kab) { $searchTerm = $this->input->post('searchTerm'); $response = $this->CRUD->getkec($id_kab, $searchTerm); echo json_encode($response); } // Kelurahan public function getdatakel($id_kec) { $searchTerm = $this->input->post('searchTerm'); $response = $this->CRUD->getkel($id_kec, $searchTerm); echo json_encode($response); } // form validation public function _rules() { $this->form_validation->set_rules('alamat', '<span class="text-danger">Alamat</span>', 'required'); $this->form_validation->set_rules('provinsi', '<span class="text-danger">Provinsi</span>', 'required'); $this->form_validation->set_rules('kabupaten', '<span class="text-danger">Kabupaten</span>', 'required'); $this->form_validation->set_rules('kecamatan', '<span class="text-danger">Kecamatan</span>', 'required'); $this->form_validation->set_rules('kelurahan', '<span class="text-danger">Kelurahan</span>', 'required'); } } |
Membuat view
File view yang kita buat sebanyak dua file yaitu crud_select2_form.php untuk view form input dan update, dan file crud_select2_list.php untuk menampilkan daftar alamat yang kita inputkan.
File crud_select2_form.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>CRUD dengan SELECT2</title> <!-- Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@300;400;600&display=swap" rel="stylesheet"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!-- JQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <!-- Datatables --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"> <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script> <!-- Select2 --> <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/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <style> body { font-family: 'Oswald', sans-serif; font-weight: 300; } </style> </head> <body> <div class="container"> <div class="row mt-4"> <div class="col-md-12"> <h4 class="text-center">Form dengan Select 2</h4> <hr> <?php if (!empty(validation_errors())) { ?> <div class="alert alert-warning" role="alert" id="infoMessage"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h5> Perhatian!</h5> <strong><?php echo validation_errors(); ?></strong> </div> <?php } ?> <form class="form-horizontal" action="<?php echo $action; ?>" method="post" enctype='multipart/form-data' id="form"> <div class="form-group"> <label for="alamat">Alamat</label> <textarea name="alamat" id="alamat" cols="30" rows="3" class="form-control"><?php echo $alamat; ?></textarea> </div> <div class="form-group row"> <div class="col-md-6"> <label for="provinsi">Provinsi</label> <select id="provinsi" name="provinsi" class="form-control select2"> <option value="" selected>Pilih Provinsi</option> </select> <script type="text/javascript"> // Provinsi $(document).ready(function() { $("#provinsi").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdataprov', type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); }); </script> <?php if ($this->uri->segment(2) == 'update') { ?> <script type="text/javascript"> var $option = $("<option selected></option>").val('<?php echo $id_prov; ?>').text("<?php echo $nm_prov; ?>"); $('#provinsi').append($option).trigger('change'); </script> <?php } ?> </div> <div class="col-md-6"> <label for="kabupaten">Kabupaten</label> <select id="kabupaten" name="kabupaten" class="form-control select2"> <option value="" selected>Pilih Kabupaten</option> </select> <script type="text/javascript"> // Kabupaten $("#provinsi").change(function() { var id_prov = $("#provinsi").val(); $("#kabupaten").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakab/' + id_prov, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); }); </script> <?php if ($this->uri->segment(2) == 'update') { ?> <script type="text/javascript"> var $option = $("<option selected></option>").val('<?php echo $id_kab; ?>').text("<?php echo $nm_kab; ?>"); $('#kabupaten').append($option).trigger('change'); var id_prov = $("#provinsi").val(); $("#kabupaten").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakab/' + id_prov, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); $("#provinsi").change(function() { $('#kabupaten').append('<option value="" selected>Pilih Kabupaten</option>').trigger('change'); $('#kecamatan').append('<option value="" selected>Pilih Kecamatan</option>').trigger('change'); $('#kelurahan').append('<option value="" selected>Pilih Kelurahan</option>').trigger('change'); }); </script> <?php } ?> </div> </div> <div class="form-group row"> <div class="col-md-6"> <label for="kecamatan">Kecamatan</label> <select id="kecamatan" name="kecamatan" class="form-control select2"> <option value="" selected>Pilih kecamatan</option> </select> <script type="text/javascript"> // Kecamatan $("#kabupaten").change(function() { var id_kab = $("#kabupaten").val(); $("#kecamatan").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakec/' + id_kab, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); }); </script> <?php if ($this->uri->segment(2) == 'update') { ?> <script type="text/javascript"> var $option = $("<option selected></option>").val('<?php echo $id_kec; ?>').text("<?php echo $nm_kec; ?>"); $('#kecamatan').append($option).trigger('change'); var id_kab = $("#kabupaten").val(); $("#kecamatan").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakec/' + id_kab, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); $("#kabupaten").change(function() { $('#kecamatan').append('<option value="" selected>Pilih Kecamatan</option>').trigger('change'); $('#kelurahan').append('<option value="" selected>Pilih Kelurahan</option>').trigger('change'); }); </script> <?php } ?> </div> <div class="col-md-6"> <label for="kelurahan">Kelurahan</label> <select id="kelurahan" name="kelurahan" class="form-control select2"> <option value="" selected>Pilih kelurahan</option> </select> <script type="text/javascript"> // Kelurahan $("#kecamatan").change(function() { var id_kac = $("#kecamatan").val(); $("#kelurahan").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakel/' + id_kac, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); }); </script> <?php if ($this->uri->segment(2) == 'update') { ?> <script type="text/javascript"> var $option = $("<option selected></option>").val('<?php echo $id_kel; ?>').text("<?php echo $nm_kel; ?>"); $('#kelurahan').append($option).trigger('change'); var id_kac = $("#kecamatan").val(); $("#kelurahan").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakel/' + id_kac, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); $("#kecamatan").change(function() { $('#kelurahan').append('<option value="" selected>Pilih Kelurahan</option>').trigger('change'); }); </script> <?php } ?> </div> </div> <hr> <a href="<?php echo base_url('crud_select2'); ?>" class="btn btn-sm btn-warning">Kembali</a> <button type="submit" class="btn btn-sm btn-danger">Simpan</button> </form> </div> </div> </div> </body> </html> |
Poin utama untuk proses editing data ada pada bagian script berikut
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php if ($this->uri->segment(2) == 'update') { ?> <script type="text/javascript"> var $option = $("<option selected></option>").val('<?php echo $id_kab; ?>').text("<?php echo $nm_kab; ?>"); $('#kabupaten').append($option).trigger('change'); var id_prov = $("#provinsi").val(); $("#kabupaten").select2({ ajax: { url: '<?php echo base_url() ?>crud_select2/getdatakab/' + id_prov, type: "post", dataType: 'json', delay: 200, data: function(params) { return { searchTerm: params.term }; }, processResults: function(response) { return { results: response }; }, cache: true } }); $("#provinsi").change(function() { $('#kabupaten').append('<option value="" selected>Pilih Kabupaten</option>').trigger('change'); $('#kecamatan').append('<option value="" selected>Pilih Kecamatan</option>').trigger('change'); $('#kelurahan').append('<option value="" selected>Pilih Kelurahan</option>').trigger('change'); }); </script> <?php } ?> |
Proses akan mendeteksi url jika uri segment 2 sama dengan “update”, maka option selected akan di set sesuai dengan nilai yang di definisikan pada function update pada controller. Untuk posisi uri segment bisa diganti-ganti sesuai alamat url pada aplikasi yang dibuat. Untuk tutorial ini karena urlnya adalah http://localhost/tutorial/crud_select2/update/64200a7ca54e0 maka posisi “update” pada uri segment 2. Penamaan url juga bisa disesuaikan tidak harus menggunakan “update”, bisa juga “edit”, “ubah” dan lain-lain sesuai kebutuhan.
File crud_select2_list.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
<!DOCTYPE html> <html> <head> <title>Codeigniter - CRUD dengan Select 2</title> <!-- Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@300;400;600&display=swap" rel="stylesheet"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!-- JQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <!-- Datatables --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"> <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script> <style> body { font-family: 'Oswald', sans-serif; font-weight: 300; font-size: 0.85rem; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <h4 class="text-center">CRUD dengan Select 2</h4> <hr> </div> </div> <div class="row"> <div class="col-md-12"> <a href="<?php echo base_url('crud_select2/create') ?>" class="d-none d-sm-inline-block btn btn-sm btn-danger shadow-sm col-12 col-sm-3 col-md-2">Tambah Data</a> </div> </div> <div class="row mt-4"> <div class="col-12"> <div class="card"> <div class="card-header"> Daftar Alamat </div> <div class="card-body"> <?php if (!empty($this->session->userdata('message'))) { ?> <div class="alert alert-success" role="alert" id="infoMessage"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h5><i class="icon fas fa-check"></i> Pesan!</h5> <strong><?php echo $this->session->userdata('message'); ?></strong> </div> <?php } ?> <div class="responsive"> <table id="list_data" class="table display row-border table-striped compact" style="width: 100%;"> <thead> <tr> <th>No</th> <th>Alamat</th> <th>Kelurahan</th> <th>Kecamatan</th> <th>Kabupaten</th> <th>Provinsi</th> <th>Tanggal Ubah</th> <th>Opsi</th> </tr> </thead> </table> </div> </div> </div> </div> </div> <script type="text/javascript"> var dataTable_; $(document).ready(function() { dataTable_ = $('#list_data').DataTable({ processing: true, serverSide: true, searching: true, info: true, paging: true, lengthChange: true, ordering: true, ajax: { url: '<?php echo base_url('crud_select2/listdata'); ?>', type: "POST" }, }); }) </script> </body> </html> |
Jika langkah-langkah di atas sudah sesuai maka akan didapatkan hasil seperti berikut ini
Demikian pembahasan kali ini terkait CRUD menggunakan form inputan select2 dengan model combo box bertingkat. Jika ada yang kurang jelas silahkan isi kolom komentar. Terimakasih.