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

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

[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,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

[/sql]

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]

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

}

?>

[/php]

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

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

}

?>

[/php]

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 :

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

[/php]

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

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

[/php]

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

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

[/php]

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 🙂

About the author

gieart administrator

16 Comments so far

Nurhadi JaffarPosted on4:24 pm - Aug 2, 2012

sy tiap kali mau upload gak bs katanya undefinied index : image.
errornya di bagian ini if ($_FILES['image']['error']!= 4) mohon penjelasannya..msh nubie bgt nih..mau upload foto gak bisa2….plisss.

    Gie ArtPosted on3:04 am - Aug 3, 2012

    coba di cek nama form uploadnya.. harusnya nama form uploadnya adalah 'image' , krn $_FILES['image']['error'] itu mengecek form upload dengn nama 'image'. Untk membuat form upload dng nama image kodenya => echo form_upload('image');. Selain itu tipe form nya harus 'open multipart' => echo form_open_multipart('action');

    Nurhadi JaffarPosted on3:28 am - Aug 3, 2012

    msh tetap undefinied index…..
    yg msalah upload itu cuma di bagian controller sm view gak mas???gak ada hubungannya sm model atau ada????

    Gie ArtPosted on7:50 am - Aug 3, 2012

    yang utama di view dan controller.. klo di model cuma nyimpen alamat/path imagenya saja

Nurhadi JaffarPosted on4:29 pm - Aug 2, 2012

sy tiap kali mau upload gak bs katanya undefinied index : image.
errornya di bagian ini if ($_FILES[‘image’][‘error’]!= 4) mohon penjelasannya..msh nubie bgt nih..mau upload foto gak bisa2….plisss.

    gieartPosted on2:59 am - Aug 3, 2012

    coba di cek nama form uploadnya.. harusnya nama form uploadnya adalah ‘image’ , krn $_FILES[‘image’][‘error’] itu mengecek form upload dengn nama ‘image’. Untk membuat form upload dng nama image kodenya => echo form_upload(‘image’);. Selain itu tipe form nya harus ‘open multipart’ => echo form_open_multipart(‘action’);

      Nurhadi JaffarPosted on3:55 am - Aug 3, 2012

      msh tetap undefinied index…..
      yg msalah upload itu cuma di bagian controller sm view gak mas???gak ada hubungannya sm model atau ada????

Friendly’s Medi HalohoPosted on2:31 am - Nov 26, 2012

hay gie.

saya baru belajar CI, saya download online demo, database bisa diimport, tpi pas masuk ke localhost error.
errornya kayak gini mass.

A Database Error Occurred.

Unable to connect to your database server using the provided settings.

Filename: C:xampphtdocsfriendlysystemdatabaseDB_driver.php

Line Number: 124.

Dwi SetiyawanPosted on12:27 pm - Nov 26, 2012

saluut buat mas gienya tapi saya bingung liat codingan mlu ahahahaha pertamax.

Soedjarwo AliPosted on4:50 am - Dec 13, 2012

mas cara setting chmod 777 di windows gmn ya mas? setau saya chmod kan cuma bisa di linux ya? soalnya punya saya error di image path >> " The upload path does not appear to be valid. " atau mungkin ada setingan lain? thanks

Ganang Aris SutignoPosted on1:40 am - Jan 25, 2013

untuk yg ini$data['content'] = 'admin/posts/index'; maksutny gmn ya mas? trus ini 'admin/posts/index'; controller ap view?

Muttaqin NadPosted on10:05 am - Feb 17, 2013

thank u mas ,, berharap bis sperti mas,, lgi bljar CI ,, newbi

Leave a Reply