• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add and Edit using the same form - avoiding code duplication

#1
[eluser]juddmuir[/eluser]
Hi,

I'm sure that this is common functionality:

- Form to add an entry
- Form to edit an entry

In the latter, you need to pass in the entry id; in the former obviously you don't.

What's the accepted best practice?
1. Generate two form views, essentially the same but with the extra hidden id field in the edit form - these two forms then get submitted to controller->add() and controller->edit() functions respectively, or
2. Use the same form, with a hidden id field, submit both the same controller function, then test for non-zero value of the id field to decide whether to add or edit?

Or something else entirely?!?

#2
[eluser]Kinsbane[/eluser]
What I do is use the Validation class and only one file for the form. Then I pass through the files from the Validation - and I use the following snippet to generate default values for Validation so when the form is an edit form, it uses the data from the database to populate the fields:
Code:
foreach ($event as $k => $v) {
            $data['event'][$k] = $v;
            $this->validation->set_default_values($k, $v);
            $fields[$k] = $v;
        }

Then, I also check my URL to see where I am - did the user click an add link, or edit link?

#3
[eluser]juddmuir[/eluser]
Sounds interesting - I couldn't find any reference to the set_default_values() function though :-(

How would you code that in the controller?

#4
[eluser]majidmx[/eluser]
in CI versions before 1.7 you had to define a
Code:
set_default_value()
function by yourself [at least I did so, may be I wasn't aware of any existing one], but in CI 1.7 you can easily use
Code:
set_value()
function, check This post


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.