Hi there i am still very new to grails and I have not been able to figure out why this is happening.
I have a domain class:
package scheduler
class Client {
String name
static constraints = {}
}
And a controller:
package scheduler
class AdminController {
def create() {
def client = new Client(name:"John")
println client
}
}
Currently I am always getting null for client. Originally the above was a little more complex on the domain class side but I systematically dumbed it down to see if it was a problem there. I still can not get the above working.
The output is always
scheduler.Client : null
Please let me know if I need to provide anymore information.
It's not null, that's just the default output of the toString method that Grails adds. It prints the class name and the id. Since you haven't saved the instance, the id is null. If the instance was null the output would have been null, not scheduler.Client : null
If you want to see the data in the instance, use the Groovy dump() method, e.g.
def client = new Client(name:"John")
println client.dump()
You could also add a toString method that includes the name attribute, e.g.
package scheduler
class Client {
String name
String toString() { name }
}
Related
I have created a brand new Grails 4.0.0 app and created a domain / controller using the grails cmd. I've also created a simple service that returns "Hello World" to the controller, which then renders this to the screen. However I get "Cannot invoke method on null object" when trying to call the service method - seems like the dependency injection isn't working properly.
I've tried declaring the service using "def", I've also tried declaring by class name - neither of which seem to work.
package uk.org.pmms
import grails.gorm.transactions.Transactional
#Transactional
class HelloWorldService {
def hello() {
return "Hello World"
}
}
package uk.org.pmms
class ClientController {
//static scaffold = Client
def helloWorld
def show(Long id){
Client clientInstance = Client.get(id)
respond ("client": clientInstance, "message": helloWorld.hello())
}
}
I expect the controller to return the clientInstance data and a string "Hello World" which are displayed on a GSP page.
When I remove the "message:" part of the respond statement it displays the client information correctly so it is definitely just the service call that is the problem.
The name of the bean created for your service would be helloWorldService
class ClientController {
def helloWorldService // <--- corrected bean name for auto wire by name.
def show(Long id){
Client clientInstance = Client.get(id)
respond ("client": clientInstance, "message": helloWorldService.hello())
}
}
I recently posted a question about multiple data sources. Things were going well until I hit this issue:
Controller
def doSomething() {
def user=userService.getCurrentUser()
}
Service
class UserService {
def getCurrentUser() {
def principal = springSecurityService.principal
String username = principal.username
return find(username)
}
def find(String user) {
return User.find{username==user}
}
}
This had been working previously on single DataSource but now with both enabled I see this on the browser:
Error 500: Internal Server Error URI /xxx/xxx Class
org.springframework.beans.factory.NoUniqueBeanDefinitionException
Message No qualifying bean of type
[org.springframework.transaction.PlatformTransactionManager] is
defined: expected single matching bean but found 3:
transactionManager,transactionManager_countrycity,$primaryTransactionManager
Okay this is now resolved.
I think I found the issue: under grails 3 with multiple data sources if you have this import :
import org.springframework.transaction.annotation.Transactional
You will run into the above problems:
If you how ever have :
import grails.transaction.Transactional
things will work as expected. I hadn;t paid attention and let ide choose wrong declaration
I am using the GSON type converter in a filter as follows...
def account = new Object(){
String firstName, lastName
};
if(springSecurityService.isLoggedIn()){
account.setFirstName(springSecurityService.principal.givenName);
account.setLastName(springSecurityService.principal.familyName);
}
String test = account as GSON;
But test is always null, even thought the object is populated properly. I don't like all the extra data in the normal JSON serializer. So does anyone know why this does not work?
UPDATE
I get the following when converting to JSON...
Caused by: java.lang.IllegalAccessException: Class org.codehaus.groovy.grails.web.converters.marshaller.json.GenericJavaBeanMarshaller can not access a member of class org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor with modifiers "public"
I want to use g.formatNumber in service, I have tried a below method, Which i got online. This is not working, its giving me the error "Cannot invoke method formatNumber() on null object", The code is below
import org.springframework.beans.factory.InitializingBean
class MyService implements InitializingBean {
boolean transactional = false
def gspTagLibraryLookup // being automatically injected by spring
def g
public void afterPropertiesSet() {
g = gspTagLibraryLookup.lookupNamespaceDispatcher("g")
assert g
}
def getFormattedNumber(){
def number = g.formatNumber(number: 5000,234 , type: "number" , maxFractionDigits: 2)
return number
}
}
How to do this.
I want to use g.formatNumber in service
Rather than jumping through the hoops you need to use a taglib within a service, it would be simpler to just use java.text.NumberFormat directly
NumberFormat format = NumberFormat.getNumberInstance()
format.maximumFractionDigits = 2
def number = format.format(5000.234)
If the service method is being called from a web request handling thread then you may wish to use the LocaleContextHolder to get the correct locale for the current web request, rather than just using the server's default.
This should work
def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib');
You will of course need grailsApplication injected by defining it ala
def grailsApplication
Grails 2.1.1
I can't seem to get a command object to be injected with a service so that I can use custom validator. I've tried several things, including
Grails command object data binding and
what the 2.1.1 docs on custom validator suggest, I just can't figure this one out..
Relevant Code:
class RegistrationCommand {
String username
def registrationService
static constraints = {
username validator: { val, obj ->
obj.registrationService.isUsernameUnique(val) }
}
}
class RegistrationService {
def isUsernameUnique(username){
def user = new User(username:username)
user.validate()
if(user.errors.hasFieldErrors("username")){
return false
}else{
return true
}
}
Resolved.. Issue was due to plugin.
I'm using a plugin for client side jquery validation (jquery-validation-ui-1.4.2). The command object being created by the plugin's controller wasn't getting injected with the service. The issue was reported https://github.com/limcheekin/jquery-validation-ui/issues/17 . The fix does work but has not been pushed upstream yet.