Msgstr "getOrElse is not a member of String" in template

I have the following template code:

views /Login.scala.html:

@(loginForm: Form[views.Data])

@import mytemplates.loginform

@Main("") {
    email:@loginform(loginForm("email"))
    @*email:@loginForm("email").value.getOrElse("xyz")*@
}

      

view /mytemplates/loginform.scala.html:

@(emailField: Field)

@emailField.value.getOrElse("xyz")

      

views /Main.scala.html:

@(page: String)(content: Html)

<!DOCTYPE html>

<html>
    <body>
    @content
</html>

      

views / Data.java:

package views;

import play.data.validation.ValidationError;
import java.util.List;

public class Data {

    public String email = "";

    public Data() { }

    public List<ValidationError> validate() {

        return null;
    }
}

      

Compilation of the above completed successfully. But if the line @*email:@loginForm("email").value.getOrElse("xyz")*@

in Login.scala.html is not commented out, an error occurs value getOrElse is not a member of String

.

Why is this happening? I would like to exclude the pattern mytemplates.loginform

but cannot get it to work.

edit: Following the evaluation guidelines, I get this:

views /Login.scala.html:

@loginForm("email").getClass

: class play.data.Form $ Field

@loginForm("email").valueOr("").getClass

: class java.lang.String

view /mytemplates/loginform.scala.html:

@emailField.getClass

: class play.core.j.PlayMagicForJava $$ anon $ 1

@emailField.value.getClass

: class scala.None $

I had to use valueOr("")

in Login.scala.html , otherwise NullPointer execution exception will be thrown. Obviously these are different classes. I haven't used Play framework very often and I don't know what that means.

+1


source to share


1 answer


Since it looks like you have a Java project, the framework will do some automatic conversions here and there between Java classes and their Scala equivalent.

Try the following:

@loginForm("email").getClass()
@loginForm("email").value.getClass()

      

Make this change as Login.scala.html

well as on loginform.scala.html

, and you will find that you are dealing with different classes for each scenario.



When you go through the template loginform

, yours field.value

will be wrapped in an object scala.Some

, so it .getOrElse

compiles in this case. When you do this directly in the main view, you never leave the java class-world, so yours field.value

returns directly as String

.

If you are using the latest version of Play, you can use the method Field.valueOr

instead getOrElse

.

@loginForm("email").valueOr("xyz")

      

+5


source







All Articles