Skip to content

Tutorial Codeigniter (Studi Kasus Online Shop) Part 4

lsp toko online 22

Setelah kita menyelesaikan Pembuatan database hingga Generate semua tabel Toko Online atau Online shop pada part sebelumnya, di part terakhir ini kita akan membuat bagian Frontend dari Online shop ini.

Pembuatan Template untuk Member (Frontend)

  1. Langkah pertama kita untuk membuat Frontend adalah dengan membuat view dengan nama depan.php, kemudian isikan kode berikut
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <title><?=$judul;?></title>
        <link href="<?=base_url();?>assets/html/css/bootstrap.css" rel="stylesheet">
        <link href="<?=base_url();?>assets/html/css/font-awesome.min.css" rel="stylesheet">
        <link href="<?=base_url();?>assets/html/css/jquery.bxslider.css" rel="stylesheet">
        <link href="<?=base_url();?>assets/html/css/style.css" rel="stylesheet">
        <link href="<?=base_url();?>assets/style.css" rel="stylesheet">    
        <script src="<?=base_url();?>assets/html/js/jquery.js"></script>
        <script src="<?=base_url();?>assets/custom.js"></script>
    
    </head>
    <body>
    	<header class="hidden-print">
    	    <div class="container">
    	        <div class="row">
    
    	        	<!-- Logo -->
    	            <div class="col-lg-4 col-md-3 hidden-sm hidden-xs">
    	            	<div class="well logo">
    	            		<a href="<?=base_url();?>">
    	            			 <img src="<?=base_url();?>assets/food-stand.png" > <span>Toko Shobi</span>
    	            		</a>	            		
    	            	</div>
    	            </div>
    	            <!-- End Logo -->
    
    						
    				<!-- Search Form -->
    	            <div class="col-lg-5 col-md-5 col-sm-7 col-xs-12">
    	            	<div class="well">
    	                    <form action="<?php echo site_url('Depan/index'); ?>" method="get">
    	                        <div class="input-group">
    							
    	                            <input type="text" name="q" class="form-control input-search" placeholder="Cari produk apapun"/>
    	                            <span class="input-group-btn">
    	                                <button class="btn btn-default no-border-left" type="submit"><i class="fa fa-search"></i></button>
    						<?php 
    						if ($q <> '')
    						{
                                                    ?>
    						<a href="<?php echo site_url('Depan'); ?>" class="btn btn-default">Reset</a>
                                                    <?php
    						}
    						?>
    	                            </span>
    								
    	                        </div>
    	                    </form>
    	                </div>
    	            </div>
    	            <!-- End Search Form -->
    
    	            <!-- Shopping Cart List -->
    	            <div class="col-lg-3 col-md-4 col-sm-5">
    	                <div class="well">
    	                    <div class="btn-group btn-group-cart">
    						
    	                    <?php
    						
    	                    if($this->session->userdata('id_user_level')=='3')
    	                    {
    					?>
    						
    					<a href="<?=base_url();?>index.php/Auth/logout">Logout</a>
    					<?php
    					}else{
    					$ref=$this->uri->ruri_string();
    					?>
    					<a href="<?=base_url();?>index.php/Auth">Login</a> | 
    					<a href="<?=base_url();?>index.php/Member">Daftar</a>
    					<?php
    					}
    	                    ?>						
    	                    </div>
    	                </div>
    	            </div>
    	            <!-- End Shopping Cart List -->
    	        </div>
    	    </div>
        </header>
    
    	<!-- Navigation -->
        <nav class="navbar navbar-inverse hidden-print" role="navigation">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <!-- text logo on mobile view -->
                    <a class="navbar-brand visible-xs" href="<?= site_url('Depan') ?>">Shobi Online</a>
                </div>
                <div class="collapse navbar-collapse navbar-ex1-collapse">
                    <ul class="nav navbar-nav">                	
                        <li><a href="<?=base_url();?>">Home</a></li>				
                     <?php
    						
    	                if($this->session->userdata('id_user_level')=='3')
    	                    {
    				?>
    				<li><a href="<?=base_url();?>index.php/Depan/history" class="">Histori Belanja</a></li>
    										
    				<?php	
    				}
    				?>
                    </ul>
                    <ul class="nav navbar-nav navbar-right">
    				<li>
    				<?php
    					$text_cart_url  = '<span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span>';
    					$text_cart_url .= ' Keranjang: '. $this->cart->total_items() .' items';
    				?>
    					<?=anchor('Depan/cart', $text_cart_url)?>
    					</li>
    			    </ul>    			
                </div>
    			
    			
    	  
            </div>
        </nav>
        <!-- End Navigation -->
    
    <div class="container main-container">
             
    <div class="row">       
            	<!-- Categories -->
    <div class="col-lg-3 col-md-3 col-sm-3">
    	<div class="no-padding">
        		<span class="title">Kategori</span>
        	</div>
    
    		<div id="main_menu">
                <div class="list-group panel panel-cat">
    			<?php
    			$query = $this->db->query("SELECT * FROM tbl_kategori");
    
    			foreach ($query->result_array() as $rows) {
    			  $dwet = $rows['kategori'];
    			  $id = $rows['id'];
    			  ?>
    			  <a href="<?php echo site_url('Depan/index?q='.$id); ?>" class="list-group-item" ><?=$dwet;?></a>
    			 <?php
    			 } 
    		 ?>
    						 
                                          
                </div>
            </div>
    
    	</div>	
    	<!-- End Categories -->
    <div class="col-lg-9 col-md-9 col-sm-9">	
    <?php
                echo $contents;
                ?>
    </div>        	
    </div>

     

  2. Langkah berikutnya kita buat view untuk menampilkan Produk dari tabel Product dalam bentuk grid, Buat View baru dengan nama Produk.php, kemudian isi dengan kode berikut ini
    <!-- looping products -->
      <?php foreach($products as $product) : ?>
      <div class="col-xs-4 col-md-4">
    	<div class="thumbnail">
    	  <?=img([
    		'src'		=> 'uploads/' . $product->image,
    		'style'		=> 'max-width: 100%; max-height:100%; height:100px'
    	  ])?>
    	   <div class="caption prod-caption">
    		<h3><?=$product->name?></h3>
    		<p><?=$product->description?></p>
    		<a href="javascript:;" class="btn btn-default">Rp <?=number_format($product->price,0);?></a>
    		<div class="btn-group">
    		<a href="<?=base_url();?>index.php/Depan/add_to_cart/<?=$product->id;?>" class="btn btn-primary"><i class="fa fa-shopping-cart"></i> Beli</a>
    		
    		
    			
    		</div>
    	  </div>
    	</div>
      </div>
      <?php endforeach; ?>
    <!-- end looping -->
    

     

  3. Agar Template tersebut dapat digunakan, langkah berikutnya kita akan membuat Controller untuk memanggil view produk dan template depan

