Reputation: 593
I've got the params that a user enter in a g:textField
in my controller when I call method save()
, and I need to use this value in my services. How can I pass the params that I have in my controller to my services or is possible pass this data directly to my services from my gsp??
I'm trying to pass the params equal than the gsp-Controller When I'm trying to access to the params in my Services, but I get an error: No such property: params
GSP:
<g:textField name="enterEmail" required=""/>
Controller:
save(){
def enterMail = params.enterEmail
}
Services:
def sendYourEmail(EmailTemplate emailTemplateInstance){
....
def enterMail = params.enterEmail
log.info "Sending email"
String source = 'myEmail'
Destination destination = new Destination([enterMail])
Content subject = new Content('test')
Body body = new Body().withHtml(new Content(output.toString()))
Message message = new Message(subject, body)
amazonWebService.ses.sendEmail(new SendEmailRequest(source, destination, message))
}
Upvotes: 0
Views: 1570
Reputation: 20699
pass params
as an argument to your service method, as it's only accessible from controllers or taglibs
UPDATE:
code sample
controller
def yourService
def save(){
service.sendYourEmail emailTemplateInstance, params
}
service:
def sendYourEmail( EmailTemplate emailTemplateInstance, params ){
def enterMail = params.enterEmail
....
}
Upvotes: 0
Reputation: 350
The params attribute you are using in your controllers is a dynamic attribute Grails added for you at runtime. You can't use from a service class.
It's a bad idea to get the params from a service, but you can do that using this line:
org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes().params
A good idea is to use a command: a plain groovy/java object with your parameters bound from the request, and send this command to the service. Doing that, you remove the dependency between your service class (business layer) and the params map (web layer): it will be easier to test and reusable from other parts (you can create the command whatever you want).
Command:
class MailCommand {
String enterEmail
}
Controller:
def mailService
def save(MailCommand mailCommand){
mailService.sendYourEmail(mailCommand, mailTemplate)
}
MailService class:
def sendYourEmail(MailCommand mailCommand, EmailTemplate emailTemplateInstance){
def enterMail = mailCommand.enterEmail
...
}
More information: http://grails.github.io/grails-doc/latest/guide/single.html#commandObjects
Upvotes: 1