Website Sekolah CodeIgntier IX: Menampilkan Posts di halaman depan (front page)

Heii bro n sista,

Emm.. mau ngucapin selamat menjalankan ibadah puasa ramadhan dulu ah.. bagi yng menjalankan. Smoga lancar dn semua ibadah kita di terima Allah. amiin :D

Okey.. kali ini aku akan lanjutin tutorial web sekolahnya tentang bagaimana menampilkan ‘Posts’ di halaman depan (front page).

Let’s Go !!

Sebelumnya kita telah mempunya controller ‘Pages’  utk bagian front yg tersimpan pada controllers/pages.php dan di dalamnya terdapat fungsi home(), nah kita akan memodifikasi fungsi ini agar bisa menampilkan ‘Posts’ di halaman depan. Okey, ubah controller ‘Pages’ (controller/pages.php) menjadi seperti berikut (di replace aja code seblumnya):

<?php


class Pages extends CI_Controller {

var $template = 'template';

function __construct() {
parent::__construct();
$this->load->model('Posts_model');
}

function home() {
$data['posts'] = $this->Posts_model->findActive(5);
$data['page'] = 'pages/home';
$this->load->view($this->template, $data);
}

}

?>


Selanjutnya modifikasi juga view ‘home’ yang ada di views/pages/home.php menjadi seperti berikut:


<div><img src="<?php echo base_url(); ?>public/images/img06.jpg" alt="" width="510" height="250" /></div>
<?php if (!empty($posts)): ?>
<?php foreach ($posts as $post): ?>
<div>
<h1><a href="<?php echo site_url('posts/detail/' . $post['permalink']); ?>"><?php echo $post['title'] ?></a></h1>
<p><small><?php echo $post['created']; ?> by <a href="#"><?php echo $post['username']; ?></a></small></p>
<div>
<?php if (!empty($post['image'])): ?>
<img src="<?php echo base_url() . $post['image'] ?>" width="510" height="250"/>
<?php endif; ?>
<?php echo word_limiter($post['body'], 30); ?><br/>
<?php echo anchor('posts/detail/' . $post['permalink'], 'baca selengkapnya..'); ?>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>

Oh iya.. di view di atas dipanggil fungsi word_limiter yang ada pada helper “text” utk membatasi jumlah kata. Utk menggunakan itu kita harus mengaktifkan helpernya, bisa di panggil di autoload (config/autoload.php) dgn baris berikut:


$autoload['helper'] = array('url','form','tinymce','text');

Sampe di sini klo skrg kita akses localhost/sekolahku maka akan ditampilkan ‘Posts’ di halaman depan.

Selanjutnya adalah kita akan membuat tampilan detail dari artikel / posts tersebut kita di klik linknya. Maka pertama kita akan membuat controller Posts  dan simpen padacontrollers/posts.php kemudian ketikan kode berikut ini:


<?php

class Posts extends CI_Controller {

var $template = 'template';

function __construct() {
parent::__construct();
$this->load->model('Posts_model');
}

function detail($permalink = null) {
if ($permalink == null) {
redirect('pages/home');
}
$data['post'] = $this->Posts_model->findByPermalink($permalink);

$data['page'] = 'posts/detail';
$this->load->view($this->template, $data);
}

}

?>


Kemudian terakhir kita buat view ‘detail’ dan simpan pada views/posts/detail.php dan ketikan kode program seperti berikut:

<?php if (!empty($post)): ?>

<div>
<h1><?php echo $post['title'] ?></h1>
<p><small><?php echo $post['created']; ?></small></p>
<div>
<?php if (!empty($post['image'])): ?>
<img src="<?php echo base_url() . $post['image'] ?>" width="510" height="250"/>
<?php endif; ?>
<?php echo $post['body'] ?><br/>

</div>
</div>

<?php endif; ?>

Selesaaiiii… selamat mencoba :D

DOWNLOAD FULL SOURCE CODE | ONLINE DEMO

Website Sekolah CodeIgniter VIII: Membuat Admin Modul Posts (with upload Image)

Hey mas bro.. and mbak sist

