To empty the DB value when editing in Play

Asked 2 years ago, Updated 2 years ago, 118 views

I have created the following forms in playframework (2.5.6)

 case class User (age: Option [Int])

value form = Form(
  mapping(
    "age" - > optional (number)
  (User.apply) (User.unapply)
)
println(form.bindFromRequest().value)

I would like to set the DB value to NULL if an empty character is sent when editing the form, but if it is option [Int], I cannot determine if an empty character has been sent.
For example,

  • ?age=20:Some(20)
  • ?age=:None
  • None

So I don't know if it hasn't been sent when updating the DB or if I want to empty it...
What should I do?Please tell me the details.Thank you for your cooperation.

scala playframework

2022-09-30 19:45

1 Answers

I am not familiar with the Play form, but I will answer it.

form.bindFromRequest binds data from the body of the implicit request.

https://github.com/playframework/playframework/blob/2.5.6/framework/src/play/src/main/scala/play/api/data/Form.scala#L76-L88

In other words, it is possible to determine whether request.body contains data keyed with age.

If BodyParser is not specified, the request.body type is AnyContent, which is troublesome to determine.
Specify BodyParsers.parse.urlFormEncoded to allow retrieval as a Map as shown below.

defaultUser=Action.async (BodyParsers.parse.urlFormEncoded) {implicit request=>
  form.bindFromRequest().fold(
    errorForm=>{
      // error
    },
    user=>{
      if(request.body.contains("age")}
        // form sent "age"

      } else{

      }
    }
  )
}

case class User (age: Option [Int])

value form = Form(
  mapping(
    "age" - > optional (number)
  (User.apply) (User.unapply)
)


2022-09-30 19:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.