tags:

views:

103

answers:

2

In PHP, Are there any patterns people use to submit forms? A form submission best practices.. etc.

Example, I am trying to achieve a CRUD operation. Initially I have been using a same function for handling form-display and form-submission

class Somecontroller extends Controller {

  function form1_add() {
    // if submit exist save it in database
    // else
    // display the form
  }

  function form1_edit() {
    // if submit exist save it in database
    // else
    // display the same form
  }
}

What I do not like.. about this practice is, the login to check if there is a submit or whether it is brand new form is in the same function.

I have thought about making two different functions

form1_add() and form1_add_submit()

to handle these operations. But other issues appear for example, on unsuccessful validation, I would have to call form1_add() from form1_add_submit() again to display those validation errors.

What other practices do people use for this kind of operation? Are there any specific patterns for these?

+1  A: 

The general principle, as with any programming, is to keep your functions as atomic as possible. Performing multiple tasks within a single function just makes your job harder, and makes it more difficult to debug. Calling functions from other function is a perfectly good idea, and will at least make your code easier to understand.

In terms of a specific example, I always separate from display and form submission/validation from each other, because they're totally different pieces of functionality. If you want 'pretty' validation, perhaps consider using JavaScript on the form itself, and then just displaying a list of 'errors' with PHP, just above the form, if the form submission still doesn't comply with the input (allowing the user to correct them).

James Burgess
This makes sense. I guess. I am just so impressed with the FormsAPI from drupal. Wondering if there was sth similar. Thanks for the comments.
bibstha
Find what works for you, and makes your code easiest to debug, and run with it. If that's some form of framework, great. If it's just your own code, also great!
James Burgess
A: 

I'm not aware of any "best practice" or "standard way to do" this.

Personally, I use external functions to handle this.
If user submitted then i call userSubmited(), and so forth. I also separate these into separate files, so I can keep the one with the form cleaner (just the header, etc).

Also, it might be a good idea to keep the form-processing part in one file, and the UI-display in another, to keep this even cleaner.

Hugo