How to enter a hard-coded value to the database? - grails

I have a few fields in my User.groovy model class
fName
lName
userName
pwd
yourTel
The user will be entering the first 4 fields shown above. The 5th field yourTel will be hardcoded.
def create() {
[userInstance: new User(params)]
}
How can I do it ?
This is what I already tried:
def create() {
userInstance.yourTel = "2323232"
params = userInstance.yourTe
[userInstance: new User(params)]
}
SAVE
def save() {
def userInstance = new User(params)
if (!userInstance.save(flush: true)) {
render(view: "create", model: [userInstance: userInstance])
return
}else {
def userRole = Role.findOrSaveWhere(authority:'ROLE_USER')
if(!userInstance.authorities.contains(userRole)){
UserRole.create(userInstance, userRole, true)
}
redirect(controller:"login", action : "auth")
}
}
MODEL
static constraints = {
...
yourTel blank:true , nullable: false

Your approach works too with a bit of tweak:
def create() {
def instance = new User(params)
instance.yourTel="2323232"
[userInstance: instance]
}
The [userInstance: instance] the left is the key that will be used by your models, the right hand side is what you are passing to it. Here you first create the new User(params) then bind it with params and then you can tweak it and pass it back to your model.
def save() {
def userInstance = new User(params)
// set the yourTel to some value
userInstance.yourTel="2323232"
if (!userInstance.save(flush: true)) {
render(view: "create", model: [userInstance: userInstance])

params is a map, so put your data like
params.yourTel="2323232"
or
params.put("yourTel","2323232")
Now your code becomes:
def create() {
params.yourTel="2323232"
[userInstance: new User(params)]
}

Related

Grails actions getting called twice

The getStarted action redirects to companyInfo action which renders companyInfo.gsp and immediately after the page rendering, companyInfo action getting called one more time. I don't understand what the problem is.
class MyController {
#Secured('ROLE_USER')
def getStarted(){
def renderParams = [view: 'getStarted', model: [:]]
if(request.method != 'POST') {
render(view: 'getStarted')
} else {
def company = new Company()
.......
redirect(action: 'companyInfo', params: [id: company.id])
}
}
#Secured('ROLE_USER')
def companyInfo() {
def renderParams = [view: 'companyInfo', model: [:]]
if (request.method != 'POST') {
renderParams.model.cmpId = params?.id
render(renderParams)
}
}
}
See this answer. Grails trys to map get* to properties. And when the controller is called grails tries to map getStarted to a property called started, calling the method. So, Never Use get**** as your action name

Cannot invoke method pullLogs() on null object when calling service in controller

I have search around stack overflow and have found some similar instances of my problem but there fixes done seem to work for mine. (example of simular one:Grails - Can't call service from Controller --> always get "Cannot invoke method on null object error")
My service can be summed up like this
class AuditService {
AuditService auditService
def sql
def dataSource
static transactional = true
def pullLogs(String username, String id) {
if(username != null && id != null) {
sql = new Sql(dataSource)
println "Data source is: " + dataSource.toString()
def schema = dataSource.properties.defaultSchema
sql.query('select USERID, AUDIT_DETAILS from DEV.AUDIT_LOG T WHERE XMLEXISTS(\'\$s/*/user[id=\"' + id + '\" or username=\"'+username+'\"]\' passing T.AUDIT_DETAILS as \"s\") ORDER BY AUDIT_EVENT', []) { ResultSet rs ->
while (rs.next()) {
def auditDetails = new XmlSlurper().parseText(rs.getString('AUDIT_EVENT_DETAILS'))
println auditDetails
}
}
sql.close()
}
}
}
The way im trying to call it is likes this
UserController {
def auditService
show(Long id){
def UserInstance = User.get(id)
//Also tried def auditResults = auditServices.pullLogs(UserInstance.username, UserInstance.id)
def auditResults = auditServices(UserInstance.username, UserInstance.id)
System.out.println(" "+ auditResults)
[UserInstance: UserInstance,params:params]
}
}
The error I get is
Class:
java.lang.NullPointerException
Message:
Cannot invoke method pullLogs() on null object
Im pretty stumped. (Query was given to me)
Any Ideas/Opnions/Help is greatly appriciated!
Thanks!
In UserController you have
def auditService
But then
def auditResults = auditServices(UserInstance.username, UserInstance.id)
which should be
def auditResults = auditService.pullLogs(UserInstance.username, UserInstance.id)
As for the "FactoryBean not initialized" error, for that you can simply remove the
AuditService auditService
from inside AuditService - it isn't necessary as you can just use this if you need a reference to AuditService from within its own code.
The name of your service is LogService or AuditService? If it's AuditService your attribute name in the controller have an s that shouldn't.
class UserController {
def auditService //Name should be the same of the service, not in plural
...
}

Deserialize a JSON object with support for embedded associations

Is there an easy way to deserialize a JSON string to a domain class with support of embedded association; belongsTo and hasMany
{
name: "Customer",
contact: {
name: "Contact"
}
}
class Customer {
name
Contact contact
}
class Contact {
String name
static belongsTo = [customer:Customer]
}
in my controller I would like to do the following
def save() {
def customer = new Customer(request.JSON)
customer.save();
}
Now i'm forced to do
def save() {
def contact = new Contact(request.JSON.contact);
def customer = new Customer(request.JSON);
customer.contact = contact;
customer.save();
}
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
Ref: http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html
you can try this
Test test
def result = new JsonSlurper().parseTest('yourString')
test = result
Try this will work.

How to save associated object in Grails?

I am a grails beginner.
i have a 2domain class
class Employee {
String name
String department
static constraints = {
}
public String toString() {
name
}
}
class Address {
String line1
String line2
Employee employee
static belongsTo = Employee
static constraints = {
}
}
where Address belongs to Employee .. so i have given belongsTo association.
My Employee/create.gsp page takes input for fields specified in Employee and Address.
so on creation of employee , address must be get save automatically .
so what could be the save action in EmployeeController
i have tried some thing like this but did not work.
def save = {
def employeeInstance = new Employee(params)
def addressInstance = new Address(params)
if (employeeInstance.save(flush: true)) {
flash.message = "${message(code: 'default.created.message', args: [message(code: 'employee.label', default: 'Employee'), employeeInstance.id])}"
redirect(action: "show", id: employeeInstance.id)
}
else {
render(view: "create", model: [employeeInstance: employeeInstance])
}
}
how to save this associated model ?
Here you have a one-to-one relationsip - add an address property to the Employee class.
class Employee {
String name
String department
Address address
public String toString() {
name
}
}
Change your belongsTo of the Address like this:
class Address {
String line1
String line2
static belongsTo = [employee: Employee]
}
Now you could create an Employee like this:
def employeeInstance = new Employee(params)
employeeInstance.address = new Address(params)
if (employeeInstance.save(flush: true)) {
// your logic
}
Read the docs (one-to-one relationship) for further informations.

The object of UserProifle cannot be saved for ShiroUser

I am working on a Grails app and I am trying to tie a ShiroUser with a UserProfile.
I have two models called ShiroUser and UserProfile. In my ShiroUser:
class ShiroUser {
... ...
static hasOne = [profile: UserProfile]
static constraints = {
email(nullable: false, blank: false, unique: true)
profile(nullable: false)
}
}
And in my UserProfile.groovy, I have:
class UserProfile {
... ...
static belongsTo = [shiroUser:ShiroUser]
}
However, in my ShiroUserController.groovy, when I try to create a new ShiroUser instance, this doesn't work so well. Here's my code:
def create() {
[shiroUserInstance: new ShiroUser(params), userProfileInstance: new UserProfile()]
}
def save() {
//todo add validation for email and password here.
def shiroUserInstance = new ShiroUser(params)
// Create a user profile
def userProfileInstance = new UserProfile()
shiroUserInstance.profile.email = params.email
shiroUserInstance.profile.firstName = params.firstName
shiroUserInstance.profile.lastName = params.lastName
if (!userProfileInstance.save(flush: true)){
render(view: "create", model: [userProfileInstance: userProfileInstance])
return
}
shiroUserInstance.profile = userProfileInstance
if (!shiroUserInstance.save(flush: true)) {
render(view: "create", model: [shiroUserInstance: shiroUserInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), shiroUserInstance.id])
redirect(action: "show", id: shiroUserInstance.id)
}
When I go to my application and try to create a new ShiroUser, the object cannot be saved. I updated the schema before I run the app so it should not be a migration issue. Any thoughts?
It looks like in this block of code you are assigning email, firstName and lastName to the wrong object:
// Create a user profile
def userProfileInstance = new UserProfile()
shiroUserInstance.profile.email = params.email
shiroUserInstance.profile.firstName = params.firstName
shiroUserInstance.profile.lastName = params.lastName
Try this instead:
// Create a user profile
def userProfileInstance = new UserProfile()
userProfileInstance.email = params.email
userProfileInstance.firstName = params.firstName
userProfileInstance.lastName = params.lastName
shiroUserInstance.profile = userProfileInstance
You should then be able to get away with just saving shiroUserInstance and it should automatically save userProfileInstance as well if you have your mapping set up correctly.

Resources