Welcome Guest, Not a member yet? Register   Sign In
Working with forms: best practice -- PART II
#1

[eluser]fMertins[/eluser]
Hi,

What do you use when creating forms to add and update records? Usually I prefer to have only one form/view page, both for including and updating records, instead of having one page only for add records and other page only for updating records.

With this approach, I have a "formState" variable indicating to the view page (form) wich operation needs to be done: add or update. When in add mode, all HTML inputs have the "value" attribute equal = "" (empty), and when in update mode, I populate the values with correspondent database information.

I think if using independent forms/view pages, when I need to change one, so need to change other too... Because this I think better to have only one page and control the "mode".

But a simple "problem" to deal with this pattern is because some situations, the add and update forms aren´t 100% equals... (ie: a field in add mode it´s disabled, while in update mode it´s normal) Usually I deal with making some IF´s...

I´d like to know from community what are your opinions and solutions :-) Thanks for all and sorry bad english...
#2

[eluser]BravoAlpha[/eluser]
I have something like this for a controller:
Code:
<?php

class Thing extends controller {
    
    function Thing()
    {
        parent::Controller();
        $this->load->model('Thing_model', 'thing');
    }
    
    function form($thing_id = FALSE)
    {
        if ($thing_id)
        {
            $thing = $this->thing->select_by_id($thing_id);
            
            if (!$thing)
                show_404();
        }
        
        // validation and whatever
        
        if ($this->validation->run())
        {
            // whatever
            
            if (!$thing_id)
            {
                // $this->thing->insert()
                // redirect
            }
            else
            {
                // $this->thing->update()
                // redirect
            }
        }
        else if ($thing_id && !$this->input->post('submit'))
        {
            // Load current values when updating an existing thing
            foreach($thing as $key => $value)
                $this->validation->$key = $value;
        }
        
        // whatever
        $this->load->view('whatever', $data);
    }
    
}

?>

Quote:(ie: a field in add mode it´s disabled, while in update mode it´s normal)
I have one field that's the opposite of that (it disabled when updating). I currently use this in my view:
Code:
<input type="text" name="thing_id" value="<?= $this->validation->thing_id; ?>" <?php if ($this->uri->rsegment(3)) echo 'disabled="disabled" '; ?>/>




Theme © iAndrew 2016 - Forum software by © MyBB