Aku lagi lumayan semangat nulis nih.. utk melanjutkan tutorial Membuat Website Sekolah dengan CodeIgniter.. haha. Postingan seblumya kita udah bahas tentang Modul Categories, utk kali ini aku akan menulis tentang membuat Admin Modul Posts. Modul ini terkait (berelasi) dengan modul Categories, karena setiap ‘Post’ akan masuk dalam ‘Category’ tertentu. Pada prinsipnya tetep sama menggunakan konsep CRUD, cuma ada tambahan untuk Upload Image / Foto yang nantinya akan ditampilkan dalam artikel tersebut.

Okey.. Let’s Go!!

Buat tabel ‘posts’ dengan SQL berikut (klo blum buat):


CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`permalink` varchar(255) NOT NULL,
`body` text NOT NULL,
`image` varchar(255) NOT NULL,
`status` tinyint(4) NOT NULL,
`categories_id` int(11) NOT NULL,
`users_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Buat Model  “Posts_model” dan simpan pada application/models/posts_model.php , kemudian ketikan kode berikut (note: jika sudah ad model post model, kodenya di replace semua aja) :


<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Posts_model extends CI_Model {

var $table = 'posts';
 var $status = array(
 0 => 'draft',
 1 => 'published'
 );

function __construct() {
 parent::__construct();
 }

function findAll($limit = null, $offset = null, $q = null) {
 $this->db->select('posts.*,categories.name, users.username');
 $this->db->join('categories', 'categories.id = posts.categories_id');
 $this->db->join('users', 'users.id = posts.users_id');
 if ($q != null) {
 $this->db->like('title', $q);
 }
 $this->db->limit($limit, $offset);
 $this->db->order_by('id', 'desc');
 $query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
 return $query->result_array();
 }
 }

function findActive($limit = null, $offset = null, $q = null) {
 $this->db->select('posts.*,categories.name, users.username');
 $this->db->join('categories', 'categories.id = posts.categories_id');
 $this->db->join('users', 'users.id = posts.users_id');
 if ($q != null) {
 $this->db->like('posts.title', $q);
 $this->db->or_like('posts.body', $q);
 }
 $this->db->limit($limit, $offset);
 $this->db->where('posts.status', 1);
 $this->db->order_by('id', 'desc');
 $query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
 return $query->result_array();
 }
 }

function findByCategoryId($categories_id, $limit = null, $offset = null) {
 $this->db->select('posts.*,categories.name, users.username');
 $this->db->join('categories', 'categories.id = posts.categories_id');
 $this->db->join('users', 'users.id = posts.users_id');
 $this->db->limit($limit, $offset);
 $this->db->where('posts.status', 1);
 $this->db->where('posts.categories_id', $categories_id);
 $this->db->order_by('id', 'desc');
 $query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
 return $query->result_array();
 }
 }

function findOthersInCategory($categories_id, $article_id, $limit = null, $offset = null) {
 $this->db->select('posts.*,categories.name, users.username');
 $this->db->join('categories', 'categories.id = posts.categories_id');
 $this->db->join('users', 'users.id = posts.users_id');
 $this->db->where('posts.categories_id', $categories_id);
 $this->db->where('posts.id !=', $article_id);
 $this->db->limit($limit, $offset);
 $this->db->where('posts.status', 1);
 $this->db->order_by('id', 'desc');
 $query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
 return $query->result_array();
 }
 }

function findById($id) {
 $this->db->select('posts.*');
 $this->db->where('id', $id);
 $query = $this->db->get($this->table, 1);

if ($query->num_rows() == 1) {
 return $query->row_array();
 }
 }

function findByPermalink($permalink) {
 $this->db->select('posts.*');
 $this->db->where('permalink', $permalink);
 $query = $this->db->get($this->table, 1);

if ($query->num_rows() == 1) {
 return $query->row_array();
 }
 }

function countAll() {
 $query = $this->db->get($this->table);
 return $query->num_rows();
 }

function create($params = array()) {
 if (empty($params)) {
 $data = array(
 'title' => $this->input->post('title'),
 'permalink' => url_title($this->input->post('title')),
 'body' => $this->input->post('body'),
 'categories_id' => $this->input->post('categories_id'),
 'status' => $this->input->post('status'),
 'users_id' => $this->session->userdata('id'),
 'created' => date("Y-m-d H:i:s")
 );
 $this->db->insert($this->table, $data);
 } else {
 $this->db->insert($this->table, $params);
 }
 }

function update($id, $params) {
 if (empty($params)) {
 $data = array(
 'title' => $this->input->post('title'),
 'permalink' => url_title($this->input->post('title')),
 'body' => $this->input->post('body'),
 'categories_id' => $this->input->post('categories_id'),
 'status' => $this->input->post('status'),
 'users_id' => $this->session->userdata('id'),
 'modified' => date("Y-m-d H:i:s")
 );

$this->db->where('id', $id);
 $this->db->update($this->table, $data);
 } else {
 $this->db->where('id', $id);
 $this->db->update($this->table, $params);
 }
 }

function destroy($id) {
 $this->db->where('id', $id);
 $this->db->delete($this->table);
 }

}

?>

Buat Controller “Posts” dan simpan pada application/controllers/posts.php :


<?php

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class Posts extends CI_Controller {

var $template = 'admin/template';
var $imagePath = 'public/media/posts/';
var $status = array(
0 => 'draft',
1 => 'published'
);

function __construct() {
parent::__construct();
$this->general->checkAdmin();
$this->load->model('Posts_model');
$this->load->model('Categories_model');
}

function index($page = null) {

$this->load->library('pagination');
$config['uri_segment'] = 4;
$config['total_rows'] = $this->Posts_model->countAll();
$config['per_page'] = 10;
$config['base_url'] = base_url() . 'admin/posts/index/';

if ($this->input->get('q')):
$q = $this->input->get('q');
$data['posts'] = $this->Posts_model->findAll($config['per_page'], $this->uri->segment(4), $q);
if (empty($data['posts'])) {
$this->session->set_flashdata('error', 'Data tidak ditemukan');
redirect('admin/posts/index');
}
$config['total_rows'] = count($data['posts']);
else:
$data['posts'] = $this->Posts_model->findAll($config['per_page'], $this->uri->segment(4));
endif;
$this->pagination->initialize($config);
$data['status'] = $this->status;
$data['pagination'] = $this->pagination->create_links();
$data['content'] = 'admin/posts/index';
$this->load->view($this->template, $data);
}

function add() {

$this->form_validation->set_rules('title', 'title', 'required|xss_clean');
$this->form_validation->set_rules('body', 'body', 'required|xss_clean');
$this->form_validation->set_rules('categories_id', 'category', 'required|xss_clean');
$this->form_validation->set_rules('status', 'status', 'required|xss_clean');
$this->form_validation->set_error_delimiters('', '<br/>');
if ($this->form_validation->run() == TRUE) {

$params = array(
'title' => $this->input->post('title'),
'permalink' => url_title($this->input->post('title')),
'body' => $this->input->post('body'),
'categories_id' => $this->input->post('categories_id'),
'status' => $this->input->post('status'),
'users_id' => $this->session->userdata('id'),
'created' => date("Y-m-d H:i:s")
);
if ($_FILES['image']['error'] != 4) {
$config['upload_path'] = $this->imagePath;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '200000';
$this->load->library('upload', $config);

if ($this->upload->do_upload("image")) {
$image = $this->upload->data();
$params['image'] = $this->imagePath . $image['file_name'];
}
}

$this->Posts_model->create($params);
$this->session->set_flashdata('success', 'Post created');
redirect('admin/posts');
}
$data['categories'] = $this->Categories_model->findList();
$data['status'] = $this->Posts_model->status;
$data['content'] = 'admin/posts/add';
$this->load->view($this->template, $data);
}

function edit($id = null) {

if ($id == null) {
$id = $this->input->post('id');
}
$this->form_validation->set_rules('title', 'title', 'required|xss_clean');
$this->form_validation->set_rules('body', 'body', 'required|xss_clean');
$this->form_validation->set_rules('categories_id', 'category', 'required|xss_clean');
$this->form_validation->set_rules('status', 'status', 'required|xss_clean');
$this->form_validation->set_error_delimiters('', '<br/>');
if ($this->form_validation->run() == TRUE) {

$params = array(
'title' => $this->input->post('title'),
'permalink' => url_title($this->input->post('title')),
'body' => $this->input->post('body'),
'categories_id' => $this->input->post('categories_id'),
'status' => $this->input->post('status'),
'users_id' => $this->session->userdata('id'),
'created' => date("Y-m-d H:i:s")
);
if ($_FILES['image']['error'] != 4) {
$config['upload_path'] = $this->imagePath;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '200000';
$this->load->library('upload', $config);

if ($this->upload->do_upload("image")) {
$image = $this->upload->data();
$params['image'] = $this->imagePath . $image['file_name'];
}
}

$this->Posts_model->update($id, $params);
$this->session->set_flashdata('success', 'Post edited');
redirect('admin/posts');
}

$data['post'] = $this->Posts_model->findById($id);
$data['categories'] = $this->Categories_model->findList();
$data['status'] = $this->status;
$data['content'] = 'admin/posts/edit';
$this->load->view($this->template, $data);
}

function delete($id = null) {
if ($id == null) {
$this->session->set_flashdata('error', 'Invalid post');
redirect('admin/posts');
} else {
$post = $this->Posts_model->findById($id);
if (file_exists($post['image'])) {
unlink($post['image']);
}
$this->Posts_model->destroy($id);
$this->session->set_flashdata('success', 'Post deleted');
redirect('admin/posts');
}
}

}

?>

Pada controller di atas terdapat kode program untuk upload image/foto. Image ato foto tersebut akan disimpan pada folder sesuai yang didefinisikan -> var $imagePath = ‘public/media/posts/’; Sehingga kita perlu buat folder media  dalam folder public, kemudian buat folder posts di dalam folder media. Serta jangan lupa permissionnya di set 777 (chmod 777).

Next, buat view index.php dan simpan pada application/views/admin/posts/index.php :


<h3>List Posts</h3>
<?php echo anchor('admin/posts/add', 'Add'); ?><br/>
<?php if ($this->session->flashdata('success')): ?>
<i><?php echo $this->session->flashdata('success'); ?><i/>
<?php endif; ?>
<?php if ($this->session->flashdata('error')): ?>
<i><?php echo $this->session->flashdata('error'); ?><i/>
<?php endif; ?>
<table border="1">
<tr>
<td>No</td>
<td>Image</td>
<td>Title</td>
<td>Category</td>
<td>Status</td>
<td>User</td>
<td>Action</td>
</tr>
<?php if (!empty($posts)): ?>
<?php $no = 1; ?>
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $no; ?></td>
<td><img src="<?php echo base_url().$post['image']; ?>" width="100" height="100"/></td>
<td><?php echo $post['title']; ?></td>
<td><?php echo $post['name']; ?></td>
<td><?php echo $status[$post['status']]; ?></td>
<td><?php echo $post['username']; ?></td>
<td>
<a href="<?php echo site_url('admin/posts/edit/' . $post['id']); ?>">Edit</a> |
<a href="<?php echo site_url('admin/posts/delete/' . $post['id']); ?>" onclick=" return confirm('Are you sure?')">Delete</a>
</td>
</tr>
<?php $no++; ?>
<?php endforeach; ?>
<?php endif; ?>

</table>

Next, buat view add.php dan simpan pada application/views/admin/posts/add.php :


<?php
echo initialize_tinymce();
?>
<h3>Add Post</h3><br/>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/posts/add'); ?>
Title :<br/>
<?php echo form_input(array('name' => 'title', 'value' => set_value('title', isset($page['title']) ? $page['title'] : ''))); ?><br/>
Body :<br/>
<?php echo form_textarea(array('name' => 'body', 'value' => set_value('title', isset($page['body']) ? $page['body'] : ''))); ?><br/>
Category:<br/>
<?php echo form_dropdown('categories_id',$categories);?><br/>
Image : <br/>
<?php echo form_upload('image');?><br/>
Status:<br/>
<?php echo form_dropdown('status', $status, isset($page['status']) ? $page['status'] : ''); ?><br/>
<?php echo form_submit('submit', 'Save'); ?>

<?php echo form_close(); ?>

Next, buat view edit.php dan simpan pada application/views/admin/posts/edit.php:


<h3>Edit Page</h3><br/>
<?php echo initialize_tinymce(); ?>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/posts/edit'); ?>

<?php echo form_hidden('id', $post['id']); ?>
Title :<br/>
<?php echo form_input(array('name' => 'title', 'value' => set_value('title', isset($post['title']) ? $post['title'] : ''))); ?><br/>
Body :<br/>
<?php echo form_textarea(array('name' => 'body', 'value' => set_value('title', isset($post['body']) ? $post['body'] : ''))); ?><br/>
Category:<br/>
<?php echo form_dropdown('categories_id', $categories,$post['categories_id']); ?><br/>
Current Image : <br/>
<img src="<?php echo base_url().$post['image'];?>" width="150" height="150"/><br/>
Image : <br/>
<?php echo form_upload('image'); ?><br/>
Status:<br/>
<?php echo form_dropdown('status', $status, isset($post['status']) ? $post['status'] : ''); ?><br/>
<?php echo form_submit('submit', 'Save'); ?>

<?php echo form_close(); ?>

Okey… saatnya uji coba.. dan taraaaaaaaaaaa hasilnya sperti gambar berikut:

Modul Posts

Modul Posts

DOWNLOAD FULL SOURCE CODE | ONLINE DEMO

Eh tapi sorry ya guys.. nulis tutorialnya maen next2 aja.. habis klo mo dijelasin detailnya pegel juga.haha , ntar klo butuh penjelasan kita interaktif aja via Komentar dibawah :D , okey. Semoga bermanfaat :)

Testing Fitur Twitter Embed pada WordPress 3.4.1

Website Sekolah CodeIgniter VII : Membuat Admin Modul Categories

Hei guys..

Postingan ini merupakan lanjutan dari tutorial membuat website sekolah dengan CodeIgniter. Pada postingan sebelumnya telah dibahas tentang Menambahkan Editor TinyMce . Kali ini kita akan membuat admin modul Categories. Pada prinsipnya modul ini cuma menerapkan prinsip insert,update,delete seperti biasa dan mirip dengan Admin Modul Pages yang telah kita buat sebelumnya. Sehingga tidak perlu dibahas lebih detail lagi.

Okey.. pertama buat tabel di MySQL dengan nama ‘categories’ yang memiliki field (id,name,permalink,description). Anda bisa membuat tabelnya dengan SQL berikut ini:


CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`permalink` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Kedua, Buat model dengan nama ‘Categories_model’ dan simpan pada application/models/categories_model.php dan ketikan kode program seperti berikut ini:


<?php

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class Categories_model extends CI_Model {

var $table = 'categories';

function __construct() {
parent::__construct();
}

function findAll($limit =null, $offset = null) {
$this->db->select('*');
$this->db->limit($limit, $offset);
$this->db->order_by('name','ASC');
$query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
return $query->result_array();
}
}

function findList() {

$query = $this->db->get($this->table);
$data = array();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[$row['id']] = $row['name'];
}
}
return $data;
}

function findById($id) {
$this->db->select('*');
$this->db->where('id', $id);
$query = $this->db->get($this->table, 1);

if ($query->num_rows() == 1) {
return $query->row_array();
}
}

function findByPermalink($permalink) {
$this->db->select('*');
$this->db->where('permalink', $permalink);
$query = $this->db->get($this->table, 1);

if ($query->num_rows() == 1) {
return $query->row_array();
}
}

function create() {
$data = array(
'name' => $this->input->post('name'),
'permalink' => url_title($this->input->post('name')),
'description' => $this->input->post('description')
);

$this->db->insert($this->table, $data);
}

function update($id) {

$data = array(
'name' => $this->input->post('name'),
'permalink' => url_title($this->input->post('name')),
'description' => $this->input->post('description')
);

$this->db->where('id', $id);
$this->db->update($this->table, $data);
}

function destroy($id) {
$this->db->where('id', $id);
$this->db->delete($this->table);
}

}

?>

Karena categories ini nantinya akan mempunya relasi dengan posts, maka kita akan buat sekalian tabel dan model utk posts. Berikut ini SQL utk membuat tabel ‘posts’:


CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`permalink` varchar(255) NOT NULL,
`body` text NOT NULL,
`image` varchar(255) NOT NULL,
`status` tinyint(4) NOT NULL,
`categories_id` int(11) NOT NULL,
`users_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Kemudian buat model ‘Post_model’ dan simpan pada application/models/posts_model.php kemudian ketikan kode berikut:


