views:

466

answers:

5

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?

+2  A: 

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']);
Alix Axel
A: 

I'mm doing exactly the same as what you are doing. It's a bit cumbersome but not too bad imho.

stef
A: 

I felt the same way about laboring over forms, check out macigniter's Form Lib in the Ignited Code forums. It saves a ton of time and is really well-written.

miamisoftware
A direct link would be useful.
Alix Axel
A: 

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.

someoneinomaha
+1  A: 

If anyone is looking for macigniter's Form Generation library, mentioned in miamisoftware's answer, it's here:

http://codeigniter.com/forums/viewthread/107861/

dflock