Website Sekolah CodeIgniter VII : Membuat Admin Modul Categories

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:

[sql]

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 ;

[/sql]

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

[php]

<?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);
}

}

?>

[/php]

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’:

[sql]

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 ;

[/sql]

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

[php]

<?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);
}

}

?>

[/php]

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

[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’);
}
}

}

?>

[/php]

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

[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>

[/php]

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

[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–>

[/php]

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

[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(); ?>

[/php]

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

[php]

<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>

[/php]

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

About the author

gieart administrator

11 Comments so far

sasa_nisaPosted on8:30 am - Jul 4, 2012

ms ni kok ga bisa ya??
yg categories apa belum dibuat homenya?

    gieartPosted on10:51 am - Jul 4, 2012

     gak bisanya knapa mbak nisa? klo yg di demo kyake emang belum tak update.. coba langsung donwload source codenya aja, trus di coba.hehe. trims

newbieCIPosted on9:43 am - Jul 4, 2012

mas kok add categoriesnya keluar ini ? 
A Database Error Occurred
Error Number: 1054
Unknown column ‘permalink’ in ‘field list’
INSERT INTO `categories` (`name`, `permalink`, `description`) VALUES (‘ff’, ‘ff’, ‘sdd’)
Filename: C:xampphtdocsci-projectCIsystemdatabaseDB_driver.php
Line Number: 330

Wisnu ArdhanPosted on8:14 am - Jul 30, 2012

kok tampilan di http://localhost/sman3po/index.php/admin/categories g muncul gan? pdhal di database dah masuk…

Wisnu ArdhanPosted on8:14 am - Jul 30, 2012

kok tampilan di http://localhost/sman3po/index.php/admin/categories g muncul gan? pdhal di database dah masuk…

nindy gadgetPosted on1:34 am - Aug 27, 2012

mas Sugiarto kok ada peringatan seperti ini ya mas?  
Message: Undefined variable: categories
letaknya di index.php yang berhubungan dengan 

Leave a Reply