Is there a sample form submission?
In PHP, are there templates that people use to submit forms? Recommendations for form submission, etc.
For example, I am trying to perform a CRUD operation. I originally used the same function to handle 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 don't like ... about this practice, the login to check if there is a submit or a new form is in the same function.
I was thinking about creating two different functions
form1_add() and form1_add_submit()
to handle these operations. But other problems show up, for example when validation fails, I would have to call form1_add()
from again form1_add_submit()
to display these validation errors.
What other methods are used by people for this kind of operation? Are there any specific templates for these?
a source to share
The general principle, like any programming, is to keep your functions as atomic as possible. Doing multiple tasks within a single function just makes your job harder and harder to debug. Calling functions from another function is a great idea, and at least make the code clearer.
In terms of a concrete example, I always separate myself from displaying and submitting / validating a form from each other because they are completely different functionality. If you want "correct" validation, perhaps consider using JavaScript in the form itself, then just show a list of "errors" with PHP just above the form if the form's submission still doesn't match the input (allowing the user to correct them) ...
a source to share
I don't know of any "best practice" or "standard way of doing".
Personally, I use external functions to handle this.
If the user has submitted then I call userSubmited () etc. I also split them into separate files, so I can save it with a form cleaner (just a header, etc.).
Also, it might be a good idea to keep some of the form processing in one file and the UI in another to make it even cleaner.
a source to share