Membuat Controller Depan

Buat File Controller dengan nama Depan.php mengunakan Editor Code, kemudian ketik kode berikut ini

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Depan extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Products_model');
		$this->load->model('Invoices_model');
		$this->load->model('Crudm');
	}

	public function index()
	{
		$q = urldecode($this->input->get('q', TRUE));
        
        if ($q <> '') {
            $config['base_url'] = base_url() . '.php/c_url/index.html?q=' . urlencode($q);
            $config['first_url'] = base_url() . 'index.php/Depan/index.html?q=' . urlencode($q);
        } else {
            $config['base_url'] = base_url() . 'index.php/Depan/index/';
            $config['first_url'] = base_url() . 'index.php/Depan/index/';
        }
        $products = $this->Crudm->get_limit_data($q,'products');
        
        $data = array(
            'products' => $products,
            'q' => $q, 
        );
        
		$this->template->load('depan', 'produk', $data);
	}
	
	public function add_to_cart($product_id)
	{
		$product = $this->Products_model->get_by_id($product_id);
		$data = array(
					   'id'      => $product->id,
					   'qty'     => 1,
					   'price'   => $product->price,
					   'name'    => $product->name
					);

		$this->cart->insert($data);
		redirect('Depan/index');
	}
	
	public function cart(){
		$this->template->load('depan', 'show_cart');
	}
	
	public function clear_cart()
	{
		$this->cart->destroy();
		redirect('Depan/index');
	}
	
	public function history(){
		
		$q=$this->session->userdata('id_users');

		$data['invoices'] = $this->Invoices_model->history($q);

		$this->template->load('depan', 'invoices/view_invoices_member', $data);
	}
}

