Membuat Hak Akses User bagian 1

Artikel ini merupakan lanjutan pembahasan dari sistem login, dimana kali ini kita akan membagi hak akses user berdasarkan role, kita sudah berhasil membuat sistem login dan login sesuai username dan role user, namun ada beberapa permasalahan seperti, tiap user dapat mengakses menu padahal menu tersebut seharusnya dibatasi aksesnya, terus setelah berhasil login user masih harus login lagi ketika mengakses halaman login. Nah, kita akan memperbaiki permasalahan tersebut. Silahkan baca dan ikuti setiap bagian pada artikel ini, karena artikelnya lumayan panjang, semoga tidak menyulitkan.

Menyiapkan Tabel

Hal pertama yang akan kita lakukan adalah membuat tabel baru, yaitu tabel: Menu, Submenu dan Aksesmenu. Tabel menu berisi menu yang memisahkan sub menu, sub menu sendiri merupakan controller, akses menu merupakan pembatas antar menu, user mana saja yang dapat mengakses sub menu berdasarkan role user. seperti pada gambar berikut ini:

Tabel Menu

Tabel Sub Menu

Tabel Akses Menu

Setelah membuat tabel, selanjutnya adalah membuat halaman Menu, Sub Menu dan Role user

Membuat Halaman Menu

Membuat Model

Pada bagian ini kita akan membuat model misalnya kita beri nama model Modelmenu.php, kita dapat membuatnya langsung pada folder Models atau melalui Terminal/CMD seperti berikut ini

cli
php spark make:model Modelmenu

Nanti setelah perintah php spark make... dijalankan, akan terbentuk sebuah file dengan nama Modelmenu.php yang tersimpan pada folder Models.

Silahkan salin baris kode di bawah ini, lalu tempel ke dalam file Modelmenu.php:

