Re-Populatin form with Codeigniter validation

Hi,

Im using Codeigniter Form Validation class to validate some forms.
The forms are used to store info on a db.

Im using the following code, to load all the values into the fields:

<?php echo ($ae == 'edit') ? form_input('name',$records[0]->name) : form_input('name', set_value('name')); ?>

So, if we are Editing the form, we load it with the value from the db.
If we are Adding, we use the set_value() function to set the value in case that an error msg appeared.

This works ok. But I want to see if there’s a better way of writting that line or doing this.

For example, one of the problems of this approach is that, if im editing a form and after submitting it I get an error, I lose all the info I just modified, and the db info is restored. Not a big deal though.

Thanks in advance.

There are several ways that it could be cleaned up.

  1. remove duplication

The form_input function is called with the same first parameter, so you could make just the one call and move the ternary down in to the function parameter instead.


<?php echo form_input('name',
    ($ae == 'edit') ? $records[0]->name : set_value('name')
); ?>

  1. Or, you could set up the variables before the output section.

$name = set_value('name');
// other form variables here too
...
if ($ae == 'edit') {
    $name = $records[0]->name);
    // and likewise, other form variables here too
    ...
}
...
<?php echo form_input('name', $name); ?>

  1. Or, you could instead pass $ae, ‘name’ and the record to a function, and determine what to pass back from within there.


function input_by_action($action, $name, $record) {
    $value = ($action == 'edit') ? $record->$name : set_value($name);
    return form_input($name, $value);
}
...
<?php echo input_by_action($ae, 'name', $records[0]); ?>

Others here may have better design-pattern oriented ideas as well.

You could use a temporary session array, $_SESSION[‘tmp’],
and when you post it setups up for example:
$_SESSION[‘tmp’][‘name’] = value;
$_SESSION[‘tmp’][‘other’] = value;

See if the values are filled in, otherwise use the DB data.
Then unset $_SESSION[‘tmp’] at the top of the page,
then recreate $_SESSION[‘tmp’] = array();

However, I can’t remember exactly but I thought code igniter had a built in way to pre-populate failed data, maybe that was only for Creating forms with nothing in the them though, rather than calling from the DB.

Thanks Paul, your number 1 option worked perfectly for what I needed. I didn’t know I can put an IF statement inside another function.
Option 3 also sounds good to arrange the code better.

JREAM,
Yes, the CodeIgniter set_value() function does that (pre-populate data). That’s what im using.
One thing about that function, that I just find out…if you are using it with the Validation Form class, it only works if the field has a validation rule.

Thanks to both of you.