بِسْمِ اللَّهِ Mudah-mudahan tutorial Codeigniter 4 – Pagination pencarian dengan filter ini bermanfaat
Pagination atau pengaturan tampilan data per halaman didalam website adalah salah satu bagian penting dalam ilmu per-website-an. Hal berpengaruh dengan performa dari website itu sendiri. Tentunya pengaruh itu untuk menampilkan data yang banyak.
Kombinasi Pagination dengan filter atau pencarian merupakan pekerjaan yang membutuhkan waktu tersendiri, karena disana membutuhkan dua konsentrasi sekaligus. Biasanya waktu membuat pagination, pada bagian filternya terabaikan, begitu pula sebaliknya.
Persiapan Codeigniter 4 – Pagination dengan filter pencarian
Yang harus ada sebelum mengerjakan tutorial ini
Codeigniter 4 atau yang versi terakhir linknya ada disini
Template SB Admin 2 linknya ada disini
Kita mulai saja, kali ini saya akan berbagi tentang pagination dengan menggunakan Codeigniter 4. Silakan simak juga Pengenalan dan Instalasi Codeigniter disini. Sebenarnya pada framework tersebut sudah menyediakan library pagination. Nah disini saya juga akan memanfaatkan library tersebut dengan saya tambah dan kurangi sedikit. Juga dikombinasi dengan tutorial yang ada di internet, tapi maaf link-nya lupa saya simpan.
Database
Siapkan database dengan tabel berikut, kebetulan nama database yang saya gunakan adalah “db_ci4” tabel disini menyesuaikan dengan tabel yang anda buat.
CREATE TABLE `news` (
`id` int(11) NOT NULL,
`username` varchar(30) DEFAULT NULL,
`title` varchar(254) NOT NULL,
`slug` varchar(254) NOT NULL,
`body` text NOT NULL,
`publish_date` date NOT NULL,
`image` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `news`
ADD PRIMARY KEY (`id`),
ADD KEY `slug` (`slug`);
ALTER TABLE `news`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Untuk testing biar kelihatan pagination di Codeigniter itu jalan, langsung saja ditambahkan datanya dengan script berikut, dan biar datanya banyak silakan ulangi beberapa kali (11x cukup). Dan jangan lupa diganti id dan slugnya karena kedua field ini adalah kunci
INSERT INTO `news` (`id`, `username`, `title`, `slug`, `body`, `publish_date`, `image`) VALUES
(1, NULL, 'Implementation Information-1', 'implementation-information-1', '<p>
The purpose of this HTML is to help determine what default settings are with CSS and to make sure that all possible HTML Elements are included in this HTML so as to not miss any possible Elements when designing a site.
</p>
<p>
Lorem ipsum dolor sit amet, test link adipiscing elit. Nullam dignissim convallis est. Quisque aliquam. Donec faucibus. Nunc iaculis suscipit dui. Nam sit amet sem. Aliquam libero nisi, imperdiet at, tincidunt nec, gravida vehicula, nisl. Praesent mattis, massa quis luctus fermentum, turpis mi volutpat justo, eu volutpat enim diam eget metus. Maecenas ornare tortor. Donec sed tellus eget sapien fringilla nonummy. Mauris a ante. Suspendisse quam sem, consequat at, commodo vitae, feugiat in, nunc. Morbi imperdiet augue quis tellus.
</p>
<p>
Lorem ipsum dolor sit amet, emphasis consectetuer adipiscing elit. Nullam dignissim convallis est. Quisque aliquam. Donec faucibus. Nunc iaculis suscipit dui. Nam sit amet sem. Aliquam libero nisi, imperdiet at, tincidunt nec, gravida vehicula, nisl. Praesent mattis, massa quis luctus fermentum, turpis mi volutpat justo, eu volutpat enim diam eget metus. Maecenas ornare tortor. Donec sed tellus eget sapien fringilla nonummy. Mauris a ante. Suspendisse quam sem, consequat at, commodo vitae, feugiat in, nunc. Morbi imperdiet augue quis tellus.
</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam dignissim convallis est. Quisque aliquam. Donec faucibus. Nunc iaculis suscipit dui. Nam sit amet sem. Aliquam libero nisi, imperdiet at, tincidunt nec, gravida vehicula, nisl. Praesent mattis, massa quis luctus fermentum, turpis mi volutpat justo, eu volutpat enim diam eget metus.
</p>', '2021-05-20', 'ijin.png');
Konfigurasi
Kita lanjutkan dengan menyiapkan atau coding pagination dengan filter pada Codeigniter 4. Pertama-tama jangan lupa koneksi dengan database. Silakan edit file “.env” pada bagian database seperti dibawah ini
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = db_ci4
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
database.default.DBPrefix =
Atau bisa juga edit file “\app\Config\Database.php” pada bagian berikut
/**
* The default database connection.
*
* @var array
*/
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_ci4',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
Catatan
Seting koneksi database disini pilihan, jadi silakan pilih salah satu saja “.env” atau “\app\Config\Database.php”
Kemudian konfigurasi berikutnya adalah “\app\Config\Pager.php”, update pada bagian $template sedemikian rupa sehingga jadi seperti berikut
public $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
'bootstrap-bullet_pagination' => 'App\Views\Pagers\bootstrap-bullet',
];
Template Penomoran Halaman
Script diatas berhubungan dengan letak file dan nama template untuk tampilan pagination. Dengan konfigurasi seperti diatas maka lokasi seperti dibawah ini dengan nama file “bootstrap-bullet.php”, untuk sintak tampilan pagination ada dibawah juga
<?php $pager->setSurroundCount(2); ?>
<ul class="pagination pagination-rounded justify-content-center mt-3 mb-4 pb-1">
<?php
$disabledPrev = $pager->hasPrevious()?'':'disabled';
$disabledNext = $pager->hasNext()?'':'disabled';
?>
<li class="page-item <?= $disabledPrev ?>">
<a class="page-link" href="<?= $pager->getFirst() ?>" aria-label="<?= lang('Pager.first') ?>">
<i class="fa fa-angle-double-left" aria-hidden="true"></i>
</a>
</li>
<li class="page-item <?= $disabledPrev ?>">
<a class="page-link" href="<?= $pager->getPrevious() ?>" aria-label="Previous">
<i class="fa fa-angle-left" aria-hidden="true"></i>
</a>
</li>
<?php
foreach ($pager->links() as $link) {
$activeclass = $link['active']?'active':'';
?>
<li class="page-item <?= $activeclass ?>">
<a class="page-link" href="<?= $link['uri'] ?>" aria-label="Page <?= $link['title'] ?>">
<?= $link['title'] ?>
</a>
</li>
<?php } ?>
<li class="page-item <?= $disabledNext ?>">
<a class="page-link" href="<?= $pager->getNext() ?>" aria-label="Next">
<i class="fa fa-angle-right" aria-hidden="true"></i>
</a>
</li>
<li class="page-item <?= $disabledNext ?>">
<a class="page-link" href="<?= $pager->getLast() ?>" aria-label="<?= lang('Pager.last') ?>">
<i class="fa fa-angle-double-right" aria-hidden="true"></i>
</a>
</li>
</ul>
Model
Kemudian kita hubungkan dengan tabel yang ada didatabase dengan menggunakan model. Sebut saja namanya “NewsModel.php” dengan isi script seperti ini
<?php
namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
protected $table = 'news';
protected $allowedFields =
[
'active'
, 'body'
, 'image'
, 'publish_date'
, 'slug'
, 'title'
];
public function getNews($id = '')
{
if ($id === '')
{
return $this->asObject()
->orderBy('publish_date', 'desc')
->findAll();
}
return $this->asObject()
->where(['id' => $id])
->first();
}
public function getPageSlug($slug = false)
{
return $this->asObject()
->where(['slug' => $slug])
->first();
}
function checkSlug($string){
$str=$string;
$query = "SELECT * from news WHERE slug like '%".$string."%' ";
$data = $this->db->query($query);
$countResult = count($data->getResultArray());
if ($countResult > 0) {
$str=$str.'-'.$countResult;
}
return $str;
}
public function getLatestNews()
{
return $this->asObject()
->orderBy('publish_date', 'desc')
->findAll(1);
}
public function make_query($publish_date, $title, $body)
{
$query = "
SELECT * from news
WHERE 1=1
";
if (isset($body)) {
$body = substr($this->db->escape($body), 1, -1);
$query .= "
AND body like '%".$body."%'
";
}
if (isset($publish_date) && $publish_date !== '') {
$query .= "
AND publish_date='".$publish_date."'
";
}
if (isset($title)) {
$title = substr($this->db->escape($title), 1, -1);
$query .= "
AND title like '%".$title."%'
";
}
return $query;
}
public function fetch_data($limit, $start, $publish_date, $title, $body)
{
$query = $this->make_query($publish_date, $title, $body);
$query .= ' LIMIT '.$start.', '.$limit;
$data = $this->db->query($query);
return $data->getResult();
}
public function count_all($publish_date, $title, $body)
{
$query = $this->make_query($publish_date, $title, $body);
$data = $this->db->query($query);
return count($data->getResultArray());
}
}
Fungsi yang kita gunakan untuk pagination ada tiga yaitu make_query, fetch_data dan count_all. Selebihnya kita akan pakai untuk pengolahan yang lain
Controller
Setelah ini kita akan menampilkan datanya. Buat controller, sebut saja namanya News.php yang scriptnya kurang lebih seperti ini
<?php
namespace App\Controllers;
use App\Models\NewsModel;
class News extends BaseController
{
public function index()
{
return redirect()->to(base_url('/news/list?page=1'));
}
public function list()
{
$pager = \Config\Services::pager();
$model = new NewsModel();
$body = $this->request->getVar('body');
$publish_date = $this->request->getVar('publish_date');
$vartitle = $this->request->getVar('title');
$per_page = 5;
$page = $this->request->getVar('page');
$start = ($page -1) * $per_page;
$data = [
'body' => $body,
'vartitle' => $vartitle,
'publish_date' => $publish_date,
'per_page' => $per_page,
'start' => $start,
'page' => $page,
'pager' => $pager
];
$data['count_all'] = $model->count_all($publish_date, $vartitle, $body);
$data['news'] = $model->fetch_data($per_page, $start < 0 ? 0 : $start, $publish_date, $vartitle, $body);
if($data['count_all']>0 && count($data['news'])===0) {
$page = 1;
$start = ($page -1) * $per_page;
$data['news'] = $model->fetch_data($per_page, $start < 0 ? 0 : $start, $publish_date, $vartitle, $body);
}
$data['start'] = $start;
$data['page'] = $page;
$data['menu'] = 'news';
$data['title'] = 'Berita-berita';
return view('news/index', $data);
}
}
View
Tahap yang paling akhir adalah kita membuat view untuk menampilkan data tersebut “\app\Views\news\index.php”
Isi script index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin 2 - Blank</title>
<!-- Custom fonts for this template-->
<link href="<?= base_url() ?>/assets/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href="<?= base_url() ?>/assets/css/sb-admin-2.min.css" rel="stylesheet">
<!-- Custom styles for this page -->
<link href="<?= base_url() ?>/assets/vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fas fa-newspaper"></i>
</div>
<div class="sidebar-brand-text mx-3">Berita <sup>2</sup></div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Dashboard -->
<li class="nav-item">
<a class="nav-link" href="index.html">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Interface
</div>
<!-- Nav Item - Pages Collapse Menu -->
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo"
aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-fw fa-cog"></i>
<span>Components</span>
</a>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Custom Components:</h6>
<a class="collapse-item" href="buttons.html">Buttons</a>
<a class="collapse-item" href="cards.html">Cards</a>
</div>
</div>
</li>
<!-- Nav Item - Utilities Collapse Menu -->
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseUtilities"
aria-expanded="true" aria-controls="collapseUtilities">
<i class="fas fa-fw fa-wrench"></i>
<span>Utilities</span>
</a>
<div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities"
data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Custom Utilities:</h6>
<a class="collapse-item" href="utilities-color.html">Colors</a>
<a class="collapse-item" href="utilities-border.html">Borders</a>
<a class="collapse-item" href="utilities-animation.html">Animations</a>
<a class="collapse-item" href="utilities-other.html">Other</a>
</div>
</div>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Addons
</div>
<!-- Nav Item - Pages Collapse Menu -->
<li class="nav-item active">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="true"
aria-controls="collapsePages">
<i class="fas fa-fw fa-folder"></i>
<span>Pages</span>
</a>
<div id="collapsePages" class="collapse show" aria-labelledby="headingPages"
data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Login Screens:</h6>
<a class="collapse-item" href="login.html">Login</a>
<a class="collapse-item" href="register.html">Register</a>
<a class="collapse-item" href="forgot-password.html">Forgot Password</a>
<div class="collapse-divider"></div>
<h6 class="collapse-header">Other Pages:</h6>
<a class="collapse-item" href="404.html">404 Page</a>
<a class="collapse-item active" href="blank.html">Blank Page</a>
</div>
</div>
</li>
<!-- Nav Item - Charts -->
<li class="nav-item">
<a class="nav-link" href="charts.html">
<i class="fas fa-fw fa-chart-area"></i>
<span>Charts</span></a>
</li>
<!-- Nav Item - Tables -->
<li class="nav-item">
<a class="nav-link" href="tables.html">
<i class="fas fa-fw fa-table"></i>
<span>Tables</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider d-none d-md-block">
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
</ul>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
<!-- Sidebar Toggle (Topbar) -->
<button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
<i class="fa fa-bars"></i>
</button>
<!-- Topbar Search -->
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-light border-0 small" placeholder="Search for..."
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - Search Dropdown (Visible Only XS) -->
<li class="nav-item dropdown no-arrow d-sm-none">
<a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-search fa-fw"></i>
</a>
<!-- Dropdown - Messages -->
<div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in"
aria-labelledby="searchDropdown">
<form class="form-inline mr-auto w-100 navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-light border-0 small"
placeholder="Search for..." aria-label="Search"
aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</nav>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Berita-berita</h1>
<form class="user">
<input type="hidden" name="page" value="<?= $page; ?>" />
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input name="title"
type="text"
class="form-control form-control-user"
placeholder="Judul Berita" value="<?= $vartitle; ?>"/>
</div>
<div class="col-sm-6">
<input name="publish_date"
type="date"
class="form-control form-control-user"
placeholder="Tanggal Terbit" value="<?= $publish_date; ?>"/>
</div>
</div>
<div class="form-group">
<input name="body"
type="text"
class="form-control form-control-user"
placeholder="Isi Berita" value="<?= $body; ?>"/>
</div>
<div class="col-sm-12">
<button type="submit" class="btn btn-success float-end">Cari Berita</button>
<?= $pager->makeLinks($page, $per_page, $count_all, 'bootstrap-bullet_pagination') ?>
</div>
</form>
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Daftar Berita</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Judul</th>
<th>Slug</th>
<th>Tanggal</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Judul</th>
<th>Slug</th>
<th>Tanggal</th>
</tr>
</tfoot>
<tbody>
<?php foreach($news as $row): ?>
<tr>
<td><?= $row->id; ?></td>
<td><?= $row->title; ?></td>
<td><?= $row->slug; ?></td>
<td><?= $row->publish_date; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © Your Website 2020</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="login.html">Logout</a>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="<?= base_url() ?>/assets/vendor/jquery/jquery.min.js"></script>
<script src="<?= base_url() ?>/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="<?= base_url() ?>/assets/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="<?= base_url() ?>/assets/js/sb-admin-2.min.js"></script>
</body>
</html>
Hasil Akhir
Silakan dijalankan aplikasinya dan buka http://localhost:8080/news. Mudah-mudahan tidak ada error, kurang lebih tampilan seperti ini
Tambahan
Copy-kan folder-folder yang ada didalam template SB Admin 2 ini ke dalam folder public. Untuk merapikan buatkan folder baru sehingga tampilan seperti pada gambar
Selamat mencoba dan semoga berhasil
Mudah-mudahan bermanfaat