Baris Kode Modelmenu.php
php
<?php namespace App\Models; use CodeIgniter\Model; use CodeIgniter\HTTP\RequestInterface; use Config\Services; class Modelmenu extends Model { protected $table = 'menu'; protected $primaryKey = 'id_menu'; protected $column_order = ['', 'menu', '', '', 'aktif', ''];//kolom yang disort protected $column_search = ['menu'];//kolom yang dicari protected $order = ['urutan' => 'asc']; protected $allowedFields = ['id_menu', 'menu', 'menu_slug', 'link', 'ikon', 'urutan', 'aktif']; protected $request; protected $db; protected $dt; function __construct(RequestInterface $request) { $request = Services::request(); parent::__construct(); $this->db = db_connect(); $this->request = $request; // tampilkan isi tabel $this->dt = $this->db->table($this->table); } private function _get_datatables_query() { $i = 0; foreach ($this->column_search as $item) { if ($this->request->getPost('search')['value']) { if ($i === 0) { $this->dt->groupStart(); $this->dt->like($item, $this->request->getPost('search')['value']); } else { $this->dt->orLike($item, $this->request->getPost('search')['value']); } if (count($this->column_search) - 1 == $i) $this->dt->groupEnd(); } $i++; } if ($this->request->getPost('order')) { $this->dt->orderBy($this->column_order[$this->request->getPost('order')['0']['column']], $this->request->getPost('order')['0']['dir']); } else if (isset($this->order)) { $order = $this->order; $this->dt->orderBy(key($order), $order[key($order)]); } } function get_datatables() { $this->_get_datatables_query(); if ($this->request->getPost('length') != -1) $this->dt->limit($this->request->getPost('length'), $this->request->getPost('start')); $query = $this->dt->get(); return $query->getResult(); } function count_filtered() { $this->_get_datatables_query(); return $this->dt->countAllResults(); } public function count_all() { $tbl_storage = $this->db->table($this->table); return $tbl_storage->countAllResults(); } }

Membuat Controller

Selanjutnya yaitu membuat controller untuk menu, misal kita beri nama Menu.php, sama seperti membuat model, kita dapat membuatnya melalui 2 (dua) cara, yaitu langsung melalui folder Controllers atau melalui Terminal/CMD yang berbasis CLI, seperti berikut:

cli
php spark make:controller Menu

Silahkan salin kode di bawah ini, lalu tempel ke dalam file Menu.php:

Baris Kode Menu.php
php
<?php namespace App\Controllers; use App\Controllers\BaseController; use App\Models\Modelmenu; use Config\Services; class Menu extends BaseController { public function index() { $data['judul'] = "Halaman Menu"; return view('menu/index', $data); } public function tampildata() { if ($this->request->isAJAX()) { $msg = [ 'data' => view('menu/datamenu') ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } public function ajax_list() { $request = Services::request(); $m_data = new Modelmenu($request); if ($request->getPost()) { $lists = $m_data->get_datatables(); $data = []; $no = $request->getPost("start"); foreach ($lists as $list) { $no++; $row = []; //tombol edit $tomboledit = "<button type=\"button\" title=\"Edit Data\" class=\"btn btn-info btn-sm\" onclick=\"edit('" . $list->id_menu . "')\"> <i class=\"fa fa-tasks\"></i></button>"; //tombol hapus $tombolhapus = "<button type=\"button\" title=\"Hapus Data\" class=\"btn btn-danger btn-sm\" onclick=\"hapus('" . $list->id_menu . "')\"> <i class=\"fa fa-trash\"></i></button>"; $row[] = $no; $row[] = $list->menu; $row[] = $list->link; $row[] = $list->ikon; if ($list->aktif == 'Y') { $row[] = '<div class="text-primary">Aktif</div>'; } else { $row[] = '<div class="text-danger">Tidak</div>'; } $row[] = $tomboledit . " " . $tombolhapus; $data[] = $row; } $output = [ "draw" => $request->getPost('draw'), "recordsTotal" => $m_data->count_all(), "recordsFiltered" => $m_data->count_filtered(), "data" => $data ]; echo json_encode($output); } } //tampil modal tambah public function tambahdata() { if ($this->request->isAJAX()) { $msg = [ 'data' => view('menu/modaltambah') ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //proses simpan data public function simpandata() { if ($this->request->isAJAX()) { $validation = \Config\Services::validation(); $valid = $this->validate([ 'menu' => [ 'label' => 'Menu', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'link' => [ 'label' => 'Link', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'ikon' => [ 'label' => 'Ikon', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'urutan' => [ 'label' => 'Urutan', 'rules' => 'required|numeric', 'errors' => [ 'required' => '{field} tidak boleh kosong', 'numeric' => '{field} harus berupa angka', ] ], ]); if (!$valid) { $msg = [ 'error' => [ 'menu' => $validation->getError('menu'), 'link' => $validation->getError('link'), 'ikon' => $validation->getError('ikon'), 'urutan' => $validation->getError('urutan') ] ]; } else { //menu slug $slug = url_title($this->request->getVar('menu'), '-', true); $simpandata = [ 'menu' => $this->request->getVar('menu'), 'menu_slug' => $slug, 'link' => $this->request->getVar('link'), 'ikon' => $this->request->getVar('ikon'), 'urutan' => $this->request->getVar('urutan'), 'aktif' => 'Y' ]; //simpan ke tabel menu $request = Services::request(); $user = new Modelmenu($request); $user->insert($simpandata); $msg = [ 'sukses' => 'Data menu telah tersimpan' ]; } echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //tampil edit data public function editdata() { if ($this->request->isAJAX()) { $id_menu = $this->request->getVar('id_menu'); //data menu $request = Services::request(); $menu = new Modelmenu($request); $data['menu'] = $menu->find($id_menu); $msg = [ 'sukses' => view('menu/modaledit', $data) ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //update data public function updatedata() { if ($this->request->isAJAX()) { $validation = \Config\Services::validation(); $valid = $this->validate([ 'menu' => [ 'label' => 'Menu', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'link' => [ 'label' => 'Link', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'ikon' => [ 'label' => 'Ikon', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'urutan' => [ 'label' => 'Urutan', 'rules' => 'required|numeric', 'errors' => [ 'required' => '{field} tidak boleh kosong', 'numeric' => '{field} harus berupa angka', ] ], ]); if (!$valid) { $msg = [ 'error' => [ 'menu' => $validation->getError('menu'), 'link' => $validation->getError('link'), 'ikon' => $validation->getError('ikon'), 'urutan' => $validation->getError('urutan') ] ]; } else { //nama slug $slug = url_title($this->request->getVar('menu'), '-', true); // untuk menu yang aktif $aktif = $this->request->getVar('aktif'); // ini yang tidak aktif if ($aktif != "Y") { $aktif = "T"; } $simpandata = [ 'menu' => $this->request->getVar('menu'), 'menu_slug' => $slug, 'link' => $this->request->getVar('link'), 'ikon' => $this->request->getVar('ikon'), 'urutan' => $this->request->getVar('urutan'), 'aktif' => $aktif, ]; $request = Services::request(); $menu = new Modelmenu($request); //update data menu $id_menu = $this->request->getVar('id_menu'); $menu->update($id_menu, $simpandata); $msg = [ 'sukses' => 'Data menu telah diupdate' ]; } echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //hapus data public function hapus() { if ($this->request->isAJAX()) { $id_menu = $this->request->getVar('id_menu'); $request = Services::request(); $user = new Modelmenu($request); $user->delete($id_menu); $msg = [ 'sukses' => "Data menu telah dihapus" ]; echo json_encode($msg); } } }

Membuat View

Setelah Controller dan Model Menu kita buat, langkah selanjutnya adalah membuat view untuk user interface-nya, biasa kita akan membagi menjadi 4 (empat) file, yaitu: index.php, datamenu.php, modaltambah.php dan modaledit.php. Keempat file tersebut akan kita simpan di folder Views/menu, berarti kita harus membuat folder menu terlebih dahulu di dalam folder Views, seperti pada gambar beikut ini:

Membuat file index.php

Silahkan buat file index.php, lalu salin baris kode berikut:

Baris kode index.php
html
<?= $this->extend('template/main'); ?> <?= $this->extend('template/menu'); ?> <?= $this->section('konten'); ?> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800"><?= $judul ?></h1> </div> <div class="container"> <button type="button" class="btn btn-primary btn-sm tomboltambah"> <i class="fa fa-plus-circle"></i> Tambah Data </button> <div class="mt-3 card-text viewdata"> </div> <div class="viewmodal" style="display:none;"></div> <script> //tampil data function datamenu() { $.ajax({ url: "<?= site_url('menu/tampildata') ?>", dataType: "json", success: function(response) { $('.viewdata').html(response.data); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } $(document).ready(function() { datamenu(); }); //tambah data $('.tomboltambah').click(function(e) { e.preventDefault(); $.ajax({ url: "<?= site_url('menu/tambahdata') ?>", dataType: "json", success: function(response) { $('.viewmodal').html(response.data).show(); $('#modaltambah').modal('show'); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); }); </script> <?= $this->endsection(''); ?>

Membuat file datamenu.php

Silahkan buat file datamenu.php, lalu salin baris kode berikut:

Baris kode datamenu.php
html
<div class="table-responsive b-0" data-pattern="priority-columns"> <table id="myTable" class="table table-striped table-bordered table-hover"> <thead class="bg-primary text-white"> <tr> <td>No</td> <td>Menu</td> <td>Link</td> <td>Ikon</td> <td>Aktif</td> <td>Aksi</td> </tr> </thead> <tbody> </tbody> </table> </div> <script> //datatable $(document).ready(function() { var table = $('#myTable').DataTable({ "processing": true, "serverSide": true, "order": [], "ajax": { "url": "<?php echo base_url('menu/ajax_list') ?>", "type": "POST" }, //optional "lengthMenu": [ [5, 10, 25, 50, 100], [5, 10, 25, 50, 100] ], "columnDefs": [{ "targets": [0, 2, 3, 5], //kolom yg tidak bisa di sort 0,2,3 dan 5 "orderable": false, }, ], }); }); // //edit modal function edit(id_menu) { $.ajax({ type: "post", url: "<?= site_url('menu/editdata') ?>", data: { id_menu: id_menu }, dataType: "json", success: function(response) { if (response.sukses) { $('.viewmodal').html(response.sukses).show(); $('#modaledit').modal('show'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } //hapus konfirmasi function hapus(id_menu) { Swal.fire({ title: 'Hapus Data', text: 'Yakin menghapus menu?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#dc3545', cancelButtonColor: '#6c757d', confirmButtonText: 'Ya', cancelButtonText: 'Batal' }).then((result) => { if (result.isConfirmed) { $.ajax({ type: "post", url: "<?= site_url('menu/hapus') ?>", data: { id_menu: id_menu }, dataType: "json", success: function(response) { if (response.sukses) { Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses, }) datamenu(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } }) } </script>

Membuat file modaltambah.php

Silahkan buat file modaltambah.php, lalu salin baris kode berikut:

Baris kode modaltambah.php
html
<!-- Modal --> <div class="modal fade" id="modaltambah" tabindex="-1" aria-labelledby="modaltambahLabel" aria-hidden="true"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="modaltambahLabel">Tambah Menu</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <?= form_open('menu/simpandata', ['class' => 'formmenu']); ?> <?= csrf_field(); ?> <div class="modal-body"> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Menu</label> <div class="col-sm-8"> <input type="text" class="form-control" id="menu" name="menu"> <div class="invalid-feedback errorMenu"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Link</label> <div class="col-sm-8"> <input type="text" class="form-control" id="link" name="link"> <div class="invalid-feedback errorLink"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Ikon</label> <div class="col-sm-8"> <input type="text" class="form-control" id="ikon" name="ikon"> <div class="invalid-feedback errorIkon"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Urutan</label> <div class="col-sm-4"> <input type="number" class="form-control" id="urutan" name="urutan"> <div class="invalid-feedback errorUrutan"> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btnsimpan">Simpan</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> </div> <?= form_close(); ?> </div> </div> </div> <script> $(document).ready(function() { //focus pada input $('body').on('shown.bs.modal', '#modaltambah', function() { $('input:visible:enabled:first', this).focus(); }) $('.formmenu').submit(function(e) { e.preventDefault(); $.ajax({ type: "post", url: $(this).attr('action'), data: $(this).serialize(), dataType: "json", beforeSend: function() { $('.btnsimpan').attr('disabled', 'disabled'); $('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses'); }, complete: function() { $('.btnsimpan').removeAttr('disabled'); $('.btnsimpan').html('Simpan'); }, success: function(response) { //klo ada error if (response.error) { //error menu if (response.error.menu) { $('#menu').addClass('is-invalid'); $('.errorMenu').html(response.error.menu); } else { $('#menu').removeClass('is-invalid'); $('.errorMenu').html(''); } //error link if (response.error.link) { $('#link').addClass('is-invalid'); $('.errorLink').html(response.error.link); } else { $('#link').removeClass('is-invalid'); $('.errorLink').html(''); } //error ikon if (response.error.ikon) { $('#ikon').addClass('is-invalid'); $('.errorIkon').html(response.error.ikon); } else { $('#ikon').removeClass('is-invalid'); $('.errorIkon').html(''); } //error urutan if (response.error.urutan) { $('#urutan').addClass('is-invalid'); $('.errorUrutan').html(response.error.urutan); } else { $('#urutan').removeClass('is-invalid'); $('.errorUrutan').html(''); } } //sukses else { //pesan sukses bro Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses }); //hide modal tambah data $('#modaltambah').modal('hide'); //load data menu datamenu(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); return false; }); }); </script>

Membuat file modaledit.php

Silahkan buat file modaledit.php, lalu salin baris kode berikut:

Baris kode modaledit.php
html
<!-- Modal --> <div class="modal fade" id="modaledit" tabindex="-1" aria-labelledby="modaleditLabel" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="modaleditLabel">Edit Menu</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <?= form_open('menu/updatedata', ['class' => 'formmenu']); ?> <?= csrf_field(); ?> <div class="modal-body"> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Menu</label> <div class="col-sm-8"> <input type="text" class="form-control" id="id_menu" name="id_menu" value="<?= $menu['id_menu'] ?>" hidden> <input type="text" class="form-control" id="menu" name="menu" value="<?= $menu['menu'] ?>"> <div class="invalid-feedback errorMenu"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Link</label> <div class="col-sm-8"> <input type="text" class="form-control" id="link" name="link" value="<?= $menu['link']; ?>"> <div class="invalid-feedback errorLink"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Ikon</label> <div class="col-sm-8"> <input type="text" class="form-control" id="ikon" name="ikon" value="<?= $menu['ikon']; ?>"> <div class="invalid-feedback errorIkon"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Urutan</label> <div class="col-sm-4"> <input type="number" class="form-control" id="urutan" name="urutan" value="<?= $menu['urutan']; ?>"> <div class="invalid-feedback errorUrutan"> </div> </div> </div> <!-- akif dan tidak --> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Aktif</label> <div class="col-sm-4"> <div class="custom-control custom-switch mt-2"> <!-- aktif --> <input type="checkbox" class="custom-control-input" value="Y" name="aktif" id="customSwitch1" <?php if ($menu['aktif'] == 'Y') echo "checked"; ?>> <label class="custom-control-label" for="customSwitch1">Ya</label> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btnsimpan">Simpan</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> </div> <?= form_close(); ?> </div> </div> </div> <script> $(document).ready(function() { //focus pada input $('body').on('shown.bs.modal', '#modaltambah', function() { $('input:visible:enabled:first', this).focus(); }) $('.formmenu').submit(function(e) { e.preventDefault(); $.ajax({ type: "post", url: $(this).attr('action'), data: $(this).serialize(), dataType: "json", beforeSend: function() { $('.btnsimpan').attr('disabled', 'disabled'); $('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses'); }, complete: function() { $('.btnsimpan').removeAttr('disabled'); $('.btnsimpan').html('Simpan'); }, success: function(response) { //klo ada error if (response.error) { //error menu if (response.error.menu) { $('#menu').addClass('is-invalid'); $('.errorMenu').html(response.error.menu); } else { $('#menu').removeClass('is-invalid'); $('.errorMenu').html(''); } //error link if (response.error.link) { $('#link').addClass('is-invalid'); $('.errorLink').html(response.error.link); } else { $('#link').removeClass('is-invalid'); $('.errorLink').html(''); } //error ikon if (response.error.ikon) { $('#ikon').addClass('is-invalid'); $('.errorIkon').html(response.error.ikon); } else { $('#ikon').removeClass('is-invalid'); $('.errorIkon').html(''); } //error urutan if (response.error.urutan) { $('#urutan').addClass('is-invalid'); $('.errorUrutan').html(response.error.urutan); } else { $('#urutan').removeClass('is-invalid'); $('.errorUrutan').html(''); } } //sukses else { //pesan sukses bro Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses }); //hide modal tambah data $('#modaledit').modal('hide'); //load data menu datamenu(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); return false; }); }); </script>

Update file Routes

Setelah selesai membuat view, langkah selanjutnya adalah meng-update file Routes.php yang terdapat pada folder /app/config/Routes.php, seperti berikut ini:

Potongan Baris kode Routes.php
php
.... // menu $routes->get('/menu', 'Menu::index'); $routes->get('/menu/tampildata', 'Menu::tampildata'); $routes->post('/menu/ajax_list', 'Menu::ajax_list'); $routes->get('/menu/tambahdata', 'Menu::tambahdata'); $routes->post('/menu/simpandata', 'Menu::simpandata'); $routes->post('/menu/editdata', 'Menu::editdata'); $routes->post('/menu/updatedata', 'Menu::updatedata'); $routes->post('/menu/hapus', 'Menu::hapus'); ....

Menginput Data Menu

Buka tautan http://localhost:8080/menu, silahkan isi data menu, seperti ini:

Membuat Halaman Sub Menu

Selanjunya kita akan membuat halaman sub menu, untuk membuat halaman tersebut mirip caranya seperti membuat halaman menu, yaitu membuat model, controller, view dan update pada routes. Karena ini adalah langkahnya masih sama, saya tidak menjelaskan secara rinci.

Membuat Model

Silahkan buka terminal pada Visual Studio Code atau CMD pada folder proyek-web, lalu jalankan perintah berikut ini:

cli
php spark make:model Modelsubmenu

silahkan salin baris kode berikut, pada file Modelsubmenu.php:

Baris Kode Modelsubmenu.php
php
<?php namespace App\Models; use CodeIgniter\Model; use CodeIgniter\HTTP\RequestInterface; use Config\Services; class Modelsubmenu extends Model { protected $table = 'submenu'; protected $primaryKey = 'id_submenu'; protected $column_order = ['', 'submenu', 'menu', '', '', 'aktif', '']; protected $column_search = ['submenu']; protected $order = ['submenu' => 'asc']; protected $allowedFields = ['id_submenu', 'id_menu', 'submenu', 'submenu_slug', 'link', 'ikon', 'aktif']; protected $request; protected $db; protected $dt; function __construct(RequestInterface $request) { $request = Services::request(); parent::__construct(); $this->db = db_connect(); $this->request = $request; // tampilkan isi tabel $this->dt = $this->db->table($this->table)->select('id_submenu,submenu,submenu_slug,submenu.link,submenu.ikon,submenu.aktif,menu.menu')->join('menu', 'menu.id_menu=submenu.id_menu');; } private function _get_datatables_query() { $i = 0; foreach ($this->column_search as $item) { if ($this->request->getPost('search')['value']) { if ($i === 0) { $this->dt->groupStart(); $this->dt->like($item, $this->request->getPost('search')['value']); } else { $this->dt->orLike($item, $this->request->getPost('search')['value']); } if (count($this->column_search) - 1 == $i) $this->dt->groupEnd(); } $i++; } if ($this->request->getPost('order')) { $this->dt->orderBy($this->column_order[$this->request->getPost('order')['0']['column']], $this->request->getPost('order')['0']['dir']); } else if (isset($this->order)) { $order = $this->order; $this->dt->orderBy(key($order), $order[key($order)]); } } function get_datatables() { $this->_get_datatables_query(); if ($this->request->getPost('length') != -1) $this->dt->limit($this->request->getPost('length'), $this->request->getPost('start')); $query = $this->dt->get(); return $query->getResult(); } function count_filtered() { $this->_get_datatables_query(); return $this->dt->countAllResults(); } public function count_all() { $tbl_storage = $this->db->table($this->table); return $tbl_storage->countAllResults(); } }

Membuat Controller

Lanjut ke pembuatan Controller Sub Menu, kita cukup menjalankan perintah ini:

cli
php spark:controller Submenu

Lalu salin kode berikut:

php
<?php namespace App\Controllers; use App\Controllers\BaseController; use App\Models\Modelsubmenu; use App\Models\Modelmenu; use Config\Services; class Submenu extends BaseController { public function index() { $data['judul'] = "Halaman Sub Menu"; return view('submenu/index', $data); } public function tampildata() { if ($this->request->isAJAX()) { $msg = [ 'data' => view('submenu/datasubmenu') ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } public function ajax_list() { $request = Services::request(); $m_data = new Modelsubmenu($request); if ($request->getPost()) { $lists = $m_data->get_datatables(); $data = []; $no = $request->getPost("start"); foreach ($lists as $list) { $no++; $row = []; //tombol edit $tomboledit = "<button type=\"button\" title=\"Edit Data\" class=\"btn btn-info btn-sm\" onclick=\"edit('" . $list->id_submenu . "')\"> <i class=\"fa fa-tasks\"></i></button>"; //tombol hapus $tombolhapus = "<button type=\"button\" title=\"Hapus Data\" class=\"btn btn-danger btn-sm\" onclick=\"hapus('" . $list->id_submenu . "')\"> <i class=\"fa fa-trash\"></i></button>"; $row[] = $no; $row[] = $list->submenu; $row[] = $list->menu; $row[] = $list->link; $row[] = $list->ikon; if ($list->aktif == 'Y') { $row[] = '<div class="text-primary">Aktif</div>'; } else { $row[] = '<div class="text-danger">Tidak</div>'; } $row[] = $tomboledit . " " . $tombolhapus; $data[] = $row; } $output = [ "draw" => $request->getPost('draw'), "recordsTotal" => $m_data->count_all(), "recordsFiltered" => $m_data->count_filtered(), "data" => $data ]; echo json_encode($output); } } //tampil modal tambah public function tambahdata() { if ($this->request->isAJAX()) { // akses ke tabel menu $menu = new Modelmenu($this->request); $data['menu'] = $menu->findAll(); $msg = [ 'data' => view('submenu/modaltambah', $data) ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //proses simpan data public function simpandata() { if ($this->request->isAJAX()) { $validation = \Config\Services::validation(); $valid = $this->validate([ 'submenu' => [ 'label' => 'Sub Menu', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'link' => [ 'label' => 'Link', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'ikon' => [ 'label' => 'Ikon', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'id_menu' => [ 'label' => 'Menu', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], ]); if (!$valid) { $msg = [ 'error' => [ 'submenu' => $validation->getError('submenu'), 'link' => $validation->getError('link'), 'ikon' => $validation->getError('ikon'), 'urutan' => $validation->getError('urutan'), 'id_menu' => $validation->getError('id_menu'), ] ]; } else { //submenu slug $slug = url_title($this->request->getVar('submenu'), '-', true); $simpandata = [ 'submenu' => $this->request->getVar('submenu'), 'submenu_slug' => $slug, 'link' => $this->request->getVar('link'), 'ikon' => $this->request->getVar('ikon'), 'id_menu' => $this->request->getVar('id_menu'), 'aktif' => 'Y' ]; //simpan ke tabel Sub Menu $request = Services::request(); $user = new Modelsubmenu($request); $user->insert($simpandata); $msg = [ 'sukses' => 'Data Sub Menu telah tersimpan' ]; } echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //tampil edit data public function editdata() { if ($this->request->isAJAX()) { $id_submenu = $this->request->getVar('id_submenu'); //data submenu $request = Services::request(); $submenu = new Modelsubmenu($request); $data['submenu'] = $submenu->find($id_submenu); // akses ke tabel menu $menu = new Modelmenu($this->request); $data['menu'] = $menu->findAll(); $msg = [ 'sukses' => view('submenu/modaledit', $data) ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //update data public function updatedata() { if ($this->request->isAJAX()) { $validation = \Config\Services::validation(); $valid = $this->validate([ 'submenu' => [ 'label' => 'Sub Menu', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'link' => [ 'label' => 'Link', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'ikon' => [ 'label' => 'Ikon', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], 'id_menu' => [ 'label' => 'Menu', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], ]); if (!$valid) { $msg = [ 'error' => [ 'submenu' => $validation->getError('submenu'), 'link' => $validation->getError('link'), 'ikon' => $validation->getError('ikon'), 'urutan' => $validation->getError('urutan'), 'id_menu' => $validation->getError('id_menu'), ] ]; } else { //nama slug $slug = url_title($this->request->getVar('submenu'), '-', true); // untuk submenu yang aktif $aktif = $this->request->getVar('aktif'); // ini yang tidak aktif if ($aktif != "Y") { $aktif = "T"; } $simpandata = [ 'submenu' => $this->request->getVar('submenu'), 'submenu_slug' => $slug, 'link' => $this->request->getVar('link'), 'ikon' => $this->request->getVar('ikon'), 'id_menu' => $this->request->getVar('id_menu'), 'aktif' => $aktif, ]; $request = Services::request(); $submenu = new Modelsubmenu($request); //update data submenu $id_submenu = $this->request->getVar('id_submenu'); $submenu->update($id_submenu, $simpandata); $msg = [ 'sukses' => 'Data Sub Menu telah diupdate' ]; } echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //hapus data public function hapus() { if ($this->request->isAJAX()) { $id_submenu = $this->request->getVar('id_submenu'); $request = Services::request(); $user = new Modelsubmenu($request); $user->delete($id_submenu); $msg = [ 'sukses' => "Data Sub Menu telah dihapus" ]; echo json_encode($msg); } } }

Membuat View

Untuk membuat tampilan sub menu, kita akan membuat sebuah folder submenu yang terdapat pada folder Views, yang berisi index.php, datasubmenu.php, modaltambah.php, modaledit.php, seperti pada gambar berikut:

Membuat file index.php

Silahkan buat file index.php, lalu salin baris kode berikut:

Baris kode index.php
html
<?= $this->extend('template/main'); ?> <?= $this->extend('template/menu'); ?> <?= $this->section('konten'); ?> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800"><?= $judul ?></h1> </div> <div class="container"> <button type="button" class="btn btn-primary btn-sm tomboltambah"> <i class="fa fa-plus-circle"></i> Tambah Data </button> <div class="mt-3 card-text viewdata"> </div> <div class="viewmodal" style="display:none;"></div> <script> //tampil data function datasubmenu() { $.ajax({ url: "<?= site_url('submenu/tampildata') ?>", dataType: "json", success: function(response) { $('.viewdata').html(response.data); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } $(document).ready(function() { datasubmenu(); }); //tambah data $('.tomboltambah').click(function(e) { e.preventDefault(); $.ajax({ url: "<?= site_url('submenu/tambahdata') ?>", dataType: "json", success: function(response) { $('.viewmodal').html(response.data).show(); $('#modaltambah').modal('show'); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); }); </script> <?= $this->endsection(''); ?>

Membuat file datasubmenu.php

Silahkan buat file datasubmenu.php, lalu salin baris kode berikut:

Baris kode datasubmenu.php
html
<div class="table-responsive b-0" data-pattern="priority-columns"> <table id="myTable" class="table table-striped table-bordered table-hover"> <thead class="bg-primary text-white"> <tr> <td>No</td> <td>Sub Menu</td> <td>Menu</td> <td>Link</td> <td>Ikon</td> <td>Aktif</td> <td>Aksi</td> </tr> </thead> <tbody> </tbody> </table> </div> <script> //datatable $(document).ready(function() { var table = $('#myTable').DataTable({ "processing": true, "serverSide": true, "order": [], "ajax": { "url": "<?php echo base_url('submenu/ajax_list') ?>", "type": "POST" }, //optional "lengthMenu": [ [5, 10, 25, 50, 100], [5, 10, 25, 50, 100] ], "columnDefs": [{ "targets": [0, 3, 4, 6], //kolom yang tidak disort 0,3,4 dan 6 "orderable": false, }, ], }); }); // //edit modal function edit(id_submenu) { $.ajax({ type: "post", url: "<?= site_url('submenu/editdata') ?>", data: { id_submenu: id_submenu }, dataType: "json", success: function(response) { if (response.sukses) { $('.viewmodal').html(response.sukses).show(); $('#modaledit').modal('show'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } //hapus konfirmasi function hapus(id_submenu) { Swal.fire({ title: 'Hapus Data', text: 'Yakin menghapus menu?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#dc3545', cancelButtonColor: '#6c757d', confirmButtonText: 'Ya', cancelButtonText: 'Batal' }).then((result) => { if (result.isConfirmed) { $.ajax({ type: "post", url: "<?= site_url('submenu/hapus') ?>", data: { id_submenu: id_submenu }, dataType: "json", success: function(response) { if (response.sukses) { Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses, }) datasubmenu(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } }) } </script>

Membuat file modaltambah.php

Silahkan buat file modaltambah.php, lalu salin baris kode berikut:

Baris kode modaltambah.php
html
<!-- Modal --> <div class="modal fade" id="modaltambah" tabindex="-1" aria-labelledby="modaltambahLabel" aria-hidden="true"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="modaltambahLabel">Tambah Sub Menu</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <?= form_open('submenu/simpandata', ['class' => 'formsubmenu']); ?> <?= csrf_field(); ?> <div class="modal-body"> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Sub Menu</label> <div class="col-sm-8"> <input type="text" class="form-control" id="submenu" name="submenu"> <div class="invalid-feedback errorSubmenu"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Link</label> <div class="col-sm-8"> <input type="text" class="form-control" id="link" name="link"> <div class="invalid-feedback errorLink"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Ikon</label> <div class="col-sm-8"> <input type="text" class="form-control" id="ikon" name="ikon"> <div class="invalid-feedback errorIkon"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Menu</label> <div class="col-sm-6"> <select name="id_menu" id="id_menu" class="form-control"> <option value="">--Pilih--</option> <?php foreach ($menu as $m) : ?> <option value="<?= $m['id_menu'] ?>"><?= $m['menu'] ?></option> <?php endforeach; ?> </select> <div class="invalid-feedback errorMenu"> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btnsimpan">Simpan</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> </div> <?= form_close(); ?> </div> </div> </div> <script> $(document).ready(function() { //focus pada input $('body').on('shown.bs.modal', '#modaltambah', function() { $('input:visible:enabled:first', this).focus(); }) $('.formsubmenu').submit(function(e) { e.preventDefault(); $.ajax({ type: "post", url: $(this).attr('action'), data: $(this).serialize(), dataType: "json", beforeSend: function() { $('.btnsimpan').attr('disabled', 'disabled'); $('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses'); }, complete: function() { $('.btnsimpan').removeAttr('disabled'); $('.btnsimpan').html('Simpan'); }, success: function(response) { //klo ada error if (response.error) { //error sub menu if (response.error.submenu) { $('#submenu').addClass('is-invalid'); $('.errorSubmenu').html(response.error.submenu); } else { $('#submenu').removeClass('is-invalid'); $('.errorSubmenu').html(''); } //error link if (response.error.link) { $('#link').addClass('is-invalid'); $('.errorLink').html(response.error.link); } else { $('#link').removeClass('is-invalid'); $('.errorLink').html(''); } //error ikon if (response.error.ikon) { $('#ikon').addClass('is-invalid'); $('.errorIkon').html(response.error.ikon); } else { $('#ikon').removeClass('is-invalid'); $('.errorIkon').html(''); } //error menu if (response.error.id_menu) { $('#id_menu').addClass('is-invalid'); $('.errorMenu').html(response.error.id_menu); } else { $('#id_menu').removeClass('is-invalid'); $('.errorMenu').html(''); } } //sukses else { //pesan sukses bro Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses }); //hide modal tambah data $('#modaltambah').modal('hide'); //load data menu datasubmenu(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); return false; }); }); </script>

Membuat file modaledit.php

Silahkan buat file modaledit.php, lalu salin baris kode berikut:

Baris kode modaledit.php
html
<!-- Modal --> <div class="modal fade" id="modaledit" tabindex="-1" aria-labelledby="modaleditLabel" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="modaleditLabel">Edit Sub Menu</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <?= form_open('submenu/updatedata', ['class' => 'formsubmenu']); ?> <?= csrf_field(); ?> <div class="modal-body"> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Sub Menu</label> <div class="col-sm-8"> <input type="text" class="form-control" id="id_submenu" name="id_submenu" value="<?= $submenu['id_submenu'] ?>" hidden> <input type="text" class="form-control" id="submenu" name="submenu" value="<?= $submenu['submenu'] ?>"> <div class="invalid-feedback errorSubmenu"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Link</label> <div class="col-sm-8"> <input type="text" class="form-control" id="link" name="link" value="<?= $submenu['link']; ?>"> <div class="invalid-feedback errorLink"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Ikon</label> <div class="col-sm-8"> <input type="text" class="form-control" id="ikon" name="ikon" value="<?= $submenu['ikon']; ?>"> <div class="invalid-feedback errorIkon"> </div> </div> </div> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Menu</label> <div class="col-sm-6"> <select name="id_menu" id="id_menu" class="form-control"> <option value="">--Pilih--</option> <?php foreach ($menu as $m) : ?> <?php if ($m['id_menu'] == $submenu['id_menu']) { ?> <option value="<?= $m['id_menu'] ?>" selected><?= $m['menu'] ?></option> <?php } else { ?> <option value="<?= $m['id_menu'] ?>"><?= $m['menu'] ?></option> <?php } endforeach; ?> </select> <div class="invalid-feedback errorMenu"> </div> </div> </div> <!-- akif dan tidak --> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Aktif</label> <div class="col-sm-4"> <div class="custom-control custom-switch mt-2"> <!-- aktif --> <input type="checkbox" class="custom-control-input" value="Y" name="aktif" id="customSwitch1" <?php if ($submenu['aktif'] == 'Y') echo "checked"; ?>> <label class="custom-control-label" for="customSwitch1">Ya</label> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btnsimpan">Simpan</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> </div> <?= form_close(); ?> </div> </div> </div> <script> $(document).ready(function() { //focus pada input $('body').on('shown.bs.modal', '#modaltambah', function() { $('input:visible:enabled:first', this).focus(); }) $('.formsubmenu').submit(function(e) { e.preventDefault(); $.ajax({ type: "post", url: $(this).attr('action'), data: $(this).serialize(), dataType: "json", beforeSend: function() { $('.btnsimpan').attr('disabled', 'disabled'); $('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses'); }, complete: function() { $('.btnsimpan').removeAttr('disabled'); $('.btnsimpan').html('Simpan'); }, success: function(response) { //klo ada error if (response.error) { //error sub menu if (response.error.submenu) { $('#submenu').addClass('is-invalid'); $('.errorSubmenu').html(response.error.submenu); } else { $('#submenu').removeClass('is-invalid'); $('.errorSubmenu').html(''); } //error link if (response.error.link) { $('#link').addClass('is-invalid'); $('.errorLink').html(response.error.link); } else { $('#link').removeClass('is-invalid'); $('.errorLink').html(''); } //error ikon if (response.error.ikon) { $('#ikon').addClass('is-invalid'); $('.errorIkon').html(response.error.ikon); } else { $('#ikon').removeClass('is-invalid'); $('.errorIkon').html(''); } //error menu if (response.error.id_menu) { $('#id_menu').addClass('is-invalid'); $('.errorMenu').html(response.error.id_menu); } else { $('#id_menu').removeClass('is-invalid'); $('.errorMenu').html(''); } } //sukses else { //pesan sukses bro Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses }); //hide modal tambah data $('#modaledit').modal('hide'); //load data menu datasubmenu(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); return false; }); }); </script>

Update File Routes.php

Selanjutnya kita akan menambah Route atau rute sub menu, sehingga dapat dikenali oleh sistem Codeigniter 4, silahkan salin baris kode berikut ke dalam file Routes.php:

Potongan Baris kode Routes.php
php
.... // sub menu $routes->get('/submenu', 'Submenu::index'); $routes->get('/submenu/tampildata', 'Submenu::tampildata'); $routes->post('/submenu/ajax_list', 'Submenu::ajax_list'); $routes->get('/submenu/tambahdata', 'Submenu::tambahdata'); $routes->post('/submenu/simpandata', 'Submenu::simpandata'); $routes->post('/submenu/editdata', 'Submenu::editdata'); $routes->post('/submenu/updatedata', 'Submenu::updatedata'); $routes->post('/submenu/hapus', 'Submenu::hapus'); ....

Menginput Data Sub Menu

Buka tautan http://localhost:8080/submenu, silahkan isi data sub menu, sesuai pada gambar berikut:

Membuat Halaman Role

Mengubah Model Role

Karena kita sudah membuat model role pada artikel sebelumnya, maka kita akan mengubah saja dengan menambahkan fungsi tambahan, perhatikan baris kode berikut:

Baris kode Modelrole.php
php
<?php namespace App\Models; use CodeIgniter\Model; use CodeIgniter\HTTP\RequestInterface; use Config\Services; class Modelrole extends Model { protected $table = "role"; protected $primaryKey = "id_role"; protected $column_order = ['', 'role', '']; protected $column_search = ['role']; protected $order = ['id_role' => 'asc']; //field yang dapat diisi protected $allowedFields = ['id_role', 'role']; protected $request; protected $db; protected $dt; function __construct(RequestInterface $request) { $request = Services::request(); parent::__construct(); $this->db = db_connect(); $this->request = $request; // tampilkan isi tabel $this->dt = $this->db->table($this->table); } private function _get_datatables_query() { $i = 0; foreach ($this->column_search as $item) { if ($this->request->getPost('search')['value']) { if ($i === 0) { $this->dt->groupStart(); $this->dt->like($item, $this->request->getPost('search')['value']); } else { $this->dt->orLike($item, $this->request->getPost('search')['value']); } if (count($this->column_search) - 1 == $i) $this->dt->groupEnd(); } $i++; } if ($this->request->getPost('order')) { $this->dt->orderBy($this->column_order[$this->request->getPost('order')['0']['column']], $this->request->getPost('order')['0']['dir']); } else if (isset($this->order)) { $order = $this->order; $this->dt->orderBy(key($order), $order[key($order)]); } } function get_datatables() { $this->_get_datatables_query(); if ($this->request->getPost('length') != -1) $this->dt->limit($this->request->getPost('length'), $this->request->getPost('start')); $query = $this->dt->get(); return $query->getResult(); } function count_filtered() { $this->_get_datatables_query(); return $this->dt->countAllResults(); } public function count_all() { $tbl_storage = $this->db->table($this->table); return $tbl_storage->countAllResults(); } }

Membuat Controller

Kita akan membuat controller role, silahkan salin kode berikut pada terminal

cli
php spark make:controller role

silahkan salin baris kode berikut:

php
<?php namespace App\Controllers; use App\Controllers\BaseController; use App\Models\Modelrole; use App\Models\Modelmenu; use Config\Services; class Role extends BaseController { public function index() { $data['judul'] = "Halaman Role User"; return view('role/index', $data); } public function tampildata() { if ($this->request->isAJAX()) { $msg = [ 'data' => view('role/datarole') ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } public function ajax_list() { $request = Services::request(); $m_data = new Modelrole($request); if ($request->getPost()) { $lists = $m_data->get_datatables(); $data = []; $no = $request->getPost("start"); foreach ($lists as $list) { $no++; $row = []; //tombol edit $tomboledit = "<button type=\"button\" title=\"Edit Data\" class=\"btn btn-info btn-sm\" onclick=\"edit('" . $list->id_role . "')\"> <i class=\"fa fa-tasks\"></i></button>"; $row[] = $no; $row[] = $list->role; $row[] = $tomboledit; $data[] = $row; } $output = [ "draw" => $request->getPost('draw'), "recordsTotal" => $m_data->count_all(), "recordsFiltered" => $m_data->count_filtered(), "data" => $data ]; echo json_encode($output); } } //tampil modal tambah public function tambahdata() { if ($this->request->isAJAX()) { $msg = [ 'data' => view('role/modaltambah') ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //proses simpan data public function simpandata() { if ($this->request->isAJAX()) { $validation = \Config\Services::validation(); $valid = $this->validate([ 'role' => [ 'label' => 'Role', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ] ]); if (!$valid) { $msg = [ 'error' => [ 'role' => $validation->getError('role') ] ]; } else { $simpandata = [ 'role' => $this->request->getVar('role') ]; //simpan ke tabel menu $request = Services::request(); $user = new Modelrole($request); $user->insert($simpandata); $msg = [ 'sukses' => 'Data role telah tersimpan' ]; } echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //tampil edit data public function editdata() { if ($this->request->isAJAX()) { $id_role = $this->request->getVar('id_role'); //data menu $request = Services::request(); $role = new Modelrole($request); $data['role'] = $role->find($id_role); $msg = [ 'sukses' => view('role/modaledit', $data) ]; echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } //update data public function updatedata() { if ($this->request->isAJAX()) { $validation = \Config\Services::validation(); $valid = $this->validate([ 'role' => [ 'label' => 'Role', 'rules' => 'required', 'errors' => [ 'required' => '{field} tidak boleh kosong', ] ], ]); if (!$valid) { $msg = [ 'error' => [ 'role' => $validation->getError('role') ] ]; } else { //simpan data $simpandata = [ 'role' => $this->request->getVar('role') ]; $request = Services::request(); $role = new Modelrole($request); //update data role $id_role = $this->request->getVar('id_role'); $role->update($id_role, $simpandata); $msg = [ 'sukses' => 'Data role telah diupdate' ]; } echo json_encode($msg); } else { exit('Maaf, tidak dapat diproses'); } } }

Membuat View

Sama seperti pada view menu atau sub menu, terlebih kita akan membuat folder role pada folder Views, lalu menambahkan beberapa file: index.php, datarole.php, modaltambah.php dan modaledit.php

Membuat file index.php

Silahkan salin baris kode berikut:

Baris kode index.php
html
<?= $this->extend('template/main'); ?> <?= $this->extend('template/menu'); ?> <?= $this->section('konten'); ?> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800"><?= $judul ?></h1> </div> <div class="container"> <button type="button" class="btn btn-primary btn-sm tomboltambah"> <i class="fa fa-plus-circle"></i> Tambah Data </button> <div class="mt-3 card-text viewdata"> </div> <div class="viewmodal" style="display:none;"></div> <script> //tampil data function datarole() { $.ajax({ url: "<?= site_url('role/tampildata') ?>", dataType: "json", success: function(response) { $('.viewdata').html(response.data); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } $(document).ready(function() { datarole(); }); //tambah data $('.tomboltambah').click(function(e) { e.preventDefault(); $.ajax({ url: "<?= site_url('role/tambahdata') ?>", dataType: "json", success: function(response) { $('.viewmodal').html(response.data).show(); $('#modaltambah').modal('show'); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); }); </script> <?= $this->endsection(''); ?>

Membuat datarole.php

Silahkan salin baris kode berikut:

Baris kode datarole.php
html
<div class="table-responsive b-0" data-pattern="priority-columns"> <table id="myTable" class="table table-striped table-bordered table-hover"> <thead class="bg-primary text-white"> <tr> <td>No</td> <td>Role</td> <td>Aksi</td> </tr> </thead> <tbody> </tbody> </table> </div> <script> //datatable $(document).ready(function() { var table = $('#myTable').DataTable({ "processing": true, "serverSide": true, "order": [], "ajax": { "url": "<?php echo base_url('role/ajax_list') ?>", "type": "POST" }, //optional "lengthMenu": [ [5, 10, 25, 50, 100], [5, 10, 25, 50, 100] ], "columnDefs": [{ "targets": [0, 2], "orderable": false, }, ], }); }); //edit modal function edit(id_role) { $.ajax({ type: "post", url: "<?= site_url('role/editdata') ?>", data: { id_role: id_role }, dataType: "json", success: function(response) { if (response.sukses) { $('.viewmodal').html(response.sukses).show(); $('#modaledit').modal('show'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } //edit akses function akses(id_role) { $.ajax({ type: "post", url: "<?= site_url('role/editakses') ?>", data: { id_role: id_role }, dataType: "json", success: function(response) { if (response.sukses) { $('.viewmodal').html(response.sukses).show(); $('#modalakses').modal('show'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); } </script>

Membuat modaltambah.php

Silahkan salin baris kode berikut:

Baris kode modaltambah.php
html
<!-- Modal --> <div class="modal fade" id="modaltambah" tabindex="-1" aria-labelledby="modaltambahLabel" aria-hidden="true"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="modaltambahLabel">Tambah Role User</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <?= form_open('role/simpandata', ['class' => 'formrole']); ?> <?= csrf_field(); ?> <div class="modal-body"> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Role</label> <div class="col-sm-8"> <input type="text" class="form-control" id="role" name="role"> <div class="invalid-feedback errorRole"> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btnsimpan">Simpan</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> </div> <?= form_close(); ?> </div> </div> </div> <script> $(document).ready(function() { //focus pada input $('body').on('shown.bs.modal', '#modaltambah', function() { $('input:visible:enabled:first', this).focus(); }) $('.formrole').submit(function(e) { e.preventDefault(); $.ajax({ type: "post", url: $(this).attr('action'), data: $(this).serialize(), dataType: "json", beforeSend: function() { $('.btnsimpan').attr('disabled', 'disabled'); $('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses'); }, complete: function() { $('.btnsimpan').removeAttr('disabled'); $('.btnsimpan').html('Simpan'); }, success: function(response) { //klo ada error if (response.error) { //error menu if (response.error.role) { $('#role').addClass('is-invalid'); $('.errorRole').html(response.error.role); } else { $('#role').removeClass('is-invalid'); $('.errorRole').html(''); } } //sukses else { //pesan sukses bro Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses }); //hide modal tambah data $('#modaltambah').modal('hide'); //load data role datarole(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); return false; }); }); </script>

Membuat modaledit.php

Silahkan salin baris kode berikut:

Baris kode modaledit.php
html
<!-- Modal --> <div class="modal fade" id="modaledit" tabindex="-1" aria-labelledby="modaleditLabel" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="modaleditLabel">Edit Role User</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <?= form_open('role/updatedata', ['class' => 'formrole']); ?> <?= csrf_field(); ?> <div class="modal-body"> <div class="form-group row"> <label for="" class="col-sm-2 col-form-label">Menu</label> <div class="col-sm-8"> <input type="text" class="form-control" id="id_role" name="id_role" value="<?= $role['id_role'] ?>" hidden> <input type="text" class="form-control" id="role" name="role" value="<?= $role['role'] ?>"> <div class="invalid-feedback errorRole"> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btnsimpan">Simpan</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button> </div> <?= form_close(); ?> </div> </div> </div> <script> $(document).ready(function() { //focus pada input $('body').on('shown.bs.modal', '#modaltambah', function() { $('input:visible:enabled:first', this).focus(); }) $('.formrole').submit(function(e) { e.preventDefault(); $.ajax({ type: "post", url: $(this).attr('action'), data: $(this).serialize(), dataType: "json", beforeSend: function() { $('.btnsimpan').attr('disabled', 'disabled'); $('.btnsimpan').html('<i class="fa fa-spin fa-spinner"></i> Proses'); }, complete: function() { $('.btnsimpan').removeAttr('disabled'); $('.btnsimpan').html('Simpan'); }, success: function(response) { //klo ada error if (response.error) { //error role if (response.error.role) { $('#role').addClass('is-invalid'); $('.errorRole').html(response.error.role); } else { $('#role').removeClass('is-invalid'); $('.errorRole').html(''); } } //sukses else { //pesan sukses bro Swal.fire({ icon: 'success', title: 'Berhasil', text: response.sukses }); //hide modal tambah data $('#modaledit').modal('hide'); //load data menu datarole(); } }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status + "\n" + xhr.responseText + "\n" + thrownError); } }); return false; }); }); </script>

Update File Routes.php

Setelah semua bagian dari halaman role dibuat, saatnya kita mengupdate file Routes.php, silahkan tambahkan kode berikut ini pada baris akhir file Routes.php

Potongan baris kode Routes.php
php
// role $routes->get('/role', 'Role::index'); $routes->get('/role/tampildata', 'Role::tampildata'); $routes->post('/role/ajax_list', 'Role::ajax_list'); $routes->get('/role/tambahdata', 'Role::tambahdata'); $routes->post('/role/simpandata', 'Role::simpandata'); $routes->post('/role/editdata', 'Role::editdata'); $routes->post('/role/updatedata', 'Role::updatedata'); $routes->post('/role/editakses', 'Role::editakses'); $routes->post('/role/updateakses', 'Role::updateakses');

Menampilkan Isi Role

Silahkan buka pada tautan http://localhost:8080/role

Cukup untuk artikel kali ini, karena pembahasan masih panjang maka kita akan lanjut bagian kedua.

Prototez
Prototez Bercerita mencari jawaban

Tidak ada komentar untuk "Membuat Hak Akses User bagian 1"