<?php

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class Posts_model extends CI_Model {

var $table = 'posts';
var $status = array(
0 => 'draft',
1 => 'published'
);

function __construct() {
parent::__construct();
}

function findAll($limit = null, $offset = null, $q = null) {
$this->db->select('posts.*,categories.name, users.username');
$this->db->join('categories', 'categories.id = posts.categories_id');
$this->db->join('users', 'users.id = posts.users_id');
if ($q != null) {
$this->db->like('title', $q);
}
$this->db->limit($limit, $offset);
$this->db->order_by('id', 'desc');
$query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
return $query->result_array();
}
}

function findActive($limit = null, $offset = null, $q = null) {
$this->db->select('posts.*,categories.name, users.username');
$this->db->join('categories', 'categories.id = posts.categories_id');
$this->db->join('users', 'users.id = posts.users_id');
if ($q != null) {
$this->db->like('posts.title', $q);
$this->db->or_like('posts.body', $q);

}
$this->db->limit($limit, $offset);
$this->db->where('posts.status', 1);
$this->db->order_by('id', 'desc');
$query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
return $query->result_array();
}
}

function findByCategoryId($categories_id, $limit = null, $offset = null) {
$this->db->select('posts.*,categories.name, users.username');
$this->db->join('categories', 'categories.id = posts.categories_id');
$this->db->join('users', 'users.id = posts.users_id');
$this->db->limit($limit, $offset);
$this->db->where('posts.status', 1);
$this->db->where('posts.categories_id', $categories_id);
$this->db->order_by('id', 'desc');
$query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
return $query->result_array();
}
}

