Cara Update/Edit Data CodeIgniter

Cara Update/Edit Data CodeIgniter

   Pada Tutorial kali ini kita akan mencoba mengupdate atau tambah data. Yang perlu kalian tambahkan adalah dibagian model dan controllernya.

1. Buka controller Produk.php yang sebelumnya sudah pernah kita buat dan tambahkan kode berikut:

            defined('BASEPATH') OR exit('Error');

            /**

             *

             */

            class Produk extends CI_Controller

            {

                        public function __construct()

                        {

                                    parent::__construct();

                                    $this->load->model('produk_model');

                                    $this->load->library('form_validation');

                        }

                        public function index()

                        {

                                    $data['produk'] = $this->produk_model->getAll();

                                    $this->load->view("common/produk/produk", $data);

                        }

                        public function add()

                        {

                    $produk = $this->produk_model;

                    $validation = $this->form_validation;

                    $validation->set_rules($produk->rules());

                            

                    if ($validation->run()) {

                        $produk->save();

                        $this->session->set_flashdata('success', 'Berhasil disimpan');

                        redirect(site_url('common/produk'));

                    }

 

                    $this->load->view("common/produk/tambahproduk");

                        }

 

            public function edit($id=null)

                        {

            if (!isset($id)) redirect('admin/produk');

                    $produk = $this->produk_model;

                    $validation = $this->form_validation;

                    $validation->set_rules($produk->rules());

 

                    if ($validation->run()) {

                        $produk->update();

                        $this->session->set_flashdata('success', 'Berhasil disimpan');       

                        redirect(site_url('common/produk'));

                    }

                    $data["produk"] = $produk->getById($id);

                    if (!$data["produk"]) show_404();

                   

                    $this->load->view("common/produk/editproduk", $data);

                        }

 

                        public function delete($id=null)

                {

                    if (!isset($id)) show_404();

                   

                    if ($this->produk_model->delete($id)) {

                        redirect(site_url('common/produk'));

                    }

                }

            }// end class

?>

Yang ditambahkan adalah function edit.

2. Buka model produk_model dan tambahkan kode berikut:

    defined('BASEPATH') OR exit('Error');

    /**

     *

     */

    class produk_model extends CI_Model

    { 

            private $_table = 'produk';

            public $id;

            public $name;

            public $price;

            public $description;

            public $image = "default.jpg";

            public function rules()

            {

                return [

                    ['field' => 'name',

                    'label' => 'name',

                    'rules' => 'required']

                ];

 

                return [

                    ['field' => 'price',

                    'label' => 'price',

                    'rules' => 'required']

                ];

 

                return [

                    ['field' => 'description',

                    'label' => 'description',

                    'rules' => 'required']

                ];

            }

            public function getAll()

            {

                return $this->db->get($this->_table)->result();

            }

            public function getById($id)

            {

                return $this->db->get_where($this->_table, ["id" => $id])->row();

            }

            public function save()

            {

                $post = $this->input->post();

                $this->name = $post['name'];

                $this->price = $post['price'];

                $this->description = $post['description'];

                $this->image = $this->_uploadImage();

                $this->db->insert($this->_table, $this);

            }

            public function update()

            {

                $post = $this->input->post();

                $update["name"] = $post['name'];

                $update["price"] = $post['price'];

                $update["description"] = $post['description'];

                if (!empty($_FILES["image"]["name"])) {

                    $update['image'] = $this->_uploadImage();

                }else{

                    $update['image'] = $post["old_image"];

                }

                $this->db->update($this->_table, $update, array('id' => $post['id']));

            }  

            public function delete($id)

            {

                return $this->db->delete($this->_table, array("id" => $id));

            }

            private function _uploadImage()

            {

                $namafile = 'file_'.time();

                $config['upload_path'] = './img/produk/';

                $config['allowed_types'] = 'gif|jpg|png';

                $config['file_name'] = $namafile;

                $config['max_size'] = 1024;    //1mb

                //$config['max_width'] = 1024;

                // config['max_height'] = 768;

 

                $this->load->library('upload',$config);

 

                if($this->upload->do_upload('image')){

                    return $this->upload->data("file_name");

                }

                return "default.jpg";

            }      

            private function _deleteImage($id)

            {

                $produk = $this->getById($id);

                if ($produk->image != "default.jpg") {

                    $filename = explode(".", $produk->image)[0];

                    return array_map('unlink', glob(FCPATH."img/produk/$filename.*"));

            }

    }

}

?>

Keterangan:

1. Yang kalian tambahkan adalah function update() yang berwarna pink untuk menambah data tulisan saja.

2. Function UploadImage() untuk menambah data berupa file gambar

3. Yang terakhir adalah Function _deleteImge($id) ini untuk menghapus data berupa file gambar. Jadi didalam Model ini ada 2 function untuk menghapus data.

  • Yang pertama ada Function delete($id) untuk menghapus data berupa tulisan.
  • Dan Function _deleteImge($id) ini untuk menghapus data berupa file gambar.

3. Buka View Produk.php dan tambahkan kode berikut pada buttuon Edit:

<?php

    $this->load->view('common/header');

?>

                <div class="col-lg-12">

                        <div class="card">

                            <div class="card-header">

                                <strong class="card-title">Produk</strong>

                            </div>

                            <a href="<?php echo site_url('common/produk/add') ?>" class="btn btn-primary btn-sm" style="width: 10%;">

                                <i class="fa fa-plus"></i> Tambah

                            </a>

                            <div class="card-body">

                                <table class="table">

                                    <thead class="thead-dark">

                                        <tr>

                                            <th scope="col">No.</th>

                                            <th scope="col">Name</th>

                                            <th scope="col">price</th>

                                            <th scope="col">Gambar</th>

                                            <th scope="col">Aksi</th>

                                        </tr>

                                    </thead>

                                 <?php $no=1; foreach ($produk as $rproduk): ?>

                                    <tbody>

                                        <tr>

                                          <td>

                                            <?php echo $no++; ?>

                                          </td>

                                          <td>

                                            <?php echo $rproduk->name; ?>

                                          </td>

                                          <td>

                                            <?php echo $rproduk->price; ?>

                                          </td>

                                          <td>

                                            <img src="<?php echo base_url('img/produk/'.$rproduk->image) ?>" width="64" />

                                          </td>

                                          <td width="90">

                                            <a href="<?php echo site_url('common/produk/edit/'.$rproduk->id) ?>" data-toggle="#" data-target="#" role="Button" class="btn btn-warning btn-sm">

                                              <i class="fa fa-edit (alias)"></i></a>

                                              <a href="<?php echo site_url('common/produk/delete/'.$rproduk->id) ?>" data-toggle="#" data-target="#" role="Button" class="btn btn-danger btn-sm">

                                              <i class="fa fa-trash-o"></i></a>

                                          </td>

                                        </tr>

                                    </tbody>

                                    <?php endforeach; ?>

                                </table>

                            </div>

                        </div>

                    </div>

<?php

    $this->load->view('common/footer');

?>

Download Tutorial