Untuk menguji apakah sudah berhasil, panggil Controller Depan di browser http://localhost/lsp_toko_online/index.php/Depan/

Membuat View Keranjang

Buat view baru dengan nama show_cart.php, kemudian isi dengan kode berikut

<div class="content-wrapper">
<section class="content">
	<div class="row">
		<div class="col-xs-12">
			<div class="box box-warning box-solid">

				<div class="box-header">
					<h3 class="box-title">KERANJANG BELANJA</h3>
				</div>
			<div class="box-body">			
				<table class="table table-bordered table-striped table-hover">
				
					<thead>
					<tr>
						<th>No</th>
						<th>Product</th>
						<th>Jumlah</th>
						<th>Price</th>
						<th>Subtotal</th>
					</tr>
					</thead>
					<tbody>
					<?php 
						$i=0;
						foreach ($this->cart->contents() as $items) : 
						$i++;
					?>
					<tr>
						<td><?= $i ?></td>
						<td><?= $items['name'] ?></td>
						<td><?= $items['qty'] ?></td>
						<td align="right"><?= number_format($items['price'],0,',','.') ?></td>
						<td align="right"><?= number_format($items['subtotal'],0,',','.') ?></td>
					</tr>
					<?php endforeach; ?>
					</tbody>
					<tfoot>
						<tr>
							<td align="right" colspan="4">Total </td>
							<td align="right"><?= number_format($this->cart->total(),0,',','.'); ?></td>
						</tr>
					</tfoot>
				</table>
				<div align="center">
					<?= anchor('welcome/clear_cart','Bersihkan Keranjang',['class'=>'btn btn-danger']) ?> 
					<?= anchor(base_url(),'Lanjut Belanja',['class'=>'btn btn-primary']) ?> 
					<?= anchor('order','Check Out',['class'=>'btn btn-success']) ?>
				</div>
			</div>
			</div>
		</div>
	</div>		
  </section>
</div>

 

Membuat Controller untuk Checkout Barang

Agar produk yang ada di dalam keranjang dapat di checkout, kita tambahkan controller baru dengan nama Order.php kemudian masukkan Code berikut ini

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Order extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('Orders_Model');
	}
	
	public function index()
	{
		cekmember();
		$is_processed = $this->Orders_Model->process();
		if($is_processed){
			$this->cart->destroy();
			redirect('Order/success');
			
		} else {
			$this->session->set_flashdata('error','Failed to processed your order, please try again!');
			redirect('Depan/cart');
		}
	}

	public function success()
	{
		$this->template->load('depan','order_success');
	}
}

Menambah Function Process Pada Orders_model

Tambahkan function Process pada Model Orders_model.hp, untuk memproses produk yang ada di keranjang

public function process()
	{
		//create new invoice
		$invoice = array(
			'date'		=> date('Y-m-d H:i:s'),
			'due_date'	=> date('Y-m-d H:i:s', mktime( date('H'),date('i'),date('s'),date('m'),date('d') + 1,date('Y'))),
			'status'	=> 'unpaid',
			'id_user' =>$this->session->userdata('id_users')
		);
		$this->db->insert('invoices', $invoice);
		$invoice_id = $this->db->insert_id();
		
		// put ordered items in orders table
		foreach($this->cart->contents() as $item){
			$data = array(
				'invoice_id'		=> $invoice_id,
				'product_id'		=> $item['id'],
				'product_name'		=> $item['name'],
				'qty'				=> $item['qty'],
				'price'				=> $item['price']
			);
			$this->db->insert('orders', $data);
		}
		
		return TRUE;
	}

Langkah berikutnya buat view dengan nama order_success.php, kemudian ketikkan dengan kode berikut :

					
<div class="content-wrapper">
    <section class="content">
		
        <?php echo alert('alert-info', 'Pemesanan Berhasil', 'Terima Kasih, Persanan kamu sedang kami proses, Selanjutnya Konfirmasi Pembayaran Melalui Tombol berikut : '. '<a href="https://wa.me/6281332558623?text=Assalamu%27alaikum%2C%20saya%20ingin%20konfirmasi%20pembayaran"  class="fa fa-whatsapp>Konfirmasi </a>' ); 
		?>
		
		<a class="btn btn-social-icon btn-whatsapp"><i class="fa fa-whatsapp"></i></a>
		
    </section>
	
