I am trying to use a groovy function inside a GSP. Please help as I am about to tare my hair out here.
At the top of my GSP i have <%# page import = company.ConstantsFile %>
Inside my GSP I have
<p>
I have been in the heating and cooling business for <%(ConstantsFile.daysBetween())%>
</p>
and my ConstantsFile.groovy
package company
import static java.util.Calendar.*
class ConstantsFile {
def daysBetween() {
def startDate = Calendar.instance
def m = [:]
m[YEAR] = 2004
m[MONTH] = "JUNE"
m[DATE] = 26
startDate.set(m)
def today = Calendar.instance
render today - startDate
}
}
I have also tried changing renter to puts, system.out, etc but that isn't my main problem.
Error 500: Internal Server Error
URI
/company/
Class
java.lang.NullPointerException
Message
Cannot invoke method daysBetween() on null object
So I try
<p>
I have been in the heating and cooling business for <%(new ConstantsFile.daysBetween())%>
</p>
but then i get
Class: org.codehaus.groovy.control.MultipleCompilationErrorsException
unable to resolve class ConstantsFile.daysBetween # line 37, column 1. (new ConstantsFile.daysBetween()) ^ 1 error
Please someone help me or point me to a website that shows what to do.. I have tried googling and everything talks about a g:select or some other kind of tag... I just want to output the result of the function like I used to in the JSPs.
First, your GSP's import should be:
<%# page import="company.ConstantsFile" %>
Second, your daysBetween should be static (it makes more sense) and you don't render from anything but a controller:
class ConstantsFile {
static daysBetween() {
def startDate = Calendar.instance
def m = [:]
m[YEAR] = 2004
m[MONTH] = "JUNE"
m[DATE] = 26
startDate.set(m)
def today = Calendar.instance
return today - startDate
}
}
Third, access it in the following way:
<p>I have been in the heating and cooling business for ${ConstantsFile.daysBetween}</p>
And lastly, you should use a taglib for this. I'm editing my post now to add an example
class MyTagLib {
static namespace = "my"
def daysBetween = { attr ->
out << ConstantsFile.daysBetween()
}
}
Then use in your GSP
<p>I have been in the heating and cooling business for <my:daysBetween /></p>
Related
I have a method:
def nameToCode(nameStr){
def ret = resortService.getResort("all")
//this gets like 180 objects with various properties like name, code, etc.
def resorts = [name: ret.prName, code: ret.prProductIndex]
def code = resorts.findByName(nameStr) //this doesn't work
println(code)
return code
}
I'm trying to call this method and send it a name. It's then supposed to go find the name in the map, if it finds it it's supposed to return the name's code. This is supposed to be simple but I've been searching everywhere and can't figure out how to do this. I'll appreciate any help. Thanks
you are using a gorm method on a standard map:
Instead of :
def resorts = [name: ret.prName, code: ret.prProductIndex]
def code = resorts.findByName(nameStr) //this doesn't work
Try:
def resorts = [name: ret.prName, code: ret.prProductIndex]
def code = resorts.findAll{name==nameStr}
Registration domain has a collection of discounts.
static hasMany = [ discounts: Discount]
I want to extract all Registrations that have a particular discount applied.
In the following code i want to get all registrations whose collection has the discount of id disid. How can i achieve that? I appreciate any help!
def disid = Discount.get(1).id
def regs = Registration.createCriteria().list(){
eq('compositeEvent', cod.compositeEvent)
}
Try this:
def disid = Discount.get(1).id
def regs = Registration.withCriteria() {
discounts {
eq 'id', disid
}
}
See http://emmanuelrosa.com/articles/gorm-for-sqladdicts-where-clause/
I am new to Rails. Can someone please explain to me the concept of string concatenation using variables in view page and the controller?
For example :
In controller Code :
def show
#firstname = 'Test'
#lastname = 'User'
end
In view page :
Full Name : <%= "#{#firstname} #{lastname}" %>
For further details Click Here
Scenarios:- If you want to keep two variables on View page and add concatenation for those then use of space is necessary.
View page:
<%
var string_1 = "With"
var string_2 = "Rails"
var addition_1 = string_1 + string_2;
var addition_2 = string_1 + " " + string_2
%>
<h1> First Addition -> #{addition_1} </h1>
<h1> Second Addition -> #{addition_2} </h1>
Output :
First Addition -> WithRails
Second Addition -> With Rails
in view
<%
var1 = "ruby"
var2 = "on"
var3 = var1 + var2
%>
Finally
<% f_var = "Ruby #{var3}"%>
but this type of code is not recommended in view as it does not look good. You should use helper method for this type of requirement
The ability to use Pagination is the goal, however I'm not sure how to work with this. The relationship is unidirectional hasMany (seen below). As current it works fine without pagination (see Screenshot), but to work with pagination I have to change the controller to use createCriteria. This is where I come into difficulty as its quite strange for the relationship.
Domain
Class Tag {
String Tag
User user
static hasMany = [events: Event]
}
Controller
def searchTags() {
println("TAG CONTROLLER - Params sent on click of tag are: "+params.selected)
def results = Tag.findByTagAndUser(params.selected, lookupPerson())
//resultTotal is for show for the time being
[query: params.selected, results: results, resultTotal: 0]
}
GSP
<g:each in="${results.events}" status="i" var="t">
.... ommited as unnessary
</g:each>
//Not working yet due to confusing createCriteria issue
<div class="pagination">
<g:paginate total="${resultTotal}" />
</div>
I could do with a little guidance, this is what I'm thinking so far but I'm a little confused:
def tagCriteria = Tag.createCriteria()
def result = tagCriteria.list (max: 50, offset: 10) {
eq("tag", params.selected)
and {
eq("user", lookupPerson())
}
//Not sure what to do at this point compared with the findByTagAndUser(params.selected, lookupPerson()).events events being the hasMany relationship seen in domain
events {
}
}
Give this a try.
def searchTags() {
def tagCriteria = Tag.createCriteria()
def results = tagCriteria.list (max: 50, offset: 10) {
eq("tag", params.selected)
eq("user", lookupPerson())
projections {
property("events")
}
}
[query: params.selected, results: results, resultTotal: results.totalCount]
}
HQL version - The problem is you have to do the same query twice, but select the count(e)
Tag.executeQuery("""
Select e
from Tag t join t.events as e
where t.tag = :selected
and t.user = :user
""", [selected: params.selected, user: lookupPerson()], [max: 50, offset 10])
I've created a tmpl gsp tag containing a bit of markup that's used throughout the forms in my webapp (/shared/formRow.gsp). I'd like to reference this tmpl gsp tag in a groovy taglib I've created. Is this possible?
Here's the def from my taglib...
def checkboxRow = { attrs ->
def name = attrs.name
def value = attrs.value
def label = attrs.label
def defaultLabel = attrs.defaultLabel
out << "<tmpl:/shared/formRow name='${name}' label='${label}' defaultLabel='${defaultLabel}'>"
out << " ${checkBox(id: name, name: name, value: value)}"
out << "</tmpl:/shared/formRow>"
}
I realise the syntax is a bit different in taglibs (e.g. you need to do ${checkBox(...)} rather than ), but is it possible to reference your own tmpl gsp tag in a similar way? If so, what syntax would I use?
Well, it turns out that it's in the Grails documentation, here.
You should just call the render template method like this:
def formatBook = { attrs, body ->
out << render(template: "bookTemplate", model: [book: attrs.book])
}
Simple really!