Posted by : Aulia Ihza H - 0089
Sunday, June 13, 2021
1.Persiapan
- Mengikuti petunjuk Tugas 6 pada Tugas 6 PBKK - Pengenalan Framework Code Igniter (iniblogspotaulia.blogspot.com)
- Membuka link petunjuk yang ada di Tutorial Codeigniter #5: Cara Membuat Fitur CRUD yang Benar! (petanikode.com)
- dan Tutorial Codeigniter #6: Membuat Fitur Upload File (petanikode.com)
2.Program T6PBKK dengan CRUD
Setelah halaman CV sudah jadi disini kita dapat mengikuti tutorial petanikoding untuk konfigurasi autoload.php dan database.php yang akan disesuaikan dengan database yang kita buat di MySQL, kita akan membuat databasenya terlebih dahulu di database MySQL dengan nama T6PBKK lalu membuat tabelnya menggunakan syntax
CREATE TABLE `portfolios` (
`portfolio_id` varchar(64) NOT NULL,
`portfolio_name` varchar(100) NOT NULL,
`portfolio_category` varchar(30) NOT NULL,
`portfolio_date` date NOT NULL,
`portfolio_desc` varchar(250) NOT NULL,
`portfolio_image` varchar(250) NOT NULL DEFAULT 'default.jpg'
)
dan modelnya di folder Direktori-xampp\htdocs\T6PBKK[nama program]\application\models\Portfolio_model.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Portfolio_model extends CI_Model
{
private $_table = "portfolios";
public $portfolio_id;
public $portfolio_name;
public $portfolio_category;
public $portfolio_date;
public $portfolio_desc;
public $portfolio_image = "default.jpg";
public function rules()
{
return [
['field' => 'portfolio_name',
'label' => 'Portfolio Name',
'rules' => 'required'],
['field' => 'portfolio_date',
'label' => 'Portfolio Date',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->order_by('portfolio_date','ASC')->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["portfolio_id" => $id])->row();
}
public function save()
{
$post = $this->input->post();
$this->portfolio_id = uniqid();
$this->portfolio_name = $post["portfolio_name"];
$this->portfolio_category = $post["portfolio_category"];
$this->portfolio_date = $post["portfolio_date"];
$this->portfolio_desc = $post["portfolio_desc"];
$this->portfolio_image = $this->_uploadImage();
return $this->db->insert($this->_table, $this);
}
public function update()
{
$post = $this->input->post();
$this->portfolio_id = $post["portfolio_id"];
$this->portfolio_name = $post["portfolio_name"];
$this->portfolio_category = $post["portfolio_category"];
$this->portfolio_date = $post["portfolio_date"];
$this->portfolio_desc = $post["portfolio_desc"];
if (!empty($_FILES["portfolio_image"]["name"])) {
print_r($_FILES);
$this->portfolio_image = $this->_uploadImage();
} else {
$this->portfolio_image = $post["old_image"];
}
return $this->db->update($this->_table, $this, array('portfolio_id' => $post['portfolio_id']));
}
public function delete($id)
{
$this->_deleteImage($id);
return $this->db->delete($this->_table, array("portfolio_id" => $id));
}
private function _uploadImage()
{
$config['upload_path'] = './upload/portfolio/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $this->portfolio_id;
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('portfolio_image')) {
return $this->upload->data("file_name");
}
return "default.jpg";
}
private function _deleteImage($id)
{
$portfolio = $this->getById($id);
if ($portfolio->portfolio_image != "default.jpg") {
$filename = explode(".", $portfolio->portfolio_image)[0];
return array_map('unlink', glob(FCPATH."upload/portfolio/$filename.*"));
}
}
}
lalu update welcome.php pada Direktori-xampp\htdocs\T6PBKK[nama program]\application\controller sehingga halaman portfoliouser dapat menerima data(Read)
...
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model("portfolio_model");
$this->load->library('form_validation');
}
...
public function portfoliouser()
{
// fungsi untuk me-load data.php
$data["portfolios"] = $this->portfolio_model->getAll();
$this->load->view('portfoliouser', $data);
}
...
Untuk halaman portofoliouser.php pada Direktori-xampp\htdocs\T6PBKK[nama program]\application\view akan diisi sedemikian rupa dengan header dan footer menyerupai Tugas 6
...
<div class="Title">
<h1>My Portfolio List</h1>
</div>
<div class="subtitle">
<h2>Check it Out</h2>
</div>
<div class="wadah">
<?php foreach ($portfolios as $portfolio): ?>
<div class="part">
<img src="<?php echo base_url('upload/portfolio/'.$portfolio->portfolio_image) ?>">
<div class="details">
<h4><?php echo $portfolio->portfolio_name ?></h4>
<h5>Category : <?php echo $portfolio->portfolio_category ?></h5>
<h6>Date : <?php echo $portfolio->portfolio_date ?></h6>
<p><?php echo $portfolio->portfolio_desc ?></p>
</div>
</div>
<?php endforeach; ?>
</div>
...
menghasilkan
Karena operasi CRUD dalam bentuk tabel akan dipisah dari user view maka akan kita atur melalui admin mengikuti tutorial petani koding dengan modifikasi pada Direktori-xampp\htdocs\T6PBKK[nama program]\controller\admin\Portofolios.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Portfolios extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model("portfolio_model");
$this->load->library('form_validation');
}
public function index()
{
$data["portfolios"] = $this->portfolio_model->getAll();
$this->load->view("admin/portfolio/list", $data);
}
public function add()
{
$portfolio = $this->portfolio_model;
$validation = $this->form_validation;
$validation->set_rules($portfolio->rules());
if ($validation->run()) {
$portfolio->save();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$this->load->view("admin/portfolio/new_form");
}
public function edit($id = null)
{
if (!isset($id)) redirect('admin/portfolios');
$portfolio = $this->portfolio_model;
$validation = $this->form_validation;
$validation->set_rules($portfolio->rules());
if ($validation->run()) {
$portfolio->update();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$data["portfolio"] = $portfolio->getById($id);
if (!$data["portfolio"]) show_404();
$this->load->view("admin/portfolio/edit_form", $data);
}
public function delete($id=null)
{
if (!isset($id)) show_404();
if ($this->portfolio_model->delete($id)) {
redirect(site_url('admin/portfolios'));
}
}
}
Lalu Atur halaman new_form, edit_form,dan list mengikuti petunjuk dengan modifikasi variabel sesuai nama di model.
new_form(Create)
...
<?php if ($this->session->flashdata('success')): ?>
<div class="alert alert-success" role="alert">
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php endif; ?>
<div class="card mb-3">
<div class="card-header">
<a href="<?php echo site_url('admin/portfolios/') ?>"><i class="fas fa-arrow-left"></i> Back</a>
</div>
<div class="card-body">
<form action="<?php echo site_url('admin/portfolios/add') ?>" method="post" enctype="multipart/form-data" >
<div class="form-group">
<label for="portfolio_name">Name*</label>
<input class="form-control <?php echo form_error('portfolio_name') ? 'is-invalid':'' ?>"
type="text" name="portfolio_name" placeholder="Portfolio Name" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_name') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_category">Category</label>
<input class="form-control <?php echo form_error('portfolio_category') ? 'is-invalid':'' ?>"
type="text" name="portfolio_category" placeholder="Portfolio Category" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_category') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_date">Date*</label>
<input class="form-control <?php echo form_error('portfolio_date') ? 'is-invalid':'' ?>"
type="date" name="portfolio_date" placeholder="Portfolio Date" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_date') ?>
</div>
</div>
<div class="form-group">
<label for="name">Photo</label>
<input class="form-control-file <?php echo form_error('portfolio_category') ? 'is-invalid':'' ?>"
type="file" name="image" />
<div class="invalid-feedback">
<?php echo form_error('image') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_desc">Description</label>
<textarea class="form-control <?php echo form_error('portfolio_desc') ? 'is-invalid':'' ?>"
name="portfolio_desc" placeholder="Portfolio description..."></textarea>
<div class="invalid-feedback">
<?php echo form_error('portfolio_desc') ?>
</div>
</div>
<input class="btn btn-success" type="submit" name="btn" value="Save" />
</form>
</div>
</div>
...
edit_form(Update)
...
<?php if ($this->session->flashdata('success')): ?>
<div class="alert alert-success" role="alert">
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php endif; ?>
<!-- Card -->
<div class="card mb-3">
<div class="card-header">
<a href="<?php echo site_url('admin/portfolios/') ?>"><i class="fas fa-arrow-left"></i>
Back</a>
</div>
<div class="card-body">
<form action="" method="post" enctype="multipart/form-data">
<!-- Note: atribut action dikosongkan, artinya action-nya akan diproses
oleh controller tempat vuew ini digunakan. Yakni index.php/admin/portfolios/edit/ID --->
<input type="hidden" name="portfolio_id" value="<?php echo $portfolio->portfolio_id?>" />
<div class="form-group">
<label for="portfolio_name">Name*</label>
<input class="form-control <?php echo form_error('portfolio_name') ? 'is-invalid':'' ?>"
type="text" name="portfolio_name" placeholder="Portfolio Name" value="<?php echo $portfolio->portfolio_name ?>" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_name') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_category">Category</label>
<input class="form-control <?php echo form_error('portfolio_category') ? 'is-invalid':'' ?>"
type="text" name="portfolio_category" placeholder="Portfolio Category" value="<?php echo $portfolio->portfolio_category ?>" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_category') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_date">Date*</label>
<input class="form-control <?php echo form_error('portfolio_date') ? 'is-invalid':'' ?>"
type="date" name="portfolio_date" placeholder="Portfolio Date" value="<?php echo $portfolio->portfolio_date ?>" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_date') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_image">Photo</label>
<input class="form-control-file <?php echo form_error('portfolio_image') ? 'is-invalid':'' ?>"
type="file" name="portfolio_image" />
<input type="hidden" name="old_image" value="<?php echo $portfolio->portfolio_image ?>" />
<div class="invalid-feedback">
<?php echo form_error('portfolio_image') ?>
</div>
</div>
<div class="form-group">
<label for="portfolio_desc">Description</label>
<textarea class="form-control <?php echo form_error('portfolio_desc') ? 'is-invalid':'' ?>"
name="portfolio_desc" placeholder="Portfolio description..."><?php echo $portfolio->portfolio_desc ?></textarea>
<div class="invalid-feedback">
<?php echo form_error('portfolio_desc') ?>
</div>
</div>
<input class="btn btn-success" type="submit" name="btn" value="Save" />
</form>
</div>
</div>
...
list(Read)
...
<!-- DataTables -->
<div class="card mb-3">
<div class="card-header">
<a href="<?php echo site_url('admin/portfolios/add') ?>"><i class="fas fa-plus"></i> Add New</a>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th width="13%">Name</th>
<th width="13%">Category</th>
<th width="13%">Date</th>
<th width="20%">Photo</th>
<th width="20%">Description</th>
<th width="20%">Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($portfolios as $portfolio): ?>
<tr>
<td>
<?php echo $portfolio->portfolio_name ?>
</td>
<td>
<?php echo $portfolio->portfolio_category ?>
</td>
<td>
<?php echo $portfolio->portfolio_date ?>
</td>
<td>
<img src="<?php echo base_url('upload/portfolio/'.$portfolio->portfolio_image) ?>" style="width:80%" />
</td>
<td>
<?php echo substr($portfolio->portfolio_desc, 0, 120) ?>...</td>
<td width="250">
<a href="<?php echo site_url('admin/portfolios/edit/'.$portfolio->portfolio_id) ?>"
class="btn btn-small"><i class="fas fa-edit"></i> Edit</a>
<a onclick="deleteConfirm('<?php echo site_url('admin/portfolios/delete/'.$portfolio->portfolio_id) ?>')"
href="#!" class="btn btn-small text-danger"><i class="fas fa-trash"></i> Hapus</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
...
Untuk halaman list tambahkan line berikut dibagian bawah body untuk menampilkan modal Delete tanpa perlu menginclude atau echo file php baru
...
<!-- Logout Delete Confirmation-->
<div class="modal fade" id="deleteModal" 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">Are you sure?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Data yang dihapus tidak akan bisa dikembalikan.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a id="btn-delete" class="btn btn-danger" href="#">Delete</a>
</div>
</div>
</div>
</div>
<script>
function deleteConfirm(url){
$('#btn-delete').attr('href', url);
$('#deleteModal').modal();
}
</script>
...
Untuk hasil dapat dilihat pada foto berikut ini :
Github : aulkiller/T6PBKK (github.com)