</div>

Ganti Nomor dan Pesan WA sesuai dengan keinginan kalian\

Membuat Controller Registrasi Member 

Member dapat melanjutkan ke proses Checkout jika sudah melakukan proses Login, sebelum login member harus Registrasi terlebih dahulu, oleh karena itu kita buatkan Controller baru dengan nama Member.php, Coding pada Member.php ini sebenarnya hampir sama dengan User.php, anda bisa copy paste dari Controller tersebut, tinggal menghapus perintah is_login(); pada baris 11 di Controller User.php, sehingga coding lengkapnya seperti ini

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Member extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        
        $this->load->model('User_model');
        $this->load->library('form_validation');        
		$this->load->library('datatables');
    }

    public function index()
    {
        $this->template->load('Depan','user/tbl_member_form');
    } 
    
    public function json() {
        header('Content-Type: application/json');
        echo $this->User_model->json();
    }

    public function create() 
    {
        $data = array(
            'button'        => 'Create',
            'action'        => site_url('user/create_action'),
	    'id_users'      => set_value('id_users'),
	    'full_name'     => set_value('full_name'),
	    'email'         => set_value('email'),
	    'password'      => set_value('password'),
	    'images'        => set_value('images'),
	    'id_user_level' => set_value('id_user_level'),
	    'is_aktif'      => set_value('is_aktif'),
	    'alamat'	    => set_value('alamat'),
	);
        $this->template->load('template','user/tbl_member_form', $data);
    }
    
    
    public function create_action() 
    {
        $this->_rules();
        $foto = $this->upload_foto();
        if ($this->form_validation->run() == FALSE) {
            $this->create();
        } else {
            $password       = $this->input->post('password',TRUE);
            $options        = array("cost"=>4);
            $hashPassword   = password_hash($password,PASSWORD_BCRYPT,$options);
            
            $data = array(
		'full_name'     => $this->input->post('full_name',TRUE),
		'email'         => $this->input->post('email',TRUE),
		'password'      => $hashPassword,
		'images'        => $foto['file_name'],
		'id_user_level' => $this->input->post('id_user_level',TRUE),
		'is_aktif'      => $this->input->post('is_aktif',TRUE),
		'alamat'      	=> $this->input->post('alamat',TRUE),
	    );

            $this->User_model->insert($data);
            $this->session->set_flashdata('message', 'Pendaftaran Sukses, Silahkan Login');
            redirect(site_url('member'));
        }
    }
    
    public function update($id) 
    {
        $row = $this->User_model->get_by_id($id);

        if ($row) {
            $data = array(
                'button'        => 'Update',
                'action'        => site_url('user/update_action'),
		'id_users'      => set_value('id_users', $row->id_users),
		'full_name'     => set_value('full_name', $row->full_name),
		'email'         => set_value('email', $row->email),
		'password'      => set_value('password', $row->password),
		'images'        => set_value('images', $row->images),
		'id_user_level' => set_value('id_user_level', $row->id_user_level),
		'is_aktif'      => set_value('is_aktif', $row->is_aktif),
		'alamat'	=> set_value('alamat', $row->alamat),
	    );
            $this->template->load('depan','user/tbl_member_form', $data);
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('member'));
        }
    }
    
    public function update_action() 
    {
        $this->_rules();
        $foto = $this->upload_foto();
        if ($this->form_validation->run() == FALSE) {
            $this->update($this->input->post('id_users', TRUE));
        } else {
            if($foto['file_name']==''){
                $data = array(
		'full_name'     => $this->input->post('full_name',TRUE),
		'email'         => $this->input->post('email',TRUE),
		'id_user_level' => $this->input->post('id_user_level',TRUE),
		'is_aktif'      => $this->input->post('is_aktif',TRUE));
            }else{
                $data = array(
		'full_name'     => $this->input->post('full_name',TRUE),
		'email'         => $this->input->post('email',TRUE),
                'images'        =>$foto['file_name'],
		'id_user_level' => $this->input->post('id_user_level',TRUE),
		'is_aktif'      => $this->input->post('is_aktif',TRUE));
                
                // ubah foto profil yang aktif
                $this->session->set_userdata('images',$foto['file_name']);
            }

            $this->User_model->update($this->input->post('id_users', TRUE), $data);
            $this->session->set_flashdata('message', 'Update Record Success');
            redirect(site_url('Member'));
        }
    }
    
    
    function upload_foto(){
        $config['upload_path']          = './assets/foto_profil';
        $config['allowed_types']        = 'gif|jpg|png';
        //$config['max_size']             = 100;
        //$config['max_width']            = 1024;
        //$config['max_height']           = 768;
        $this->load->library('upload', $config);
        $this->upload->do_upload('images');
        return $this->upload->data();
    }


    public function _rules() 
    {
	$this->form_validation->set_rules('full_name', 'full name', 'trim|required');
	$this->form_validation->set_rules('email', 'email', 'trim|required');
	//$this->form_validation->set_rules('password', 'password', 'trim|required');
	//$this->form_validation->set_rules('images', 'images', 'trim|required');
	$this->form_validation->set_rules('id_user_level', 'id user level', 'trim|required');
	$this->form_validation->set_rules('is_aktif', 'is aktif', 'trim|required');

	$this->form_validation->set_rules('id_users', 'id_users', 'trim');
	$this->form_validation->set_error_delimiters('<span class="text-danger">', '</span>');
    }

    

}

