Nisha
Nisha

Reputation: 158

PHP form validation using CodeIgniter

I have a simple form and applied validation to using CodeIgniter's form_validation->set_rules.

It works fine but the only issue is when I submit the form with one field blank, it shows a message to fill in that field, but the others fields also become blank.

How can I solve this so that when I submit the form with one field blank, it should show a message for that field, and other fields should hold the data entered in it.

Below is the code:

View page:

<form name='frm1' action="<?php echo base_url(); ?>index.php/Registrationc/add_user"  id="form1" method="post">
   <input type="text" class="form-control" style="text-transform: capitalize;" autocomplete="off" id="fname" name="fname">
   <h6 style="color:red;"><?php echo form_error('fname');?></h6>

   <input type="text" class="form-control" style="text-transform: capitalize;" autocomplete="off" id="mname" name="mname">
   <h6 style="color:red;"> <?php echo form_error('mname');?></h6>

   <input type="text" class="form-control" style="text-transform: capitalize;" autocomplete="off" id="lname" name="lname">
   <h6 style="color:red;"><?php echo form_error('lname');?></h6>

   <center>
      <input type="submit" value="Submit" class="btn btn-bricky" id="subbtn" name="submit">
   </center>
</form> 

Controller:

public function add_patient() {

    $this->form_validation->set_rules('fname', 'Firstname', 'trim|required|alpha');
    $this->form_validation->set_rules('mname', 'Middlename', 'trim|required|alpha');
    $this->form_validation->set_rules('lname', 'Lastname', 'trim|required|alpha');

    if ($this->form_validation->run() == FALSE) {
        $this->extra3();
    } else {
        $this->load->model('addpatientM');
        $fname1 = $this->input->post('fname');
        $lname1 = $this->input->post('lname');
        $mname1 = $this->input->post('mname');

        $submit = $this->addpatientM->insert_patient($fname1, $lname1, $mname1);
        if ($submit === true) {
            $this->load->library('session');
            $this->session->set_flashdata('success', 'successfully added');
        } else {
            $this->session->set_flashdata('fail', 'Opps there was some error while inserting');
        }
        redirect('Registrationc/extra3');
    }
}

Upvotes: 1

Views: 678

Answers (1)

BudwiseЯ
BudwiseЯ

Reputation: 1826

You need to echo set_value() into the value-attribute.

First you need to load form - helper:

$this->load->helper('form');

Update: Actually if you're using the form_validation library and using validation rules for the field in question, then there's no need to load the form helper separately for set_value.

Then use set_value in your view to set the value:

<input type="text" class="form-control" style="text-transform: capitalize;" 
autocomplete="off" id="lname" name="lname" value=<?= set_value("lname"); ?>>

Form Helper: Codeigniter documentation

Upvotes: 2

Related Questions