Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to populate form data and validation data in Code Igniter?

I'm new to code igniter. I'm following the form validation tutorial found at: http://www.codeignitor.com/user_guide/libraries/validation.html

I find I am typing too much in the view to get the form to re-populate. For example, here's what one of my INPUT fields look like:

<input type="text" name="email" value="<?=$this->validation->email ? $this->validation->email : $array_db_values['email'] ?>" />

Basically, when the form first loads, it should show a value from the database. If the user alters the value and it fails validation, then the form should post the erroneously submitted value.

Does code igniter have a "cleaner" way of rendering this kind of output? Otherwise, I'm going to do something like this in my controller:

$array_db_values = getdbresults();
if($_POST['submit'])
foreach($_POST as $key=>$val)
$array_db_values[$key] = $val;

That way, if postback data exists, it will always override database values.

Then input fields in my view can simply be:

<input type="text" name="email" value="<?=$array_db_values['email'] ?>" />

Is there a better/native CI way to handle this scenario?

like image 286
John Avatar asked Jan 31 '10 14:01

John


2 Answers

I don't think a easier way exists, the best way IMO is to do something like this in your controller:

if (isset($_POST['submit']))
{
    $values = $_POST;
}

else
{
    $values = getdbresults();
}

No need to loop through the $_POST array, for short:

$values = (isset($_POST['submit'])) ? $_POST : getdbresults();

In your view, you do the same:

<input type="text" name="email" value="<?=$values['email'] ?>" />

Or use the Form helper:

echo form_input('email', $values['email']);
like image 93
Alix Axel Avatar answered Nov 18 '22 15:11

Alix Axel


Have you guys looked into the Datamapper Overzealous project?

http://www.overzealous.com/dmz/

It handles validation at the model level. In your form fields, you can set the value to come from the model (either from the database or from your previous post).

<input type='text' name='email' value='<?=$object->data_item ?>' />

I'm pretty new to CodeIgniter as well, but adding this library has made things much easier. That project also comes with a form extension that could really make things easier, but I haven't played much with it yet.

like image 1
someoneinomaha Avatar answered Nov 18 '22 15:11

someoneinomaha