Codeigniter: How to populate a form in a controller

I have been recently acquainted with Code Igniter, and I'm loving it. Having used Zend Framework 1 and 2, and various other PHP Frameworks Code Igniter is very robust and easy to use. Codeigniter comes with a very handy form_validation helper class which you can use to validate, and populate the values back into a view when validation fails. But, how do you populate the form values that are already made it to the database, and repopulating into an EDIT form?

The easiest way to do this is to manipulate the $_POST variable in the controller before dispatching to a view. CI's set_value function uses the value stored in the $_POST to populate the field value, so it works quite well.

For example, you may use this to populate the form fields retrieved from a database table.


// Assuming you're working in a Controller.
$post = $this->some_model->get($id);

... do all your logic here..
... use $data to populate non-field values, 
and $post to populate the form fields.

$_POST = $post;
$this->load->view($template, $data);

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.