Change display name of Grails Domain Class - grails

I have a one-to-one relationship, and have a combobox for selecting the other one. How do I change the display name of the combo box?
Here's a screenshot of the combo box, to make myself clear:
I'm new to grails, and are attempting to create a simple data-driven app for in house use.
Edit: My toString():
def toString = { "${naam} [${gemeente}]" }

Override the toString method of said domain class.
String toString() {
return this.name;
}

The sig needs to be String toString() { ... } (you are returning a def and it is a closure, not a method)

In grails, the select tag also has an optional attribute named "optionValue" that will allow you to define a bean field/property to display.

In Grails 3, the following works:
String toString() {
return "${name}"
}
in your example, this would be:
String toString() {
return "${naam} [${gemeente}]"
}
cheers!

Related

Grails data binding field exclusion

I am using Grails 2.5 and use Grails databinding in request methods.
For a basic example of the situation consider the following:
Domain class
class Product {
String field1
String privateField
}
Controller
class ProductController {
def update(Product productInstance) {
productInstance.save()
}
}
If I pass an existing Product to the controller like
{"id":3, "privateField":"newValue","field1":"whatever"}
the old value of privateField is overwritten. I want to enforce, that privateField is never bound from a request and avoid checking if the field is dirty.
Is there a mechanism in Grails to achieve this?
If I have to do the dirty check, how can I discard the new value and use the old one?
Pretty sure there's a "bindable" constraint.
http://grails.github.io/grails-doc/2.5.x/ref/Constraints/bindable.html
class Product {
String field1
String privateField
static constraints = {
privateField bindable: false
}
}
Should keep that field from binding automatically.
You can enforce which values are bound, but you'll need to change your method signature to get more control of the data binding process.
class ProductController {
def update() {
def productInstance = Product.get(params.id)
bindData(productInstance, params, [exclude: ['privateField']]
productInstance.save()
}
}

Customize sorting in criteria

I found grails criteria and want to customize sorting options.
E.g. I have domain Book and I want to make some criteria:
Book.createCriteria().list {
//some code like ilike('name', 'book')
...
order(params.sort, params.order)
}
I want to make specific sorting rule, e.g. by name.trim().
How can I do this?
Based on a solution provided here, by extending the hirbernate Order class, you can customize it to accept functions and use it with createCriteria.
I wont be surprised, if there is a nicer and easier approach since this source is pretty old and also Grails is cooler than this :D
First you need a class extending Hibernate Order:
Originally by:spostelnicu
public class OrderBySqlFormula extends Order {
private String sqlFormula;
protected OrderBySqlFormula(String sqlFormula) {
super(sqlFormula, true);
this.sqlFormula = sqlFormula;
}
public String toString() {
return sqlFormula;
}
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return sqlFormula;
}
public static Order sqlFormula(String sqlFormula) {
return new OrderBySqlFormula(sqlFormula);
}
}
Then you can pass instance of this class to your createCriteria:
def ls = Domain.createCriteria().list {
order OrderBySqlFormula.sqlFormula("TRIM(name)")
}
Note1: You can pass any formula to sqlFormula as long as the underlying database accepts it.
Note2: Using such approach might cause migration challenges.
Hope it helps

Grails : Overriding getter method in domain class

