Question

I am trying to use Play Framework with Ebean. I have quite simple Java class Subject:

@Entity
public class Subject extends Model {

    private static final long serialVersionUID = 1L;

    @Id
    public final int id;
    public String name;

    public Subject() {
        id = 0;
    }

    public Subject(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

And also I have simple edit form (views.subjects.edit.scala.html):

@(subjectForm: Form[models.entities.Subject], id: Int)
@import helper._
@main("Subject") {
@helper.form(action = routes.Subjects.save(id)) {
@helper.inputText(subjectForm("name"),'_label -> "Name")
<input type="submit" class="form-submit" value="Save">
<a class="button" href="@routes.Subjects.index()">Cancel</a>
}
}

Field id is not editable (it's primary key), that's why I don't like to show it in form input elements. So, when I saving edited Subject, I need to do something like

public static Result save(int id) {
    Form<Subject> form = subjectForm.bindFromRequest();
    if (form.hasErrors()) {
        flash("error", DATA_ERROR);
        return badRequest(edit.render(form, id));
    }
    Subject subject = form.get();
    if (id == 0) {
        // Add new record case
        subject.save();
    } else {
        // Edit existing record case
        Subject old = Subject.find.byId(id);
        if (old == null) {
            return notFound(NOT_FOUND);
        }
        old.setName(subject.getName());
        old.save();
        flash("success",
                String.format("Subject %s, %d saved",
                        old.getName(), old.getId()));
    }
    return redirect(routes.Subjects.index());
}

I have only one question. Is there any ways to get Subject instance from subjectForm with correct (original) id? Make additional requests to database for updating record seems like not a good solution. But when I gettting instance from subjectForm id always 0.

Was it helpful?

Solution

If you don't want to show it use a hidden field in the form:

<input type="hidden" name="id" value='@subjectForm("id").value' />

BTW: Fetching object and updating it is natural way for doing it, alternatively you can use SqlUpdate of Ebean for direct query like in these samples

edit: If you will pass hidden ID you can also try to save object in shorter version like:

Subject subjectFromForm = subjectForm.bindFromRequest().get();
subjectFromForm.update(subjectFromForm.id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top