How to make a new empty form using Play boot forms? (Java)

54 Views Asked by At

Using Play and the play-bootstrap plugin, how does one make an empty to show on a page?

That is, if I have a data object Something, how do I make an empty form for it using play-bootstrap, so that user's can make a new Something?

(Consider a Comment, say, instead of a Something - not to edit, to create).

1

There are 1 best solutions below

0
On BEST ANSWER

In your Controller class, for whichever method is loading the page you want to see (and this is using Java)

public Result methodName(){
    Form<Something> aForm = formFactory.form(Something.class);
    return ok(twirlFile.render(aForm));
}

Where twirlFile is the twirlFile.scala.html template you want to use.

Within that you need some code that looks like this:

<div class="row">
        <div class="col-sm-3" ></div>
        <div class="col-sm-6" >
            @b3.form(routes.Controller.saveSomething) {
                @b3.text( form("name"), '_label -> "Title", 'placeholder -> "Enter Something name here" )
                @b3.text( form("description"), '_label -> "Description", 'placeholder -> "Enter short description here" )
                @b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-ok"></span> Save }
                @flash.get("success") 
            }
        </div>
        <div class="col-sm-3" ></div>
    </div>

As a bonus, if you didn't have any empty form, and wanted to put a hidden id in your form (representing the id field in `Something), add in:

@b3.hidden( "id", form("somethingId").value, 'attr -> false

So your form would then look like:

@b3.form(routes.Controller.saveSomething) {
    @b3.hidden( "id", form("id").value, 'attr -> false
    @b3.text( form("name"), '_label -> "Title", 'placeholder -> "Enter Something name here" )
    @b3.text( form("description"), '_label -> "Description", 'placeholder -> "Enter short description here" )
    @b3.submit('class -> "btn btn-default"){ <span class="glyphicon glyphicon-ok"></span> Save }
    @flash.get("success") 
}