I can't override grails getter method and becoming crazy.
What I want is use a double value and a string value to get a formatted data, but when I'm typing my override method into String, the double value is null and when into double, it obviously get me an error because a String is returned !
I get a domain class like that :
class Project {
...
String currency
Double initialTargetAmount
...
}
First Override method (initialTargetAmount is null in this case) :
//#Override Comment or uncomment it does not make any change to the behaviour
public String getInitialTargetAmount() {
println "${initialTargetAmount} ${currency}" // display "null EUR"
"${initialTargetAmount} ${currency}" // initialTargetAmount is null
}
Second method :
//#Override Comment or uncomment it does not make any change to the behaviour
public Double getInitialTargetAmount() {
println "${initialTargetAmount} ${currency}" // display "1000.00 EUR"
"${initialTargetAmount} ${currency}" // Error : String given, Double expected
}
Any help is welcome.
Snite
Groovy has dynamic getters and setters.
So, initalTargetAmount field "creates" automatically a Double getInitialTargetAmount method. Which is why it works when you have the Double return Type. But when you set String, getInitialTargetAmount automatically refers to a field String initalTargetAmount which doesn't exist
Try changing the name of the method, for example getInitialAmountWithCurrency() and it will work. Maybe your best bet will be to override toString() method ^^
Your getter should be always the same type of your field, and it's noot a good approach to change the getter like this, because Grails (Hibernate internally) will understand that your object instance changed and will try to update it ( it will check the old and new values).
You're trying in fact is to have a String representation of your amount, so you have a couple of options to this:
1 - A new method
Creating a new method that returns String will not interfere in the hibernate flow and you can use it anywere.
class Project {
...
String currency
Double initialTargetAmount
...
String displayTargetAmount() {
"${initialTargetAmount} ${currency}"
}
}
2 - TagLib
Depending on your needs, you could create a TagLib to make this custom representations of your class. This can include html formatting.
class ProjectTagLib {
static namespace = "proj"
def displayAmount = { attrs ->
if(!attrs.project) {
throwTagErrro("Attribute project must be defined.")
}
Project project = attrs.remove('project')
//just an example of html
out << "<p>${project.initialTargetAmount} , ${project.currency}</p>"
}
}

How to access other filter values inside of a custom addXXXColumnCriteria?

I have a request to create a form filter that has two fields, one a freeform text
and the other a select. The value in the select will determine how to handle the value of the text is turned into a criteria.
I can create a custom addXXXColumnCriteria for either field, but how can I access the other field from within this function?
I suggest you not to use de addXXXColumnCriteria, but overwrite the FormFilter doBuildCriteria (Propel) or doBuildQuery(Doctrine) methods.
I have never used Propel, but I guess that works as good as for Doctrine.
For example:
class yourPropelFormFilter extends anyKindOfSfFormFilterPropel {
public function doBuildCriteria(array $values) {
$criteria = parent::doBuildCriteria($values);
// ... change the criteria behaviour with the $values array (do some print_r to $values to see how the data array is formatted)
return $criteria;
}
}
For Doctrine (remember to use the getRootAlias query method):
class yourDoctrineFormFilter extends anyKindOfSfFormFilterDoctrine {
public function doBuildQuery(array $values) {
$q = parent::doBuildQuery($values);
$rootAlias = $q->getRootAlias();
if(...) {
$q->innerJoin($rootAlias.'.RelationX rx')
->addWhere('rx.value = ?',$values['...']);
}
return $q;
}
}
Please, remember to return the criteria/query modified object!

Adding a method to a domain class

I have a domain class containing a couple of fields. I can access them from my .gsps. I want to add a method to the domain class, which I can call from the .gsps (this method is a kind of virtual field; it's data is not coming directly from the database).
How do I add the method and how can I then call it from the .gsps?
To add a method, just write it out like you would any other regular method. It will be available on the object when you display it in your GSP.
def someMethod() {
return "Hello."
}
Then in your GSP.
${myObject.someMethod()}
If you want your method to appear to be more like a property, then make your method a getter method. A method called getFullName(), can be accessed like a property as ${person.fullName}. Note the lack of parentheses.
Consider class like below
class Job {
String jobTitle
String jobType
String jobLocation
String state
static constraints = {
jobTitle nullable : false,size: 0..200
jobType nullable : false,size: 0..200
jobLocation nullable : false,size: 0..200
state nullable : false
}
def jsonMap () {
[
'jobTitle':"some job title",
'jobType':"some jobType",
'jobLocation':"some location",
'state':"some state"
]
}
}
You can use that jsonMap wherever you want. In gsp too like ${jobObject.jsonMap()}

Resources