Search code examples
javaplayframeworkplayframework-2.5

formFactory.form() doesn't exist ! PlayFramework


I've a little problem, i want to create a web app and i learn PlayFramework with java documentation of

This sample code :

public Result hello() {
    DynamicForm requestData = formFactory.form().bindFromRequest();
    String firstname = requestData.get("firstname");
    String lastname = requestData.get("lastname");
    return ok("Hello " + firstname + " " + lastname);
}

The ''formFactory'' doesn't exist.

https://i.sstatic.net/PeKRc.png

Why I don't have this field ?

And when i want to create a model, i don't have the model class

https://i.sstatic.net/hywdG.png

Thanks you so much if you resolve my problem ! :)


Solution

  • From the documentation:

    To wrap a class you have to inject a play.data.FormFactory into your Controller

    Play already knows about FormFactory, so just add a constructor parameter for it:

    public class FooController {
    
        private final FormFactory formFactory;
    
        @Inject
        public FooController(final FormFactory formFactory) {
            this.formFactory = formFactory;
        }
    
        public Result hello() {
            DynamicForm requestData = formFactory.form().bindFromRequest();
            String firstname = requestData.get("firstname");
            String lastname = requestData.get("lastname");
            return ok("Hello " + firstname + " " + lastname);
        }
    }
    

    I'm guessing the Model you mention is that of EBean. You need to enable EBean for your project, and then you'll have the necessary classes on your classpath.

    In project/plugins.sbt:

    addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "3.0.0")
    

    build.sbt:

    lazy val myProject = (project in file(".")).enablePlugins(PlayJava, PlayEbean)
    

    More information is available in the relevant docs.