function findPreviousposts($limit = null, $offset = null, $postsIds = null) {
$this->db->select('posts.*,categories.name, users.username');
$this->db->join('categories', 'categories.id = posts.categories_id');
$this->db->join('users', 'users.id = posts.users_id');
$this->db->where_not_in('posts.id', $postsIds);
$this->db->limit($limit, $offset);
$this->db->where('posts.status', 1);
$this->db->order_by('id', 'desc');
$query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
return $query->result_array();
}
}

function findOthersInCategory($categories_id, $article_id, $limit = null, $offset = null) {
$this->db->select('posts.*,categories.name, users.username');
$this->db->join('categories', 'categories.id = posts.categories_id');
$this->db->join('users', 'users.id = posts.users_id');
$this->db->where('posts.categories_id', $categories_id);
$this->db->where('posts.id !=', $article_id);
$this->db->limit($limit, $offset);
$this->db->where('posts.status', 1);
$this->db->order_by('id', 'desc');
$query = $this->db->get($this->table);

if ($query->num_rows() > 0) {
return $query->result_array();
}
}

function findById($id) {
$this->db->select('posts.*');
$this->db->where('id', $id);
$query = $this->db->get($this->table, 1);

if ($query->num_rows() == 1) {
return $query->row_array();
}
}

function findByPermalink($permalink) {
$this->db->select('posts.*');
$this->db->where('permalink', $permalink);
$query = $this->db->get($this->table, 1);

if ($query->num_rows() == 1) {
return $query->row_array();
}
}

