Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Grails service in a view?

Simple question : I have a service class (let's say helpersService) and a method def constructURI(params). How can I call this method from a template view.

I have tried the following code without success

<% def helpersService  = new HelpersService() // or def helpersService
%>
<img src="${helpersService. constructURI(params)}"/>

But I get the following result:

No signature of method: com.HelpersService. constructURI() is applicable for argument types...

or (in case I use def helpersService)

Cannot invoke method constructURI() on null object 

Any ideas?

like image 512
fabien7474 Avatar asked Oct 22 '09 13:10

fabien7474


2 Answers

Services are not intended to be used inside views. You could create a TagLib where you can get a reference to the service via dependency injection.

like image 77
Siegfried Puchbauer Avatar answered Sep 18 '22 17:09

Siegfried Puchbauer


An easier method, assuming your view is being rendered by a Controller, is to just pass a reference to the service from the action to the view within the model, i.e.:

class someController {
  def someService
  def someAction = {
    render(view: 'someView', model: ['someService': someService])
  }
}

It can then be used as you would expect within the view. For a template rendered by a view, obviously you need to pass the reference to the template as well. Just to be clear though, S. Puchbauer is right; services are not really supposed to be used within Views, and you may experience difficult to diagnose problems, especially related to transactions and the Hibernate session.

like image 24
Chris King Avatar answered Sep 17 '22 17:09

Chris King