Handling very long forms with Play 2

My application contains a large form with 18 fields. It is processed with a standard form display, for example:

val bigForm = Form( mapping( "id" -> of[ObjectId], "title" -> text, // And another 16 fields... ... ) ) 

And everything was fine, but today I decided to add another field, and here a problem arises - mapping cannot take more than 18 arguments.

What should I do then? I’m thinking about combining some fields into a structure, but an additional format requires an additional formatter, JSON serializer and deserializer, too much work. I am looking for a common solution, more fields will appear in the future.

Another solution that I think of is to manually process the form, without Form .

Are there any better solutions?

+4
source share
2 answers

You can use nested mappings like

 val bigForm = Form( mapping( "id" -> of[ObjectId], "title" -> text, "general" -> mapping( ... )(GeneralInfo.apply)(GeneralInfo.unapply), "advanced" -> mapping( ... )(AdvancedInfo.apply)(AdvancedInfo.unapply) ) ) 
+4
source

Another possibility is to use view objects and update only the part that was sent (for example, through separate forms or AJAX):

 val generalForm = Form( mapping( "title" -> text, ... ) ) def updateGeneral(id: ObjectId) = Action { implicit request => MyObject.findById(id).map { myObj => generalForm.bindFromRequest.fold( fail => BadRequest(...), form => { val newObj = myObj.copy(title = form.title, ...) MyObject.save(newObj) Ok(...) } ) }.getOrElse(NotFound) } 
+1
source

Source: https://habr.com/ru/post/1432274/


All Articles