function countAll() {
$query = $this->db->get($this->table);
return $query->num_rows();
}

function create() {
$data = array(
'title' => $this->input->post('title'),
'permalink' => url_title($this->input->post('title')),
'body' => $this->input->post('body'),
'categories_id' => $this->input->post('categories_id'),
'status' => $this->input->post('status'),
'users_id' => $this->session->userdata('id'),
'created' => date("Y-m-d H:i:s")
);

$this->db->insert($this->table, $data);
}

function update($id) {

$data = array(
'title' => $this->input->post('title'),
'permalink' => url_title($this->input->post('title')),
'body' => $this->input->post('body'),
'categories_id' => $this->input->post('categories_id'),
'status' => $this->input->post('status'),
'users_id' => $this->session->userdata('id'),
'modified' => date("Y-m-d H:i:s")
);

$this->db->where('id', $id);
$this->db->update($this->table, $data);
}

function destroy($id) {
$this->db->where('id', $id);
$this->db->delete($this->table);
}

}

?>

Membuat controller categories (application/controlles/admin/categories.php):


<?php

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class Categories extends CI_Controller {

var $template = 'admin/template';

function __construct() {
parent::__construct();
$this->general->checkAdmin();
$this->load->model('Categories_model');
$this->load->model('Posts_model');

}

function index() {
$data['categories'] = $this->Categories_model->findAll();
$data['content'] = 'admin/categories/index';
$this->load->view($this->template, $data);
}

function add() {
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_error_delimiters('', '<br/>');

if ($this->form_validation->run() == TRUE) {
$this->Categories_model->create();
$this->session->set_flashdata('success', 'Category created');
redirect('admin/categories');
}
$data['content'] = 'admin/categories/add';
$this->load->view($this->template, $data);
}

function edit($id = null) {
if ($id == null) {
$id = $this->input->post('id');
}

$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_error_delimiters('', '<br/>');

if ($this->form_validation->run() == TRUE) {
$this->Categories_model->update($id);
$this->session->set_flashdata('success', 'Category edited');
redirect('admin/categories');
}
$data['category'] = $this->Categories_model->findById($id);
$data['content'] = 'admin/categories/edit';
$this->load->view($this->template, $data);
}

function delete($id = null) {
if ($id == null) {
$this->session->set_flashdata('error', 'Invalid category');
redirect('admin/categories');
} else {
$articles = $this->Posts_model->findByCategoryId($id);
if (!empty($articles)) {
$this->session->set_flashdata('error', 'This category could not deleted cause have some articles');
} else {
$this->Categories_model->destroy($id);
$this->session->set_flashdata('success', 'Category deleted');
}
redirect('admin/categories');
}
}

}

