Kali ini kita akan membahas tentang pagination dengan CodeIgniter. Kita akan menggunakan microblog sederhana sebagai dasar untuk tutorial kali ini. Membuat pagination dalam CodeIgniter sangatlah mudah karena CodeIgniter telah menyediakan pustaka untuk menangani pagination yaitu Pagination Class.
Untuk menggunakan pustaka pagination terlebih dahulu kita harus load pustaka tersebut, setelah itu kita harus mengisi beberapa konfigurasi seperti pada kode 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 | <? class Post extends Controller { function Post() { parent::Controller(); $this->load->model('model_post'); } function index($offset = 0) { if (!empty($_POST)) { $this->model_post->insert(); } $data['post_list'] = $this->model_post->get_latest(10, $offset); $this->load->library('pagination'); $config['base_url'] = site_url("post/index/"); $config['total_rows'] = $this->model_post->count(); $config['per_page'] = '5'; $this->pagination->initialize($config); $data['pagination'] = $this->pagination->create_links(); $this->load->view('post/index', $data); } } |
base_url adalah halaman dimana pagination itu berlaku.
total_rows adalah jumlah keseluruhan post.
per_page menunjukkan jumlah post yang akan ditampilkan dalam 1 page.
Untuk model, kita tambahkan fungsi yang akan mengembalikan jumlah post yang ada dalam database.
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 | <? class Model_Post extends Model { function Model_Post() { parent::Model(); } function get_latest($limit = NULL, $offset = NULL) { $this->db->order_by("date", "desc"); $query = $this->db->get('posts', $limit, $offset); return $query->result(); } function insert() { $this->content = $this->input->post('content'); $this->db->set('date', 'NOW()', false); $this->db->insert('posts', $this); } function count() { return $this->db->count_all_results('posts'); } } |
Dan untuk view kita akan tambahkan sedikit perubahan untuk menampilkan pagination.
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 | <html>
<head>
<title>Membuat Microblog Sederhana Dengan CodeIgniter</html>
</head>
<form method="post" action=".">
<textarea name="content"></textarea>
<br/>
<input type="submit" value="Kirim">
</form>
<? if (isset($post_list)): ?>
<ul>
<? foreach($post_list as $post): ?>
<li>
<? echo $post->content ?><br/>
<? echo $post->date ?>
</li>
<? endforeach ?>
</ul>
<?= $pagination ?>
<? else : ?>
<p>Belum ada post.</p>
<? endif ?>
</html> |
Mudah bukan?
Terus ikuti tutorial-tutorial CodeIgniter lainnya dengan follow komunitaz atau subscribe ke RSS komunitaz.
Related posts:
[post terbaru], Pagination Tutorial Dengan CodeIgniter – http://tinyurl.com/yjunum4
This comment was originally posted on Twitter
tolong jelasin yg lebih detail lg donk mas…key kirik ke email sya adi_matera@yahoo.co.id
ga ada tampilan hasilnya ya mas??
great tutorial..
thank’s..
Ijin coba tutorialnya.. kalo gag bisa balik lagi nih ntar…
Mohon bantuannya yah:D