Question

In Rails I can use accepts_nested_attributes_for to allow a single form to create two different but related objects. Now, I'm working on a Scala Lift project and I want to do something similar. I have a User model and an Address model. I want to have a single form that creates the User and their Address. How does this work in Lift?

Was it helpful?

Solution

In general, Lift approaches form processing by binding a handler function to each input which is called on form submission. In each of those functions, you would define the logic you need to set the appropriate fields in your model.

Using something like the example below you can instantiate your classes and then perform the appropriate action on submission. You will see this creates a User and an Address class and then sets a field on each of them. The function bound to the submit button will take care of persisting them both. Since the actions happen in a function, you can include as much logic as necessary to make your application work (data transformation, setting multiple fields, etc...). For example, in the submit logic I associate the id of the Address with the User to define how they are related.

In your Snippet

val user = new User()
val address = new Address()

".nameField" #> SHtml.input(user.name, (txt) => {
  user.name = txt
}) &
".addressField" #> SHtml.input(address.address1, (txt) => {
  address.address1 = txt
}) &
".submit" #> SHtml.submit("Save", () => {
  //persist address
  user.addressId = address.id
  //persist user
})

In your HTML

<form data-lift="form">
  <input class="nameField"></input>
  <input type="submit" class="submit"></input>
</form>

In general, that is how you would accomplish what you are looking to do. In addition to handling everything yourself, Lift includes Mapper which is pretty much a database ORM. I believe that can automate a lot of the relation mapping and make the creation of some forms easier. I don't really use it myself, so I can't give you a more concrete example. But, if you decide to check that out, you can find more information on Mapper here and here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top