Welcome Guest, Not a member yet? Register   Sign In
Pre-populate update form with data from the database
#1

I am making a "Customers" CRUD application in CodeIgniter 3. I have an update form that I want to pre-populate with the data corresponding to the customer, already existent in he database.

The model looks like this:

Code:
class Customer extends CI_Model {
 /*Lots
   of
  code*/

public function getAllCustomers($customer_id) {
   $query = $this->db->get_where('customers', array('id' => $customer_id));
   if ($query->num_rows() > 0) {
       return $query->row();
   }      
 }
}

The controller looks like this:
Code:
class Home extends CI_Controller {

/*Lots
   of
  code*/

public function edit($customer_id){
   $this->load->model('Customer');
   $customer = $this->Customer->getAllCustomers($customer_id);
   $this->load->view('update', ['customer'=>$customer]);
}
}

In the view file (update.php) I have:
Code:
<?php echo form_input('first_name', '', [
           'type'  => 'text',
           'id'    => 'first_name',
           'class' => 'form-control',
           'value' => set_value($customer->first_name),
           'placeholder' => 'First name',
   ]);
?>

The customer's first_name, although existent in the the database column called "first_name" does not pre-populate the form.

Even more puzzling: 
If, in the view, I do 

Code:
<?php echo $customer->first_name; ?>


 it outputs the first-name correctly.




On the same view file 

Code:
'value' => set_value($customer->first_name)

 outputs nothing.


Why is this?
Reply
#2

Hi,

See the note here

So you need to pass your first mane as a default value like this:


PHP Code:
<?php echo form_input('first_name''', [
 
          'type'  => 'text',
 
          'id'    => 'first_name',
 
          'class' => 'form-control',
 
          'value' => set_value($customer->first_name,isset($customer->first_name)?$customer->first_name:''),
 
          'placeholder' => 'First name',
 
  ]);
?>
A good decision is based on knowledge and not on numbers. - Plato

Reply
#3

The set_value() helper function needs the field name as the first parameter, followed by the default value.
In your case:
PHP Code:
set_value('first_name'$customer->first_name
Reply




Theme © iAndrew 2016 - Forum software by © MyBB