Kamis, 05 Mei 2011

Contoh Form Validation CodeIgniter - PHP

Kali ini saya saya akan membuat contoh sederhana submit form yang disertai dengan validasi, tentunya menggunakan Code Igniter. Saya anggap konfigurasi awal sudah oke ya...(atau baca postingan ini).

Baiklah langsung aja, berikut langkah2 nya:
1. Buat file home.php di applications/views . Copy paste script berikut diantara tag <body></body>

<?php  echo form_open_multipart('home') . "\n"; ?>
<table>
 <tr>
  <td>Category</td>
  <td><?php echo form_dropdown('category', $category); ?></td>
  <td></td>
 </tr>
 <tr>
  <td>Title</td>
  <td><input type="text" name="judul" value="<?php echo set_value('judul'); ?>" id="txtinput" />
  </td>
  <td><font color="#FF0000"><?php echo form_error('judul'); ?></font>
  </td>
 </tr>
 <tr>
  <td>Writer</td>
  <td><input type="text" name="writer" value="<?php echo set_value('writer'); ?>" id="txtinput" /></td>
  <td><font color="#FF0000"><?php echo form_error('writer'); ?></font></td>
 </tr>
 <tr>
  <td>Image Name</td>
  <td><input type="file" id="userfile" name="userfile" size="20"  value="<?php echo set_value('userfile'); ?>"/></td>
  <td><font color="#FF0000"><?php echo form_error('userfile'); ?></td></tr>
 <tr>
 <tr>
  <td valign="top">Synopis <br /><font size="-2">*max 200 words</font></td>
  <td><textarea name="sinopsis" value="<?php echo set_value('sinopsis'); ?>" id="sinopsis"  ></textarea></td>
  <td><font color="#FF0000"><?php echo form_error('sinopsis'); ?></font></td>
 </tr>
 <tr>
  <td valign="top">Jumlah Chapter</td>
  <td><input type="text" name="jumlah_chapter" value="<?php echo set_value('jumlah_chapter'); ?>" id="txtinput" /></td>
  <td><font color="#FF0000"><?php echo form_error('jumlah_chapter'); ?></font></td>
 </tr>
 <tr>
   <td>&nbsp;</td>
   <td valign="top" align="right">
   <?php echo form_submit('submit', 'Submit'). form_reset('reset', 'Clear'); ?></td>
  <td></td>
 </tr>
</table>
<?php echo form_close(); ?>
<?php
if ($this->session->flashdata('msg_title')){
?>
<div class="msg"><?php echo $this->session->flashdata('msg_title'); ?></div>
<?php } ?>

2. Buat file home.php di application/controlles

<?php 
class Home extends CI_Controller {
 function __construct()
 {
   parent::__construct();
   $this->load->model('Querypage');
   $this->load->helper(array('form', 'url','inflector'));
   $this->load->library('form_validation');
 }

 public function index()
 {
 $rules = array(
            array(
                'field' => 'judul',
                'label' => 'Judul',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'writer',
                'label' => 'Writer',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'sinopsis',
                'label' => 'Sinopis',
                'rules' => 'required|trim'
            ),
            array(
                'field' => 'userfile',
                'label' => 'File',
                'rules' => 'trim'
            ),
            array(
                'field' => 'jumlah_chapter',
                'label' => 'Jumlah Chapter',
                'rules' => 'trim|required|numeric'
   )
        );
 
  $this->form_validation->set_rules($rules);
  $this->form_validation->set_message('required', 'Required');
  $this->form_validation->set_message('numeric', 'Numeric');
 
  if ($this->input->post('submit'))
  {
   if ($this->form_validation->run() == FALSE)
   {
    $this->load->view('home', $data);
   }
   else
   {
    $this->add_title(); 
   }
  }else{
   $this->load->view('home', $data);
  }   
 
 }

 function add_title(){
  $config['upload_path'] = './img_upload/';
  $config['allowed_types'] = 'png|gif';
 
  $this->load->library('upload', $config);

  if ( ! $this->upload->do_upload() and $_FILES['userfile']['error']!=4 )
  {
    $error = array('error' => $this->upload->display_errors());
   $this->session->set_flashdata('msg_title', 'Insert failed. Please check your image file, only .png or.gif file allowed.');
  }
  else
  {
   $data_upload = $this->upload->data();
   $filename = $data_upload['file_name'];  // imagename.png
   $rawname = $data_upload['raw_name']; //imagename

   // save data
   $arr_data = array(  'type' => $this->input->post('category'),
         'title' => humanize($this->input->post('judul')),
         'writername' => humanize($this->input->post('writer')),
         'sinopsis' => $this->input->post('sinopsis'),
         'TotalChapter' => $this->input->post('jumlah_chapter'),
         'imagename' => $rawname,
         'dateinserted' => date('Y-m-d H:i:s', now())
   );

   $this->Querypage->insert_title($arr_data); //Query untuk insert data
   // set pesan
   $this->session->set_flashdata('msg_title', 'insert data sukses');
  }
  redirect('home');
 }
}
?>

3. Buat file querypage.php di application/models

<?php
class Querypage extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

   function insert_title($data)
  {
 return $this->db->insert('namatable', $data); 
   }

  }
?>

4. Selesai ^__^

Sedikit penjelasan, untuk upload image pada form diatas tidak diharuskan diisi sehingga saya menggunakan $_FILES['userfile']['error']!=4. Jika file harus diisi, hapus saja script ini. 
Untuk mempermudah dan infomasi lebih lanjut tentang form validation di Code Igniter, check this out

1 komentar:

  1. nice tutorial goodjob skripnya berhasil trimakasih banyah u helped me....

    BalasHapus