Search code examples
phphtmlcodeignitercodeigniter-3codeigniter-form-validation

Validate optional image upload field with other input fields in Codeigniter


I have problem in Codeigniter how to validate form when file upload is optional. I was created normal form which validate both input field and file upload field in a form and it is work fine. But i want to know how to validate that form when file choosing is optional.

Here my View php file (news_add.php)

<?php
    /**
     * Created by PhpStorm.
     * User: Anu
     * Date: 8/31/2018
     * Time: 10:00 PM
     */?>
    <?php include('partials/admin_header.php'); ?>
    <?php include("partials/admin_sidebar.php"); ?>
    <div class="content-wrapper">
        <div class="container-fluid">
            <!-- Breadcrumbs-->
            <ol class="breadcrumb">
                <li class="breadcrumb-item">
                    <a href="<?php echo base_url(); ?>admin/dashboard">Dashboard</a>
                </li>
                <li class="breadcrumb-item active">Test</li>
            </ol>
            <div class="container mb-4">
                <div class="row">
                    <div class="mx-auto col-10">
                        <!-- form user info -->
                        <div class="card">
                            <div class="card-header">
                                <h3>Add News & Event</h3>
                            </div>
                            <div class="card-body">
                                <?php $attributes = array('id'=>'news_add','class'=>'form-horizontal'); ?>
                                <?php echo form_open_multipart('Add/add_data', $attributes); ?>
                                <div class="form-group">
                                    <b>
                                        <?php echo form_label('User Full Name <small class="text-success"> (required) </small>','', $attributes=array("class" => "control-label col-sm-12 col-lg-12 col-md-12 col-xs-12")); ?>
                                    </b>
                                    <div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
                                        <?php echo form_input('u_name','', $attributes=array("class" => 'form-control col-sm-12 col-lg-12 col-md-12 col-xs-12',
                                            "id"=>"u_name","placeholder"=>"Enter your full name")); ?>
                                        <?php echo form_error('u_name','<div class="text-danger mb-3">', '</div>'); ?>
                                    </div>
                                </div>
                                <div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
                                    <div class="form-group">
                                        <label for="img">Image <small class="text-success"> (required) </small></label><br>
                                        <div class="form-group">
                                            <input type="file" class="form-control-file" name="userfile" size="20">
                                        </div>
                                        <?php echo form_error('userfile','<div class="text-danger mb-3">', '</div>'); ?>
                                        <?php if(isset($error)) echo "<div class='text-danger mb-3'>$error</div>"; ?>
                                    </div>
                                <div class="form-group">
                                    <div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
                                        <?php $data = array('
                                            class'=> 'btn btn-success btn-md center mt-2',
                                            'name'=> 'submit',
                                            'value'=>'Register Now',
                                            'type'=>'submit'
                                        ); ?>
                                        <center>
                                            <?php echo form_submit($data); ?>
                                        </center>
                                    </div>
                                </div>
                                <?php echo form_close(); ?>
                            </div><!-- container -->
                        </div> <!--card-body-->
                    </div> <!--mx-auto col-sm-6-->
                </div><!--row-->
            </div><!--container py-3-->
        </div><!-- /.container-fluid-->
    </div><!-- /.content-wrapper-->
    <?php include("partials/admin_footer.php") ?>

In here i used form_error() method for display corresponding error for each input field and file field. Also i use one extra way to display other file upload errors i used here <?php if(isset($error)) echo "<div class='text-danger mb-3'>$error</div>"; ?> The $error variable came from the controller

Here my controller class (Add.php)

        <?php
    /**
     * Created by PhpStorm.
     * User: Anu
     * Date: 8/31/2018
     * Time: 10:07 PM
     */

    class Add extends CI_Controller
    {
         public function __construct()
        {
            parent::__construct();
        }
        public function add_data(){

            $this->form_validation->set_rules('u_name', 'News Title', 'required');
            if (empty($_FILES['userfile']['name']))
            {
                $this->form_validation->set_rules('userfile', 'User Image', 'trim|xss_clean|required');
            }
            $config['upload_path']          = './upload/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 2048000;
            // if use helper "upload" don't you need load upload helper here like $this->load->library->('upload',$config)
            // and only you need initialize your configuration rules for your file
            // and $config can be other name it is globle array variable to codeigniter framework
            $this->upload->initialize($config);

            if ($this->form_validation->run() == true) {
                if ( ! $this->upload->do_upload('userfile')) {
                // set file upload error here
                $error = array('error' => $this->upload->display_errors());
                $this->load->view('admin/news_add', $error);
            }
            }else{
                $this->load->view('admin/news_add');
            }
        }
    }

This is work fine when both input field and file upload field is required! but assuming file upload field is optional, how to validate this current form? and if user select file how to validate that time also?


Solution

  • Add validation for files only when files are being uploaded.

    if (!empty($_FILES) && !empty($_FILES['userfile']['name']))
     {
      $this->form_validation->set_rules('userfile', 'User Image', 'trim|xss_clean|required');
      $config['upload_path']          = './upload/';
      $config['allowed_types']        = 'gif|jpg|png';
      $config['max_size']             = 2048000;
      $this->upload->initialize($config);
      if ($this->form_validation->run() == true) {
         //upload here
      }else{
         // handle error
      }
     }