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


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?!?

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:
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?

Sounds interesting - I couldn't find any reference to the set_default_values() function though :-(

How would you code that in the controller?

in CI versions before 1.7 you had to define a
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
function, check This post

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

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