Question

I am new with grails and am developing a web application.

I have a List of long values which is getting from ids of Domain class objects.

Initially this List is like [1,2,3]. I need to use this list of values in my service class for saving the associations.

But the same List is getting in service class as [49,50,51]

Why this difference of 48 is occurred? and how can i get the List as same as i sent.

Controller class:

def createQuestion(CreateQuestionCommand createQuestionCmd) { 
  if( createQuestionCmd.hasErrors() ) { 
    render(view:"create_question", model:[createQuestionCmd:createQuestionCmd , tags:Tag.list()]) 
  } else { 
    Question question = new Question() 
    question.title=createQuestionCmd.title 
    question.description=createQuestionCmd.description 
    List tags= createQuestionCmd.tags 
    question = questionService.create(question,tags) 
    render(view: "question_submitted") 
  } 
}

service class:

def create(Question question, List<Long> tagId) { 
  List<Tag> tagList=getTagsById(tagId) 
  question.save( failOnError:true ) 
  Iterator itr=tagList.iterator(); 
  while(itr.hasNext()) { 
     Tag tag=itr.next() 
     question.addToTags(tag).save() 
  }
}

def getTagsById(List tagId){ 
  Iterator itr=tagId.iterator(); 
  List<Tag> tags 
  while(itr.hasNext()) { 
    long id=itr.next() 
    println "value of id is : " 
    println id 
    println id.getClass().getName() 
    Tag tag=Tag.findById(id) 
    tags.add(tag) 
  } 
  return tags 
}
Was it helpful?

Solution

CreateQuestionCmd.tags are List<String> and you are trying to place that to List<Long>

OTHER TIPS

Just pass the object to service and create question object.In groovy we create the object in map format.In java only, we need iterator to loop collection.In groovy we use each closure to loop the collection. Try it will work out. Any problem in the following code let me know.I will help.

Controller class:

def createQuestion(CreateQuestionCommand createQuestionCmd) { 
  if(createQuestionCmd.hasErrors() ) { 
    render(view:"create_question", model:[createQuestionCmd:createQuestionCmd , tags:Tag.list()]) 
  } else { 
    questionService.create(createQuestionCmd) 
    render(view: "question_submitted") 
  } 
}

service class:

def create(def createQuestionCmd) { 
   def question = new Question(title:createQuestionCmd.title,description:createQuestionCmd.description) 
   question.save(flush:true)    
   List tagIds= createQuestionCmd.tags 
   tagIds.each{
      def tag=Tag.findById(id) 
      question.addToTags(tag).save(flush:true) 
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top