Membuat History Belanja Member

Setelah Member berhasil login, di Navbar muncul menu baru bernama HISTORY BELANJA, Agar History Belanja berfungsi kita buatkan view dengan nama view_invoices_member.php di dalam folder view/invoices/, kemudian isikan koding berikut :

<div class="content-wrapper">
    <section class="content">
				
	<div class="row">
		<div class="col-xs-12">
			<div class="box box-warning box-solid">

			<div class="box-header">
				<h3 class="box-title">HISTORY BELANJA</h3>
			</div>
				

	<!-- dalam div row harus ada col yang maksimum nilainya 12 -->
	<div class="row">
		<div class="col-md-1"></div>
		<div class="col-md-10">
		
			<table id="myTable" class="table table-striped table-bordered table-hover">
				<thead>
				<tr>
					<th>Invoice ID</th>
					<th>Date</th>
					<th>Due Date</th>
					<th>Status</th>
				   
				</tr>
				</thead>
				<tbody>
				
				<?php foreach($invoices as $invoice) : 
				?>
				<tr>
					<td><?=$invoice->id?></td>
					<td><?=$invoice->date?></td>
					<td><?=$invoice->due_date?></td>
					<td><?=$invoice->status?></td>
					
				</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
		<div class="col-md-1"></div>
	</div>
	</div>
	</div>
	</div>
		</div>
 </section>
</div>
	<script>
		$(document).ready(function(){
			$('#myTable').DataTable();
		});
	</script>

 

Menambah Function History

tambahkan Function history pada Model Invoice_model.php

function history($id_user)
    {
        $this->db->order_by($this->id, $this->order);
        $this->db->where('id_user', $id_user);
		 
        return $this->db->get($this->table)->result();
    }

Setting Default Controller pada Routers

Agar Controller Depan dipanggil pada saat aplikasi dibuka, maka kita perlu Setting Default Controller, caranya buka routes.php pada folder ..\htdocs\lsp_toko_online\application\config, kemudian ganti coding berikut ini

//CARI KODE BERIKUT
$route['default_controller'] = 'Welcome';

//DAN GANTI DENGAN

$route['default_controller'] = 'Depan';

Kemudian simpan dan jalankan, jika berhasil tampilannya akan seperti ini

Tampilan Frontend Member

lsp toko online 22

Tampilan Histori Belanjalsp toko online 23

Tampilan Keranjang Belanjalsp toko online 24

Tampilan Berhasil Checkout lsp toko online 25

Demikian Tutorial Codeigniter dengan Studi Kasus Toko Online (Online Shop), mudah-mudahan menjadi ilmu yang manfaat untuk kita semua

Leave a Reply