Welcome Guest, Not a member yet? Register   Sign In
Form validation: loading default values (1st time), re-loading submitted values (thereafter): more efficient way?
#1

[eluser]aidehua[/eluser]
In a CMS-type application, I've got a form for editing content.

On first loading, the form is pre-populated from the database.

I have something like this in the controller:

Code:
$this->load->view('admin_static_edit', $data);

($data contains the values from the database)

and something like this in the view:

Code:
<textarea id="content" name="content"><?php echo $content); ?></textarea>

That works fine.

Then I want to add form validation, so if the form is submitted, but form validation fails, the form is re-loaded, this time with the submitted data displayed in place of the original database data.

The way I've seen this done elsewhere in these forums is to use the set_value() function, like this in the view:

Code:
<textarea id="content" name="content"><?php echo set_value('content', $content); ?></textarea>

Where the first parameter of set_value() represents the submitted data, and the second parameter represents the default value from the database (to use if the form validation has not yet run).

That seems to work fine: if the form is loaded for the first time, the default value is loaded from the database. If the form is re-loaded after failed validation, the submitted value is loaded.

But doing it this way means that I have to query the database each time the form is reloaded, to get the "default" values from the database - even though every time after the first time, I'm not going to load the database values into the form, only the submitted values.

This seems a pretty inefficient way to go about it. I have to pass some value for $content to the view, or I'll get an error.

In the controller, I could check to see whether the form has already been submitted; if it hasn't, build $data from the database; if it has, build $data with empty values (since they're not going to be used):

Code:
$data = array('content' => '');

etc.

But that seems pretty clunky.

Pretty much everyone must have to deal with this if you're building a form that lets you edit data in a database. What's the best solution?
#2

[eluser]OES[/eluser]
Well on the initial load only use the data from the database so in your controller check for the form posting. If no data only use the data from the database ie.

Code:
if($_POST){

    if ($this->form_validation->run() == FALSE)
    {
        $data['fields'] = $_POST;
    }else{
        // Success do whatever
    }

}else{

    $data['fields'] = $this->model->function_for_data();

}

Hope this helps !




Theme © iAndrew 2016 - Forum software by © MyBB