I have a form with 2 fields - empno
and name
. Both fill up with default value. When display in view, I want empno
is read-only and name
is editable.
In view creation, I am using @leaveform.value.get.empno
to display ready-only and work fine. The problem only occur during insert with error ([NoSuchElementException: None.get])
.
Questions:
@inputText
for read-only field?Refer below my code:
// ***** 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"))
}
Try this: <field name="branch_id" attrs="{'readonly': [('id', '>', 0)]}" required="1"/>. You need to first define the id field (it's an integer field) and put it in the view.
It is not mandatory to use the form helpers. If you use them you can pass the attribute readonly
or style the field with CSS to make it look read only.
Twitter bootstrap disabled by CSS:
@inputText(
editForm("createdOn"),
'id -> "createdOn",
'class -> "input-xlarge disabled",
'_label -> Messages("createdOn"),
'_help -> ""
)
Pass optional attribute: readonly
@inputText(
editForm("createdOn"),
'id -> "createdOn",
'class -> "input-xlarge",
'_label -> Messages("createdOn"),
'readonly -> "readonly",
'_help -> " This is read only"
)
You can also don't resend the field, but display its value:
<span class="date">Created on: @editForm("createdOn").value</span>
Update 2018-01-24
Play field is now returning a Optional
, see the docs. This means you can get the value from the field like:
@form("fieldName").getValue.get
(can throw a NPE
)@form("fieldName").getValue.getOrElse("defaultValue")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With