How to create Domain class Instance in Grails? - grails

I have two Domain class in grails
class Quotation {
static searchable =true
static constraints = {
referenceNo(nullable:true)
dateOfRequest(validator: {return (it <= new Date())})
number(blank:false)
estimatedHours(nullable:true, blank:false, min:0)
}
int referenceNo;
Date dateOfRequest;
String number="11-120001Q01";
int estimatedHours;
String toString(){
return number
}
}
class Project {
static constraints = {
projectID(blank:false,nullable:false)
number(blank:true,nullable:true)
projectManager(blank:false)
teamLeader(blank:false)
teamMembers(blank:false)
sizeOfTeam(blank:false)
status(inList:["active", "closed"])
}
String projectID
Quotation number
String projectManager
String teamLeader
String teamMembers
Integer sizeOfTeam
String status
}
i want to print number and estimatedHours from Quotation class to be in Project class but it is only showing number.Can any one please tell me how to create an instance of Quotation in Project class and call the getter and setter methods of Quotation class?

Related

Creating Domain Relationships in Grails returns unable to resolve class error

Good day to all. I am very new in using grails and I have followed several tutorials for beginners using grails until I come up in creating domain relationships. However, I got stuck with this problem right now. I have 3 domain classes namely, todo, category and user. And as I defined their relationships, it returns me an error saying unable to resolve class. Please see my codes below. Please help. Thank you so much.
Todo.groovy Class
package todoScaff
class Todo {
String name
String note
Date createDate
Date dueDate
Date completedDate
String priority
String status
User owner
Category category
static belongsTo = [User, Category]
static constraints = {
name(blank:false)
createDate()
priority()
status()
note(maxsize:1000, nullable:true)
completedDate(nullable:true)
dueDate(nullable:true)
}
String toString() {
name
}
}
Category.groovy Class
package categoryScaff
class Category {
String name
String description
User user
static belongsTo = User
static hasMany = [todos: Todo]
static constraints = {
name(blank:false)
}
String toString(){
name
}
}
User.groovy Class
package userScaff
class User {
String userName
String fname
String lname
static hasMany = [todos: Todo, categories: Category]
static constraints = {
userName(blank:false, unique:true)
fname(blank:false)
lname(blank:false)
}
String toString(){
"$lname, $fname"
}
}
Since you've placed your domain classes in different packages, you must import the classes at the head of the file.
package categoryScaff
import todoScaff.Todo
import userScaff.User
class Category {
The same needs to happen in your other domain classes that reference classes outside the current package.

Grails check if a class has a static variable with a particular value

I have a class in grails like:
class Autoresponder {
static String TYPE_NONE = "none"
static String TYPE_GETRESPONSE = "GetResponse"
static String TYPE_MAILCHIMP = "MailChimp"
static String TYPE_AWEBER = "AWeber"
static String TYPE_INFUSIONSOFT = "InfusionSoft"
static String TYPE_ICONTACT = "iContact"
static String TYPE_SENDY = "Sendy"
static String TYPE_ACTIVECAMPAIGN = "ActiveCampaign"
static String TYPE_API_ACTIVATE = "activate"
static String TYPE_ONTRAPORT = "ontraport"
//rest of code
}
I want to simply find that the above class has a static variable with value AWeber.
How do I do it? Is there a way to fetch all static user defined variables in a class(and thereby compare each variable's value with what I want)?
EDIT:
Due to some technical reasons, I can not change class definition.
Just iterate over all static fields looking for the one with the desired value. As in the following groovy script example
import static java.lang.reflect.Modifier.isStatic
class Autoresponder {
static String TYPE_NONE = "none"
static String TYPE_GETRESPONSE = "GetResponse"
static String TYPE_MAILCHIMP = "MailChimp"
static String TYPE_AWEBER = "AWeber"
static String TYPE_INFUSIONSOFT = "InfusionSoft"
static String TYPE_ICONTACT = "iContact"
static String TYPE_SENDY = "Sendy"
static String TYPE_ACTIVECAMPAIGN = "ActiveCampaign"
static String TYPE_API_ACTIVATE = "activate"
static String TYPE_ONTRAPORT = "ontraport"
}
def getStaticAttributeWithValue(Class clazz, Object searchedValue) {
clazz.declaredFields
.findAll{ isStatic(it.modifiers) }
.find { clazz[it.name] == searchedValue }
}
assert getStaticAttributeWithValue(Autoresponder, "AWeber") != null
assert getStaticAttributeWithValue(Autoresponder, "NonExist") == null
If the function returns null, there is no static field with that value, otherwise, it will be not null. (actually it will be a object of type java.lang.reflect.Field)
There is another way to fetch all static attributes in your class, that is using groovy MetaClass, but the idea is the same
def getStaticAttributeWithValue(Class clazz, Object searchedValue) {
clazz.metaClass.properties
.findAll{ it.getter.static }
.find { clazz[it.name] == searchedValue }
}
This way you will get a groovy.lang.MetaBeanProperty instead
The easiest way would be to use GrailsClassUtils.getStaticFieldValue to see if a Groovy class in Grails has a static property with a given value.
The above utility class has other methods that you may also find helpful.
Try to go with MetaClass. Something like (not tested... just an idea):
String val
if(Autoresponder.metaClass.static.AWeber){
val = Autoresponder.AWeber
}
With MetaClass you can also edit the methods and statics in there. It should also be faster than reflections

How do you organize the fields in grails 2.4.4 including the static mapping relations?

Okay, so I understand how to organize the fields in grails without using the gsp pages by writing the fields in the constraints like so.
Class User{
String firstName;
String nickName;
static constraints = {}
}
this will make first name appear before nick name in the default scaffolding because f comes before n in the alphabet.
Class User{
String firstName;
String nickName;
static constraints = {
nickName()
firstName()
}
}
this makes nick name appear before first name in the CRUD model in scaffolding. It's the order you name the constraints.
Now, how do you make the relations appear in a specific order? For example if I had this
Class User{
String firstName;
String nickName;
static belongsTo = {company:Company}
static constraints = {
}
}
How would I rearrange this order? would it be done in constraints? I know it can be done in gsp page, but how would I do it here?
I'm pretty sure it's the same as regular fields...
i.e. if you want the order of the fields to appear as nickName, firstName, company you'd do this:
Class User {
String firstName
String nickName
static belongsTo = {company: Company}
static constraints = {
nickName()
firstName()
company()
}
}

command object no binding property

I am trying to implement some command object validation, but one property of command object is not binding its always return null
Domain class
package ni.sb
class PurchaseOrder implements Serializable {
Date dateCreated
Date dutyDate
String invoiceNumber
BigDecimal balance
String typeOfPurchase
Date lastUpdated
static constraints = {
dutyDate nullable:false, validator: { dutyDate ->
def today = new Date()
if (dutyDate <= today) {
"notMatch"
}
}
invoiceNumber blank:false, unique:true
balance nullable:true
typeOfPurchase inList:["Contado", "Credito"], maxSize:255
}
}
This is the command object
class PurchaseOrderCommand implements Serializable {
Date dutyDate
String invoiceNumber
String typeOfPurchase
static constraints = {
importFrom PurchaseOrder
}
}
Here is the controller action
def actName(PurchaseOrderCommand cmd) {
if (cmd.hasErrors()) {
println params.dump()
println cmd.dump()
return
}
}
dutyDate is not binding, after i try dumb() in params and cmd i get this
snippet params.dump()
dutyDate:2014-09-25
snippet cmd.dump()
dutyDate=null
I hope you can help me
If you inspect cmd.errors I expect you will see the error there.
If your date request parameters are formatted like "2014-09-25" and you are using a recent version of Grails then something like this should work:
import org.grails.databinding.BindingFormat
class PurchaseOrderCommand implements Serializable {
#BindingFormat('yyyy-MM-dd')
Date dutyDate
String invoiceNumber
String typeOfPurchase
}
Alternatively you could set "yyyy-MM-dd" as one of the default formats in Config.groovy.
// grails-app/conf/Config.groovy
grails.databinding.dateFormats = ['yyyy-MM-dd',
'MMddyyyy',
'yyyy-MM-dd HH:mm:ss.S',
"yyyy-MM-dd'T'hh:mm:ss'Z'"]
// ...
I hope that helps.

BootStrap.groovy content doesn't update the content

I'm new to Grails and study it via InfoQ's "Getting Started With Grails" book.
Running through it I've faced a problem with the BootStrap.groovy file:
I've edited it as the book says.
Run-app it - and the data I've entered into BootStrap.groovy has been shown.
I've updated the bootstrapping values but they are not changed.
No errors are shown in the console.
What I've tried:
exchanging def's places;
set Runner's class value to nullables;
changed .save(failOnError:true) to .save(flush:true).
Even after I've changed the Race class' bootstrapping values it looks like it hasn't been changed.
Looks like the value is taken from somewhere else than the BootStrap.groovy?
I use Grails 2.2.1 with a PostgreSQL DB.
The classes' code is below:
package racetrack
class Runner {
static constraints = {
firstName(blank:false)
lastName(blank:false)
dateOfBirth(nullable:true)
gender(inList:["M","F"])
address(nullable:true)
city(nullable:true)
state(nullable:true)
zipcode(nullable:true)
email(email:true)
}
static hasMany = [registrations:Registration]
/*static mapping = {
sort "email"
}*/
String firstName
String lastName
Date dateOfBirth
String gender
String address
String city
String state
String zipcode
String email
String toString(){
"${firstName} ${lastName} (${email})"
}
}
and
package racetrack
class BootStrap {
def init = { servletContext ->
def begun = new Runner(firstName:"Marathon",
lastName:"Runner",
dateOfBirth:"",
gender:"M",
address:"",
city:"",
state:"",
zipcode:"",
email:"me#me.ru"
)
begun.save(flush:true)
def zabeg = new Race(name:"Run SPB",
startDate:new Date() + 360*30,
city:"Moscow",
state:"Moscow",
cost:10.0,
distance:42.0,
maxRunners:10)
zabeg.save(flush:true)
}
def destroy = {
}
}
EDIT: could this be happening due to any generate-* scripts been run?
Race.groovy:
package racetrack
class Race {
static hasMany = [registrations:Registration]
String name
Date startDate
String city
String state
BigDecimal distance
BigDecimal cost
Integer maxRunners
static constraints = {
name(blank:false, maxSize:50)
startDate(validator: {
return (it >= new Date())
}
)
city()
state(inList:["Moscow", "Volgograd", "SPb", "NN"])
distance(min:0.0)
cost(min:0.0, max:100.0)
maxRunners(min:0, max:100000)
}
static mapping = {
sort "startDate"
}
BigDecimal inMiles(){
return distance*0.6214
}
String toString(){
return "${name}, ${startDate.format('MM/dd/yyyy')}"
}
}
BootStrap should be in grails-app/conf instead. Refer this.
Try to print the errors of the new instance you save by adding
print begun.errors
See if somethings comes up.
You need to remove
def index() { }
from the controllers.
I had the same issue. Now it is fixed.

Resources