How do I fetch the label property of a domain from messages.properties. For example, I have a domain as following
class Books{
String name
String author
String description
String rating
}
And in message.properties I have the following
Books.name.label=Title
Books.author.label=Author
Books.description.label=Description
Books.rating.label=Rating
So can I do something like
def fieldName = Books.name.label
and get 'Title' ? Is there any way to do this ?
If you're in a Controller or Service, you can inject the bean
def messageSource
and then you can call:
messageSource.getMessage(code, args, defaultMsg, locale)
Related
I have an array of Persons (class contain name and lastname and id )
what I have to do is to return a string form this array but in a specific format an example will be more explicative
array=[PERS1,PERS2]
I need this as a return value : "The name of all persons : "+ PERS1.name + PERS1.LASTN + " , " + PERS2.name +PERS2.LASTN +","
I know this method
array.each{ |per|
#but this will not return the format ,and with each I think I can only print (I'm new in the ruby field
}
all of this because I need it when overriding to_s , because I need to provide a string -> to_s
def to_s
"THE name of all preson"+#array.each #will not work as I want
end
Thank you for ur time and effort and if you need any clarification please let me know
each just iterates over a collection and returns the collection itself. You may want to use map and join the result.
array.map { |person| "#{person.name} #{person.lastn}" }.join(',')
Or if you modify your Person class it can be even simpler.
# I assume that the name of the class is Person and name and lastn are always present
class Person
def full_name
"#{person.name} #{person.lastname}"
end
end
# Then you can call this method on `map`.
array.map(&:full_name).join(',')
Try this,
array.each do |per|
"#{per.name} #{per.LASTN}"
end
For more info check Interpolation
I'm doing integration tests for controllers in grails.I need to pass query string in test case and I'm passing it as controller.request.queryString for the same.
My tests is getting failed. It's giving me null value for the query String parameter.
Controller - UserExController
Foll is the action on which i'm doing integration testing.In this I'm reading query string parameter 'uid' and getting the userInstance using GORM method
def getUser() {
//reading the query string parameter 'uid'
def userId = request.getParameter("uid")
User user = User.findByUsername(userId)
render view:'edit', model:[userInstance:user]
}
This is the test for the above written action .In this I'm passing the query string parameter and calling the action
class UserInstanceTests extends GroovyTestCase {
#Test
void testPerfSummaryApi() {
def userExController=new UserExController()
userExController.request.queryString='uid=rp123'
userExController.getUser()
def model = userExController.modelAndView.model.userInstance
assertNotNull model
}
}
I'm getting groovy.lang.MissingMethod.Exception in the foll call:
User.findByUsername(userId) //userId is comming null
Change in Controller:
def userId = request.getParameter("uid")
to
def userId = params.uid
Change in int test:
userExController.request.queryString='uid=rp123'
to
userExController.params.uid='rp123'
Grails' dynamic binding helps in binding the query parameters to params and request to request in the controller.
This should make things work for you (tested on Grails 2.0.4):
userExController.request.addParameter('uid', 'rp123')
However, I would recommend to turn to dmahapatro's suggestion and refactor your controller to use params.uid instead of request.getParameter("uid"). Or even introduce a command object. The way you are doing it now just does not seem to be the standard Grails way.
I created a taglib to shorten input field code. It presets 'name', 'value' and others. Now I need to get a bean value, but the field holding that value is dynamic.
See some code (shortened to better work out my problem):
gsp:
<g:validatedInputField bean="${command}" field="surname" />
<g:validatedInputField bean="${command}" field="name" />
taglib
def validatedInputField = { attrs, body ->
def field = attrs.field
def bean = attrs.bean
if (field && bean) {
def val = bean.field
out << "<input type=\"text\" name=\"$field\" bean=\"$bean\" value=\"$val\">"
}
}
So the problem is the following line. It does obviously not work because there is no field 'field' in the bean. I want it to be dynamically replaced by 'name' or 'surname' or whatever the value of the param 'field' is.
def val = bean.field
I tried exprimenting with various GString/interpolation variations, but nothing worked.
Of course I could just add another param to pass the value, but I feel like it shouldn't be required as I already have everything I need to get it in the taglib...
Can you please give me some directions?
Thanks
In groovy, you can refer to a member of an object dynamically by using GStrings. For example:
def val = bean."${field}"
You could even perform some logic inside the GString. Let's say you have a default field and you want to use the name inside the 'field' variable only if it is not null:
def val = bean."${field ? field : "default"}
If bean is an object instance and field is a String that represent a member of that object, you can try something like:
def val = bean."$field"
I have a domain class called Application as follows:
class Application {
static hasOne = [resumption:Resumption, employee:Employee]
//Employee employee
Date startDate
Date endDate
Integer amountOfDays
String leaveRecommended
String leaveNotRecommended
Date supervisorDate
String toString(){
return "Application for ${employee.lastName}, ${employee.firstName}"
}
}
In the ApplicationController I'm trying to write a query that is going to find all applications that match a particular employee id. I do so as follows:
def applicationlist(){
if(!params.max){
params.max = 10
}
def query
def criteria = Application.createCriteria()
def results
query = { eq("employee_id", Long.parseLong("1")) }
results = criteria.list(params, query)
render(view:"employeeapplicationlist", model:[applicationlist:results])
}
Now I keep getting the error: "could not resolve property: employee_id"
I've checked the generated Application table in MySql, there is a column called employee_id with a value. The weird thing is I can access any other property (like amountOfDays), so what's the deal with employee_id? Why is it complaining that it cannot resolve the property? What am I missing? Thanks in advance.
Associations in the criteria DSL are of the form
Application.withCriteria{
employee{
eq 'id', 1
}
}
http://grails.org/doc/latest/guide/GORM.html#criteria
But you could probably just do:
def employee = Employee.proxy(1)
Application.findAllByEmployee( employee )
This appears a few times in the Grails User Guide as 'querying associations'
Oh well it looks like I'm still not fully adjusted to interfacing with the database on an Object level. For anyone else with this or a similar problem, here's the fix:
query = { eq("employee.id", Long.parseLong("1")) }
Sine the Application Domain class has one Employee, then we just need to access the id field of that employee. Remember we're in the ApplicationController.
I have been reading the various blog posts on how to deal with a Complex Type in EF including the brad wilson post which most everyone seems to link. owever i dont really get it. I am using EF code first development, MVC and VB. From what i have read so far to render a editor field for a complex types requires a custom object, right? However i dont really understand what code i need to put into the custom template. Can someone break it down for me as to what code needs to go into custom templete so i can render a textbox for the PostTags icollection?
My classes:
Public Class Post
Inherits EntityBase
<Key()> Property PostId As Integer
<DisplayName("Title")> <Required()> Property PostTitle As String
<UIHint("MultilineText")> <DisplayName("Text")> Property PostText As String
ReadOnly Property PostExcerpt As String
Get
If PostText.Length > 100 Then
Return Helpers.TruncateHelper.TruncateAtWord(PostText, 250)
Else : Return PostText
End If
End Get
End Property
<ScaffoldColumn(False)> Property PostDateCreated As DateTime
<ScaffoldColumn(False)> Property PostDateModified As DateTime?
<ScaffoldColumn(False)> Property PostDatePublished As DateTime?
<DisplayName("Publish?")> Property PostIsPublished As Boolean
<DisplayName("Allow Comments?")> Property CommentsAllowed As Boolean
<ScaffoldColumn(False)> Property CategoryId As Integer?
<UIHint("Text")> <DisplayName("Category")> <Required()> Property PostCategory As String
Property Comments As IList(Of Comment)
'Post has collection of Tags
<DisplayName("Tags (comma separated)")> Overridable Property PostTags As ICollection(Of Tag)
End Class
Public Class Tag
Dim _rdsqlconn As RDSQLConn
<Key()> Property TagId As Int32
Property PostId As Int32
Property TagWord As String
'Overridable property to access Post
Overridable Property Post As Post
End Class
Solved.
Created the template Tags.vbhtml in the EditorTemplates folder and applied to PostTags. the template has the textbox which is shown in the view.