Good day. I'm new to grails and groovy and what I'm trying to do is add a domain object (in my case an album object) to a different domain (cart). When the user clicks on the 'add to cart' link when viewing albums, the 'buy' action of the HomeController is supposed to create a duplicate of the album and put it into the Cart domain, except I have no idea how to do it. Here's what I got.
class HomeController{
def index(){
//displays a list of albums and a 'add to cart' link at each album in the list
}
def buy(){
//Here's where the code should go.
redirect(controller: "home", action: "index")
}
}
I think you need to give more thought into your domainClasses before attempting the views/controllers:
You have a domain object (in my case an album object) to a different domain (cart)
Domain classes:
class User {
String name
static hasMany = [orders:Orders]
}
Class Album {
String name
}
class Order {
User user
Album album
}
View: A controller action to show this:
<!-- by defining user.id and album.id when grails receives the .id it binds that id to the actual object so --!>
<!-- User user = params.user // is the user object bound to user.id --!>
<g:form action="save" controller="myController">
<g:hidden name="user.id" value="1"/>
<g:select name="album.id" from="${mypackage.Album.list()}" optionKey="id" optionValue="name"/>
<g:submitButton name="save">
</g:form>
Controller to receive that save action - the saving functionality should really be taken over to a transactional service = This is just to show you very basically:
package mypackage
class MyController {
def save() {
Order order= new Order(params)
order.save()
//
//User user=User.get(params.user.id)
User user=params.user
user.addToOrders(order)
user.save()
render "album added to order class and then order added to users class"
}
}