我有一个包含2个字段的表单 - empno
和name
。两者都填充默认值。在视图中显示时,我希望empno
是只读的,name
是可编辑的。
在视图创建中,我使用@leaveform.value.get.empno
显示就绪且工作正常。只有在错误([NoSuchElementException: None.get])
的插入过程中才会出现此问题。
问题:
@inputText
以获取只读字段吗?请参阅下面的代码:
// ***** CONTROLLER *****//
val leaveform = Form[LeaveModel](
mapping(
"empno" -> nonEmptyText,
"name" -> nonEmptyText
)((no, empno) => LeaveModel(empno, name))
((leave: LeaveModel) => Some(leave.empno, leave.name))
)
def create = withAuth { username => implicit request =>
// Define default values
val empno = "STUDENT"
val name = ""
// Set default values
val filledForm = leaveform.fill(LeaveModel(empno,name))
Ok(html.leave.form(filledForm))
}
def insert = Action (
implicit request => {
leaveform.bindFromRequest.fold(
error => {
BadRequest(html.leave.form(error)) // Question 1. Here is the error.
},
leave => {
LeaveModel.insert(leave)
Redirect(routes.indexController.index())
}
)
}
)
// ***** VIEW START***** //
@(leaveform: Form[LeaveModel])
@leaveform.value.get.empno
@helper.form(
action = (routes.LeaveController.update(oid)),
'id -> "leaveform") {
@inputText(leaveform("empno")) // Question 2.
@inputText(leaveform("name"))
}
答案 0 :(得分:16)
使用表单助手不是强制性的。如果您使用它们,您可以传递属性readonly
或使用CSS设置字段样式,使其看起来只读。
CSS禁用Twitter引导程序:
@inputText(
editForm("createdOn"),
'id -> "createdOn",
'class -> "input-xlarge disabled",
'_label -> Messages("createdOn"),
'_help -> ""
)
传递可选属性:readonly
@inputText(
editForm("createdOn"),
'id -> "createdOn",
'class -> "input-xlarge",
'_label -> Messages("createdOn"),
'readonly -> "readonly",
'_help -> " This is read only"
)
您也可以不重新发送该字段,但会显示其值:
<span class="date">Created on: @editForm("createdOn").value</span>
更新2018-01-24
Play字段现在返回Optional
,see the docs。这意味着您可以从字段中获取值:
@form("fieldName").getValue.get
(可以抛出NPE
)@form("fieldName").getValue.getOrElse("defaultValue")
答案 1 :(得分:0)
将表单返回给用户时尝试使用Flash上下文:
def create = withAuth { username => implicit request =>
// leaveForm initialization as before
// use form data from flash if present
val form = if (flash.get("error").isDefined)
leaveForm.bind(flash.data)
else
leaveForm
Ok(stakeholders.register(form))
}
def insert = Action { implicit request =>
leaveForm.bindFromRequest.fold(
hasErrors = { form =>
Redirect(routes.Leaves.create). // put correct route here
flashing(Flash(form.data) +
("error" -> Messages("validation.errors"))) // customize error message
},
leave => {
LeaveModel.insert(leave)
Redirect(routes.indexController.index())
}
)
}
HTH,Erich