mardi 12 septembre 2023

MVC - How to display POST data back into an edit view if errored?

I would like to know the best way in MVC to correctly organise the code when a user tries to update a record from an edit view, but it's errored and we want to display the POST data in the form so they can correct and re-submit.

Example:

  1. User clicks on a 'book' record (/book/123) which calls BookController->edit($id). This fetches the record and sends it's data to the view which displays a form for the user to update the details.
  2. User makes changes to the form details and hits submit. This calls BookController->update(). which validates the POST data. In this case, the user has created a validation error.
  3. User should then be re-presented with the edit form, on the same edit URL (/book/123) with the errors displayed as well as the POST data populating the form fields instead of the record's saved details.

In the past, I've used BookController->edit($id) to be responsible for both displaying edit form as well as handling the update POST. I'd usually do this by checking if POST data had been passed and if so, trigger the validation and updating.

But, I wonder if this is the best way or if there is a more correct/accepted way which ensures the user stays on the edit page with the POST data when they save. With an error/success message as required.

Thanks!

Aucun commentaire:

Enregistrer un commentaire