i have been doing simple MVC tutorials for a while and i get the concept. But i am wondering, when a form is displayed in a view, how is the form processed? A code to check for form submission must be present in the view file, which doesn't really fit because view should just be for displaying output.
So when you have a form in a view file of an MVC framework, where should the code to check for form submission be?
Of course this depends on the specific framework, but this is rather typical:
form data is posted to a controller (like all requests)
data validation rules are defined in the model
the controller runs the data through the model for validation
if successfully validated, the controller does whatever it's supposed to do
if data is invalid, the controller pushes error messages for invalid fields to the view
the view just displays the error messages
The form submission can be handle in controller. check this
The code to check for and validate the form submission should be in the controller or the model, depending upon the type of data received from the form and what you're doing with it. That's the point of MVC. View files should contain only the barest amount of logic necessary to display the page.
I think the most common approach would be the controller, since it is the controller that handles all input data (via $_POST, $_GET etc) and then ultimately decides which methods to call to handle that input, and which view to output.
Related
I have a question related to form submission done in PHP application that's built in MVC architecture (self-written framework).
All examples that I've seen so far (including existing back-end frameworks) work this way that once form for adding record to database is submitted then certain method of controller is executed [say i.e. addRecord()], which triggers method of appropriate model. If everything goes OK then record is added and controller's method [addRecord() in this example] renders view of "index" page that displays table with records from database.
What I would like to achieve is to render view with form used to add records (the same that I used to add first record) instead of "index". Obviously I can do it easily by just rendering appropriate view from addRecord() (view with the form).
But the tricky point is when you check url you'll see the following:
The first time you enter it will be i.e.
http://project_name/my_controller/create
Once first form was submietted and you return to the view from addRecord() method then url will be:
http://project_name/my_controller/addRecord
What I would like to see is return to the original url, that is http://project_name/my_controller/create
Not sure if this is clear?
PS. Of course I could use AJAX call for form submission (that way I will stay at the same page) but perhaps it's possible to achieve the same without AJAX.
Thanks in advance,
On the controller you will want to submit to the addRecord route and do the processing. Have a check to make sure it was successful and on successful submission you can redirect back to the create route.
It is hard to give an example since you are using a custom made framework. I use slim which has a redirect method for a route. If what you have made does not have something like that then using should do the trick.
header('Location: '.$createUrl);
die(); //or exit
I am building a simple user registration form using the MVC design pattern, in PHP.
Can someone please advise if I have selected the correct areas for code implementation, as after some fair amount of reading I understand people often interpret the docs in different ways.
I understand there may be no wright / wrong answer here, but am just trying to get some feedback on how the majority would implement it.
Many thanks.
Model
Function containing PDO mysql insert query
View
HTML form markup with PHP self action and controller include
Controller
Data validation and php include of model function
yup there are different approaches to MVC... your concepts look correct except for the view which should not contain the controller include. It is the controller that includes the model and view. Furthermore, i would have put validations in the model itself.
Model : validation functions(return true or false if error) and insert query
View : html form only with data passed from controller
Controller: main entry point/file (e.g. registration.php)
The controller is the entry point which is where you include your view and model.
Basically in the controller,
you check if form is submitted or not.
If not submitted, display the view (i.e. the form)
if data submitted, do validation using model's validation functions.
If validation ok, execute sql in your model and redirect to success page or display a success message.
If validation is not correct, display your view and fill in your form with the submitted data.
But as i said, there are different approaches to MVC; e.g. you can do all validations in the controller itself instead of the model like you proposed.
A very basic question. I have a form in one file form.php, I post it to another file processForm.php which does the server-side validation and processing. I am not using any framework.
Now, in case of form validation failure, I need to display the form again with all the values prefilled, without using a javascript history.back() from the processForm.php. What is the clean and proper way to do this so that I have all the posted values available again in form.php and can prefill them?
This is easy if the form submission happens to the same page, but this is how I got this and I cannot make the submission into the same page. So what would you do? Store the values in session? Curl post? Send the values using GET to form.php?
Why or why not? Please mention pros and cons.
Go read up on the MVC pattern.
You can't implement an interactive program without implementing a model, a view and a controller - the point is that your code should be structured to implement each of the three concerns as a single entity, be that as functions (or function trees), classes (or class trees) or files. And the three components within the pattern should be structurally grouped.
So if you want to the user to arrive at (say) second page after successfully filling in a form at first page, but to stay on first page when the form fails the validation, then a simple way to implement this would be to have first page implement the model view and controller, i.e. to both populate/generate the form and be the target for the form. Then if it receives a valid request sent from the form, send a redirect to second page.
This avoids the need for each page to load and process the MVC code for the preceding page as well as the current one - although that approach reduces the number of round trips to the browser which can help with performance.
NB using POST does not preclude the use of variables in the URL - indeed, I recommend using GET variables to indicate the data you wish to manipulate and POST variables to show how they should be manipulated.
I have a custom MVC application/framework where each action is a function inside of a controller class.
I have a signup action which renders a view with a form requesting user details. On submit it posts to a processSignup action that validates the data and either inserts the user into the database and redirects to a success page or needs to redisplay the original view/form with the errors.
The signup action runs several queries and hands off a variety of data to the view. E.g. it needs to get a list of available countries that the user can choose in a drop-down, retrieve a list of suggested usernames based on the name they entered on a previous form, and retrieve other data from a model.
I'm trying to find out how I can avoid repeating all these queries and the render of the view in my processSignup action in the event of an error. What's the standard way to handle these situations? The signup action receives POST data from a previous form so I can't have the signup form submit to itself and branch based on GET vs POST.
I could just call the signup function directly and have it receive an optional parameter to differentiate between normal requests and ones for invalid forms but that seems hackish. How do other frameworks handle this scenario? I'm using PHP but this is more of a high-level question than one specific to the language.
Avoiding duplicate code certainly isn't unique to MVC frameworks. The standard approach would be to simply create a private function that both signup and processSignup call before rendering the view. Something like:
private function setCommonVars()
{
// set country, username arrays, etc...
}
As far as rendering the signup view, the flexible thing about MVC is that you can reuse views. Your framework should have a way of explicitly choosing a view within a controller method (e.g., $this->view = 'signup'). That way, if an error occurs in processSignup, you can choose the signup view before rendering.
I'm using the Zend Framework and I'm about to hack up some of my controller code to do something that seems like there should be a pattern for already.
Currently when I only have one form, the form's action points back to the same action and controller as the one that generated the page. The controller's action function then verifies the form and if verification succeeds, does the desired action. If verification fails, it doesn't perform the action and the page is re-generated using the form that was validated so error messages appear in the correct place.
My situation now is that I have an action/controller that creates two forms and a list of items to the view for display. The view displays the list (say, for example, a list of users) and shows the forms (add user and create role - just as an example). What is the correct "Zend Framework" way to handle this? Should each of the forms' actions be pointing back to the same action/controller? If so, how does one handle validation?
My guess (and how I'm going to proceed for now) is to point both forms back to the controller, figure out which form was submitted, validate that form only, perform action on validation, or re-generate view on failure.
Yes. Let each form have different submit name and validate them based on that. But beware, when you validate wrong form, the error messages will appear ;) So test carefully.
You can submit the two forms to the two different actions of the same controller, and extract the list generation to a third method, and call it from indexAction, and the both form submission actions.