Search code examples
grailsgrails-ormgrails-domain-classgrails-controller

grails saving object with hasmany relation through form


I'm trying to create simple form for saving post with it's relations. Here is my domain models;

Post Model;

class Post {

  String title
  String teaser
  String content

  static belongsTo = [author: Person, category: Category]
  static hasMany = [tags: Tag] 

  static constraints = {
  }

}

Tag Model;

class Tag {

  String name

  static belongsTo = Post
  static hasMany = [posts: Post]

  static constraints = {
  }
}

I've created a form for saving post object through html form;

<g:form controller="posts" action="save" method="post">
  <div class="input">
    <label for="post.title">Title:</label>
    <g:textField name="post.title" />
  </div>
  <div class="input">
    <label for="post.teaser">Teaser:</label>
    <g:textField name="post.teaser" />
  </div>
  <div class="input">
    <label for="post.content">Content:</label>
    <g:textArea name="post.content" />
  </div>
  <div class="input">
    <label for="post.content">Category:</label>
    <g:select optionKey="id" optionValue="name" name="post.category" from="${categories}" noSelection="['':'-Choose Category-']"/>
  </div>
  <div class="input">
    <label for="post.tags">Tags:</label>
    <g:select optionKey="id" optionValue="name" name="post.tags" from="${tags}" noSelection="['':'-Choose Tags-']" />
  </div>
  <div class="input">
    <g:submitButton name="Create" value="Create" />
  </div>
</g:form>

And here is the controller logic;

def save() {
  def post = new Post(params.post)
  post.author = springSecurityService.currentUser
  if(post.save()){
    flash.message = "Post created successfully..."
    redirect(action: "index", method: "GET")
  }
  else{
    flash.error = "Something went wrong, please check the form again!"
    [tags: Tag.list(), categories: Category.list()]
    render(view: "create")
  }
}

With this way i can't save tags for post object.


Solution

  • I solved the problem with

    post.save(flush: true)
    

    here is the documentation about gorm save