我正在使用scala的playframework,我正在尝试构建表单但是会出现以下错误
“找不到隐式的MessagesProvider实例。 请参阅https://www.playframework.com/documentation/2.6.x/ScalaForms#Passing-MessagesProvider-to-Form-Helpers“ 这是我的index.scala.html
@(customerForm:Form[Customer])
@import helper._
@main("welcome") {
<h1>Customer Form</h1>
@form(action=routes.Application.createCustomer()) {
@inputText(customerForm("Credit Limit"))
@inputText(customerForm("Customer Name"))
<input type="submit" value="Submit">
}
}
这是我的应用程序控制器代码
package controllers
import play.api._
import play.api.mvc._
import models.Customer
import play.api.data._
import play.api.data.Forms._
class Application extends Controller {
def customerForm = Form(mapping("Customer Name" -> nonEmptyText,
"Credit Limit" -> number)(Customer.apply)(Customer.unapply))
def index = Action { implicit request =>
Ok(views.html.index(customerForm))
}
def createCustomer = Action { implicit request =>
customerForm.bindFromRequest().fold(
formWithErrors => BadRequest(views.html.index(formWithErrors)),
customer => Ok(s"Customer ${customer.name} created successfully"))
}
}
答案 0 :(得分:8)
播放框架表单处理在版本2.5和2.6之间已经改变,为了使事情工作,您必须更改Application类的声明,如下所示:
import javax.inject._
import play.api.i18n.I18nSupport
class Application @Inject()(val cc: ControllerComponents) extends AbstractController(cc) with I18nSupport
并在您的视图中添加隐式参数,如下所示:
@(customerForm:Form[Customer])(implicit request: RequestHeader, messagesProvider: MessagesProvider)
如果您在视图中不需要RequestHeader,则可以省略其声明。
有关详细信息,请参阅错误消息中的链接: https://www.playframework.com/documentation/2.6.x/ScalaForms#Passing-MessagesProvider-to-Form-Helpers
答案 1 :(得分:0)
我遇到了同样的错误,就我而言,我忘记了使请求隐式。我希望此答案对您有所帮助,如果您按照Achraf的回答更改了代码,但仍然出现错误。
def foo() = Action { implicit request =>
Ok(html.index(form))
}