?>

Membuat view index  (application/views/admin/categories/index.php):


<h3>Categories</h3>
<?php echo anchor('admin/categories/add', 'Add'); ?><br/>

<?php if ($this->session->flashdata('success')): ?>

<?php echo $this->session->flashdata('success'); ?>
<?php endif; ?>
<?php if ($this->session->flashdata('error')): ?>

<?php echo $this->session->flashdata('error'); ?>
<?php endif; ?>

<table cellpadding="0" cellspacing="0" border="1">
<tr>
<th>Name</th>
<th>Description</th>
<th>Action</th>
</tr>
<?php if ($categories): ?>
<?php foreach ($categories as $category): ?>
<tr>
<td><?php echo $category['name']; ?></td>
<td><?php echo $category['description']; ?></td>
<td>
<a href="<?php echo site_url('admin/categories/edit/' . $category['id']) ?>">Edit</a> |
<a href="<?php echo site_url('admin/categories/delete/' . $category['id']) ?>" onclick="return confirm('Anda yakin akan menghapus ini?');">Hapus</a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</table>

Membuat view add (application/views/admin/categories/add.php):


<h3>Add Category</h3><br/>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/categories/add'); ?>
Name : <br/>
<?php echo form_input(array('name' => 'name', 'value' => set_value('name'))); ?><br/>
Description: <br/>
<?php echo form_textarea(array('name' => 'description', 'value' => set_value('description'))); ?>
<br/>
<input type="submit" value="Submit"/>
<?php echo form_close(); ?>

