1. Membuat Database
masuk kedalam database daily_codeigniter kemudian masukan query sql dibawah ini untuk membuat tablenya :
CREATE TABLE `tb_biodata` (
`id` int(255) NOT NULL,
`name` varchar(255) NOT NULL,
`gender` enum('Male','Female') NOT NULL,
`birthday` date NOT NULL,
`photo` varchar(255) NOT NULL,
`hobby` varchar(255) NOT NULL,
`about` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tb_biodata`
--
ALTER TABLE `tb_biodata`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `tb_biodata`
--
ALTER TABLE `tb_biodata`
MODIFY `id` int(255) NOT NULL AUTO_INCREMENT;
2. Membuat Controller
- buat file controllers dengan nama Crud_Multiple.php didalam folder app maka pathnya adalah application/controllers/app/Crud_Multiple.php
- kemudian isi dengan kode dibawah ini :
<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class Crud_Multiple extends MY_App
{
private $redirect = 'app/crud_multiple';
private $redirect_create = 'app/crud_multiple/create';
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('app/M_Crud_Multiple');
}
public function index()
{
$data = [
'title' => 'Module Crud',
'biodata' => $this->M_Crud_Multiple->read(),
];
$this->load->view('app/crud_multiple/index',$data);
}
public function create()
{
$data = [
'title' => 'Create Data',
'update' => false,
];
/**
* check if count form > 100
*/
if ($this->input->get('form')) {
if ($this->input->get('form') > 100) {
$this->session->set_flashdata('validation', 'Form limited 100');
redirect($this->redirect_create);
exit;
}elseif (!is_numeric($this->input->get('form'))) {
$this->session->set_flashdata('validation', 'Error Create Form, Parameter not interger');
redirect($this->redirect_create);
exit;
}
}
$this->load->view('app/crud_multiple/form',$data);
}
public function process_create()
{
$create = $this->M_Crud_Multiple->create_multiple();
if ($create == TRUE) {
$this->session->set_flashdata('create', true);
}
else {
$this->session->set_flashdata('create', 'failed');
}
redirect($this->redirect);
}
public function update($id = false)
{
$data = [
'title' => 'Update Data',
'update' => true,
'biodata' => $this->M_Crud_Multiple->read_multiple($id),
];
$this->load->view('app/crud_multiple/form',$data);
}
public function process_update()
{
if ($this->M_Crud_Multiple->update_multiple() == TRUE) {
$this->session->set_flashdata('edit', true);
}else {
$this->session->set_flashdata('edit', 'failed');
}
redirect($this->redirect);
}
public function process_delete()
{
if ($this->M_Crud_Multiple->delete_batch() == TRUE) {
$this->session->set_flashdata('delete', true);
}else {
$this->session->set_flashdata('delete', 'failed');
}
redirect($this->redirect);
}
}
?>
3. Membuat Model
- Dilanjut membuat file model dengan nama M_Crud_Multiple.php didalam folder app (buat folder app terlebih dahulu) maka pathnya adalah application/models/app/M_Crud_Multiple.php
- kemudian isi dengan kode dibawah ini :
<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class M_Crud_Multiple extends CI_Model
{
private $table = 'tb_biodata';
private $storage_path = 'storage/uploads/';
/**
* Form Process
*/
public function _form_data($identity = false)
{
foreach ($this->input->post('name') as $key => $x) {
$this->_form_validation($key);
$prepare_data = array(
'name' => $this->input->post('name')[$key],
'gender' => $this->input->post('gender')[$key],
'birthday' => date('Y-m-d', strtotime($this->input->post('birthday')[$key])),
'hobby' => $this->input->post('hobby')[$key],
'about' => $this->input->post('about')[$key],
);
if ($identity) {
$id = array('id' => $this->input->post('id')[$key]);
$prepare_data = array_merge($prepare_data,$id);
}
if (!empty($_FILES['photo']['name'][$key]))
{
$upload_image = $this->__upload_file($key);
if ($upload_image !== 'failed')
{
if ($identity)
{
$delete_image = $this->db->get_where($this->table,$id)->row_array();
$this->__delete_file($delete_image['photo']);
}
$photo = $upload_image;
/**
* temp upload_image (succes uploaded)
*/
$tmp_file[] = $upload_image;
}else {
/**
* if upload image failed, delete all previous file
*/
if (!empty($tmp_file)) {
$this->__delete_file($tmp_file,true);
}
$this->session->set_flashdata('validation','Oops... Failed Upload Photo.');
redirect($_SERVER['HTTP_REFERER']);
}
$photo = array('photo' => $photo);
}else {
$photo = array('photo' => $this->input->post('photo_old')[$key]);
}
$data[] = array_merge($prepare_data,$photo);
}
return $data;
}
public function _form_validation($key)
{
$this->form_validation->set_rules("name[$key]",'name','required');
$this->form_validation->set_rules("gender[$key]",'gender','required');
$this->form_validation->set_rules("birthday[$key]",'birthday','required');
$this->form_validation->set_rules("hobby[$key]",'hobby','required');
$this->form_validation->set_rules("about[$key]",'about','required');
$this->form_validation->set_error_delimiters('<span>', '</span>');
if($this->form_validation->run() != false)
{
return true;
}else{
$this->session->set_flashdata('validation',validation_errors());
redirect($_SERVER['HTTP_REFERER']);
}
}
/**
* Database Process
*/
public function read()
{
return $this->db->get($this->table)->result_array();
}
public function read_multiple($id)
{
if (empty($id)) {
redirect($_SERVER['HTTP_REFERER']);
}else {
$identity = explode('-', $id);
$sql = $this->db->where_in('id', $identity)->get($this->table);
return array(
'count' => $sql->num_rows(),
'data' => $sql->result_array(),
);
}
}
public function create_multiple()
{
$post_data = $this->_form_data();
$this->db->insert_batch($this->table,$post_data);
return ($this->db->affected_rows() > 0) ? true : false;
}
public function update_multiple()
{
$identity = 'id';
$post_data = $this->_form_data($identity);
$this->db->trans_start();
$this->db->update_batch($this->table, $post_data, $identity);
$this->db->trans_complete();
if ($this->db->affected_rows() > 0) {
return true;
}else {
if ($this->db->trans_status() === false) {
return false;
}else {
return true;
}
}
}
public function delete_batch()
{
if (empty($this->input->post('id'))) {
return false;
}else {
foreach ($this->input->post('id') as $key => $id) {
$identity = array('id' => $id);
$this->db->db_debug = false;
$read = $this->db->get_where($this->table,$identity);
if ($read->num_rows() > 0) {
$delete_image = $read->row_array();
$this->__delete_file($delete_image['photo']);
$this->db->delete($this->table,$identity);
$result[] = ($this->db->affected_rows() > 0) ? true : false;
}
}
return true;
}
}
/**
* File Process
*/
public function __upload_file($key)
{
$_FILES['photo[]']['name'] = $_FILES['photo']['name'][$key];
$_FILES['photo[]']['type'] = $_FILES['photo']['type'][$key];
$_FILES['photo[]']['tmp_name'] = $_FILES['photo']['tmp_name'][$key];
$_FILES['photo[]']['error'] = $_FILES['photo']['error'][$key];
$_FILES['photo[]']['size'] = $_FILES['photo']['size'][$key];
$this->load->library('upload');
$config_upload = [
'upload_path' => $this->storage_path,
'allowed_types' =>'jpg|png|ico',
'file_name' => $_FILES['photo']['name'][$key],
];
$this->upload->initialize($config_upload);
if($this->upload->do_upload('photo[]'))
{
$result = array('photo' => $this->upload->data());
$create_thumb = $this->_thumbnail($result['photo']['file_name']);
if ($create_thumb != 'success') {
echo $create_thumb;
exit;
}
return $result['photo']['file_name'];
}else {
return 'failed';
}
}
public function __delete_file($file,$isarray = false)
{
if ($isarray == true) {
foreach ($file as $x) {
@unlink($this->storage_path.$x);
@unlink($this->storage_path.'thumbnail/'.$x);
}
}else {
@unlink($this->storage_path.$file);
@unlink($this->storage_path.'thumbnail/'.$file);
}
}
/**
* Image Process
*/
public function _thumbnail($file_data)
{
$this->load->library('image_lib');
$source_path = $this->storage_path.$file_data;
$target_path = $this->storage_path.'thumbnail/';
$config = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'width' => 320,
);
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
return $this->image_lib->display_errors();
}
else {
return 'success';
}
}
}
4. Membuat View
- Buat folder crud didalam folder app (pathnya daily_codeigniter/application/views/app/crud)
- Buat file index.php didalam folder app (pathnya daily_codeigniter/application/views/app/crud/index.php)
- isi dengan kode ini
<?php $this->load->view('app/_layouts/header'); ?>
<?php $this->load->view('app/_layouts/sidebar'); ?>
<form method="POST">
<div class="row">
<div class="col-md-12">
<div class="c-card c-card--responsive h-100vh u-p-zero">
<div class="c-card__header c-card__header--transparent o-line">
<a class="c-btn--custom c-btn--small c-btn c-btn--info" href="<?php echo base_url('app/crud_multiple/create') ?>">
<i class="fa fa-plus"></i>
</a>
<button disabled="" type="button" class="c-btn--custom c-btn--small c-btn c-btn--info u-ml-auto action-update" data-href="<?php echo base_url('app/crud_multiple/update') ?>">
<i class="fa fa-edit"></i>
</button>
<button disabled="" class="c-btn--custom c-btn--small c-btn c-btn--danger u-ml-small action-delete" type="button" data-href='<?php echo base_url('app/crud_multiple/process_delete') ?>'>
<i class="fa fa-trash"></i>
</button>
</div>
<div class="c-card__body">
<?php $this->load->view('app/_layouts/alert'); ?>
<div class="c-table-responsive">
<table class="c-table c-table--zebra" style="display: table;">
<thead class="c-table__head">
<tr class="c-table__row">
<th class="c-table__cell c-table__cell--head" style="padding:10px !important;width: 50px">
<div class="c-choice c-choice--checkbox" style="position: relative; left: 10px; top: 10px;">
<input class="c-choice__input" id="select_all" type="checkbox">
<label class="c-choice__label" for="select_all"></label>
</div>
</th>
<th class="c-table__cell c-table__cell--head">user</th>
<th class="c-table__cell c-table__cell--head">birthday</th>
<th class="c-table__cell c-table__cell--head">hobby</th>
<th class="c-table__cell c-table__cell--head">about</th>
</tr>
</thead>
<tbody>
<?php if ($biodata): ?>
<?php foreach ($biodata as $data): ?>
<tr class="c-table__row">
<td class="c-table__cell">
<div class="c-choice c-choice--checkbox" style="position: relative; left: 5px; top: 10px;">
<input class="c-choice__input checkbox" id="checkbox-<?php echo $data['id'] ?>" name="id[]" value="<?php echo $data['id'] ?>" type="checkbox">
<label class="c-choice__label" for="checkbox-<?php echo $data['id'] ?>"></label>
</div>
</td>
<td class="c-table__cell">
<?php if ($data['photo']): ?>
<div class="o-media__img u-mr-xsmall">
<a target="_blank" href="<?php echo base_url("storage/uploads/thumbnail/{$data['photo']}") ?>"><img width="60" src="<?php echo base_url("storage/uploads/thumbnail/{$data['photo']}") ?>" alt="<?php echo $data['name'] ?>"/></a>
</div>
<?php endif ?>
<div class="o-media__body">
<?php echo $data['name'] ?>
<span class="u-block u-text-mute u-text-xsmall"><?php echo $data['gender'] ?></span>
</div>
</td>
<td class="c-table__cell">
<?php echo $data['birthday'] ?>
</td>
<td class="c-table__cell">
<?php echo $data['hobby'] ?>
</td>
<td class="c-table__cell">
<?php echo $data['about'] ?>
</td>
</tr>
<?php endforeach ?>
<?php else: ?>
<tr>
<td class="c-table__cell u-text-center" colspan="8">No Content</td>
</tr>
<?php endif ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</form>
<?php $this->load->view('app/_layouts/footer'); ?>
- Buat file form.php didalam folder crud (pathnya daily_codeigniter/application/views/app/crud/form.php)
- isi dengan kode ini
<?php $this->load->view('app/_layouts/header'); ?>
<?php $this->load->view('app/_layouts/sidebar'); ?>
<form action="<?php echo (empty($this->input->get('form')) and $update == false) ? base_url('app/crud_multiple/create') : (($update == false) ? base_url('app/crud_multiple/process_create') : base_url('app/crud_multiple/process_update')) ?>" class="row" method="<?php echo (empty($this->input->get('form')) AND $update == false) ? 'GET' : 'POST' ?>" enctype="multipart/form-data">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="c-card c-card--responsive h-100vh u-p-zero">
<div class="c-card__header c-card__header--transparent o-line">
<?php if ($this->input->get('form') or $update): ?>
<button class="c-btn c-btn--info c-btn--custom c-btn--small" name="publish" type="submit" title="publish">
<i class="fa fa-save" aria-hidden="true"></i>
</button>
<?php if (!$update): ?>
<a href='<?php echo base_url('app/crud_multiple/create') ?>' class="c-btn c-btn--danger c-btn--custom c-btn--small u-ml-auto" type="submit" title="publish">
<i class="fa fa-trash" aria-hidden="true"></i>
</a>
<?php endif ?>
<?php else: ?>
<div class="c-field">
<input required="" min="1" max="100" autofocus="" value="" class="c-input" name="form" id="form" type="number" placeholder="Insert Count Form (number)">
</div>
<button style="width: 120px" class="c-btn c-btn--info u-ml-xsmall" type="submit" title="Submit">
Create
</button>
<?php endif ?>
</div>
<div class="c-card__body u-p-small">
<div class="row">
<?php $this->load->view('app/_layouts/alert'); ?>
<?php if ($this->input->get('form') or $update): ?>
<?php
$length = ($update) ? $biodata['count'] : $this->input->get('form');
for ($i=0; $i < $length ; $i++) { ?>
<div class="col-lg-6 col-md-6 col-12 u-mb-small">
<div class="c-card c-card--responsive u-p-zero">
<div class="c-card__header c-card__header--transparent o-line">
Form <?php echo $i+1 ?>
</div>
<div class="c-card__body u-p-small">
<?php if (!empty($biodata['data'][$i]['id'])): ?>
<input type="hidden" name="id[]" value="<?php echo $biodata['data'][$i]['id'] ?>">
<?php endif ?>
<div class="c-field u-mb-small">
<label class="c-field__label u-text-uppercase">name : </label>
<input autofocus="" value="<?php echo (!empty($biodata['data'][$i]['name']) ? $biodata['data'][$i]['name'] : '') ?>" class="c-input" name="name[]" id="name" type="text" placeholder="name">
<?php if ($this->session->flashdata('name')): ?>
<small class="c-field__message u-color-danger">
<i class="fa fa-times-circle"></i><?php echo $this->session->flashdata('name') ?>
</small>
<?php endif ?>
</div>
<div class="c-field u-mb-medium">
<label class="c-field__label" for="select- <?php echo $i ?>">Gender</label>
<select name="gender[]" class="c-select" id="select- <?php echo $i ?>">
<?php if ($biodata['data'][$i]['gender'] == 'Male'): ?>
<option value="Male" selected="">Male</option>
<option value="Female">Female</option>
<?php elseif($biodata['data'][$i]['gender'] == 'Female'): ?>
<option value="Male">Male</option>
<option value="Female" selected="">Female</option>
<?php else: ?>
<option value="Male">Male</option>
<option value="Female">Female</option>
<?php endif ?>
</select>
<?php if ($this->session->flashdata('gender')): ?>
<small class="c-field__message u-color-danger">
<i class="fa fa-times-circle"></i><?php echo $this->session->flashdata('gender') ?>
</small>
<?php endif ?>
</div>
<label class="c-field__label u-text-uppercase">birthday</label>
<div class="c-field has-icon-right u-mb-small">
<span class="c-field__icon">
<i class="fa fa-calendar"></i>
</span>
<input name="birthday[]" readonly="" class="c-input" data-toggle="datepicker" type="text" placeholder="select date" value="<?php echo (!empty($biodata['data'][$i]['birthday']) ? date('m/d/Y', strtotime($biodata['data'][$i]['birthday'])) : '') ?>">
<?php if ($this->session->flashdata('birthday')): ?>
<small class="c-field__message u-color-danger">
<i class="fa fa-times-circle"></i><?php echo $this->session->flashdata('birthday') ?>
</small>
<?php endif ?>
</div>
<div class="c-field u-mb-small">
<label class="c-field__label u-text-uppercase">photo : </label>
<?php if (!empty($biodata['data'][$i]['photo'])): ?>
<img width="100px" src="<?php echo (!empty($biodata['data'][$i]['photo']) ? base_url("storage/uploads/thumbnail/{$biodata['data'][$i]['photo']}") : '') ?>" alt="photo">
<?php endif ?>
<input class="c-input" name="photo[]" id="photo" type="file" placeholder="photo">
<input class="c-input" name="photo_old[]" id="photo" type="hidden" value="<?php echo (!empty($biodata['data'][$i]['photo']) ? $biodata['data'][$i]['photo'] : '') ?>">
</div>
<div class="c-field u-mb-small">
<label class="c-field__label u-text-uppercase">hobby : </label>
<input autofocus="" value="<?php echo (!empty($biodata['data'][$i]['hobby']) ? $biodata['data'][$i]['hobby'] : '') ?>" class="c-input" name="hobby[]" id="hobby" type="text" placeholder="hobby">
<?php if ($this->session->flashdata('hobby')): ?>
<small class="c-field__message u-color-danger">
<i class="fa fa-times-circle"></i><?php echo $this->session->flashdata('hobby') ?>
</small>
<?php endif ?>
</div>
<div class="c-field u-mb-small">
<label class="c-field__label u-text-uppercase">about : </label>
<textarea rows="5" autofocus="" class="c-input" name="about[]" id="about" type="text" placeholder="about"><?php echo (!empty($biodata['data'][$i]['about']) ? $biodata['data'][$i]['about'] : '') ?></textarea>
<?php if ($this->session->flashdata('about')): ?>
<small class="c-field__message u-color-danger">
<i class="fa fa-times-circle"></i><?php echo $this->session->flashdata('about') ?>
</small>
<?php endif ?>
</div>
</div>
</div>
</div><!-- col -->
<?php } ?>
<?php endif ?>
</div><!-- row -->
</div><!-- card body -->
</div><!-- card -->
</div><!-- col -->
</div><!-- row -->
</div><!-- container -->
</form>
<?php $this->load->view('app/_layouts/footer'); ?>
5. Menambah Menu Navigasi
- buka file nav.php (pathnya daily_codeigniter/application/views/app/_layouts/nav.php)
- ganti isi kode didalamnya menjadi kode dibawah ini
<li class="c-sidebar__item">
<a class="c-sidebar__link <?php if($this->uri->segment(1)=="app" and empty($this->uri->segment(2)) or $this->uri->segment(2) == 'dashboard'){echo "is-active";}?>" href="<?php echo base_url('app/dashboard') ?>">
<i class="fa fa-fire u-mr-xsmall"></i>Dashboard
</a>
</li>
<h4 class="c-sidebar__title">First App</h4>
<li class="c-sidebar__item">
<a class="c-sidebar__link <?php if($this->uri->segment(2)=='crud_multiple' or $this->uri->segment(2)=='crud_multiple' and $this->uri->segment(3) == 'create' ){echo "is-active";}?>" href="<?php echo base_url('app/crud_multiple') ?>">
<i class="fa fa-fire u-mr-xsmall"></i> Crud Multiple
</a>
</li>
6. Menambahkan Sweet Alert
- buka file all-modules.js (pathnya daily_codeigniter/storage/app/js/all-modules.js)
- tambahkan kode dibawah ini
7. Konfigurasi Sweet Alert, Tombol Update, Checkbox
- buka file custom.js (pathnya daily_codeigniter/storage/app/js/custom.js)
- tambahkan kode dibawah ini
$('.action-delete').click(function(){
Swal.fire({
title: 'Are you sure?',
text: "You Will delete this data !",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if (result.value) {
var form = $(this).parents('form');
form.attr('action',$(this).attr('data-href'));
form.submit();
}
})
});
$('.action-update').click(function(e){
var arr = [];
$('input.checkbox:checked').each(function () {
arr.push($(this).val());
});
var action = $(this).attr('data-href') + '/' +arr.join("-");
window.location.href = action;
});
//select all checkboxes
$("#select_all").change(function(){ //"select all" change
$(".checkbox").prop('checked', $(this).prop("checked")); //change all ".checkbox" checked status
if(false == $(this).prop("checked")){
$(".action-update").prop('disabled', true);
$(".action-delete").prop('disabled', true);
}
if ($('.checkbox:checked').length > 0){
$(".action-update").prop('disabled',false);
$(".action-delete").prop('disabled',false);
}
});
//".checkbox" change
$('.checkbox').change(function(){
//uncheck "select all", if one of the listed checkbox item is unchecked
if(false == $(this).prop("checked")){ //if this item is unchecked
$("#select_all").prop('checked', false); //change "select all" checked status to false
$(".action-update").prop('disabled', true);
$(".action-delete").prop('disabled', true);
}
//check "select all" if all checkbox items are checked
if ($('.checkbox:checked').length == $('.checkbox').length ){
$("#select_all").prop('checked', true);
$(".action-update").prop('disabled',false);
$(".action-delete").prop('disabled',false);
}
if ($('.checkbox:checked').length > 0){
$(".action-update").prop('disabled',false);
$(".action-delete").prop('disabled',false);
}
});
8. Membuat Folder Uploads
folder uploads ini nantinya untuk menampung file gambar yang berhasil diupload pada proses crud- buat folder uploads didalam folder storage (pathnya daily_codeigniter/storage/uploads)
- buat folder thumbnail didalam folder storage (pathnya daily_codeigniter/storage/uploads/thumbnail)
9. Ujicoba Proses
credits:
checkbox check all : https://www.sanwebe.com/2014/01/how-to-select-all-deselect-checkboxes-jquery
file upload multiple : https://stackoverflow.com/questions/20113832/multiple-files-upload-in-codeigniter
Download File Project
checkbox check all : https://www.sanwebe.com/2014/01/how-to-select-all-deselect-checkboxes-jquery
file upload multiple : https://stackoverflow.com/questions/20113832/multiple-files-upload-in-codeigniter
Download File Project
Komentar
EH Kan CI dah keluar tuh yang versi 4 nya, kira kira ada perubahan ga ya dari segi pemogramannya, takutnya pas mau nerapin CI 4 malah programnya gak jalan..