<!--end #article-->

Membuat view edit (application/views/admin/categories/edit.php):


<h3>Edit Category</h3><br/>
<?php echo validation_errors();?><br/>
<?php echo form_open_multipart('admin/categories/edit'); ?>
<?php echo form_hidden('id', $category['id']) ?>
Name : <br/>
<?php echo form_input(array('name' => 'name', 'value' => set_value('name', isset($category['name']) ? $category['name'] : ''))); ?><br/>
Description : <br/>
<?php echo form_textarea(array('name' => 'description', 'value' => set_value('description', isset($category['description']) ? $category['description'] : ''))); ?><br/>

<input type="submit" value="Submit"/>
<?php echo form_close(); ?>

Sekarang tambahkan menu pada header yang terletak pada file application/views/admin/template.php, sehingga file template.php menjadi seperti berikut:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Admin Panel Sekolahku</title>
<meta name="keywords" content="" />
<meta name="Premium Series" content="" />

</head>
<body>
<table>
<tr>
<td>
<h2>Admin Panel</h2>
</td>
</tr>
<tr>
<td>
<?php echo anchor('admin/pages', 'Pages') ?> |
<?php echo anchor('admin/categories', 'Categories') ?> |
<?php echo anchor('users/logout', 'Logout') ?>
<hr/>
</td>
</tr>
<tr>
<td>
<?php if (!empty($content)): ?>
<?php $this->load->view($content); ?>
<?php endif; ?>
</td>
</tr>
<tr>
<td>
<hr/>
Admin Panel Sekolahku
</td>
</tr>
</table>
</body>
</html>

Okey.. skrg saatnya melakukan uji coba. silahkan login dengan akun admin kemudian klik menu ‘Categories’ atau ketika url http://localhost/sekolahku/admin/categories/ , jika tidak ada kesalahan maka akan tampil seperti berikut:

modul admin categories

modul admin categories

DOWNLOAD FULL SOURCE CODE | ONLINE DEMO

Plugin from the creators of Brindes :: More at Plulz Wordpress Plugins