1

Is there a way to make a domain class name human readable in Groovy/Grails? For example, I might have a class called LibraryBook and in the application views, it will be shown as "Create LibraryBook". Is it possible to make Grails show this as "Create Library Book"?

Chris Dix
  • 57
  • 8

2 Answers2

4

GrailsDomainClass has a naturalName property which you can use. You can also use GrailsNameUtils.getNaturalName() for properties' names.

Still, it's not localizable.

Usual convention is as @tim_yates mentioned, add messages like className.label = Class Name and className.propertyName.label=Property Name to messages.properties.

Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91
3

If you look at the top of your grails-app/views/libraryBook/create.gsp file, you will see something like:

    <g:set var="entityName" value="${message(code: 'libraryBook.label', default: 'LibraryBook')}" />

This shows you can set a libraryBook.label message property to override the default name of LibraryBook. This property should be set in the grails-app/i18n/message.properties file. The documentation for this can be found here.

As an interesting aside (and not the recommended best practice), you can alter the default grails scaffolding templates. First, you need to install the templates with:

grails install-templates

Then, you can edit the file src/templates/scaffolding/create.gsp (and list.gsp, etc) and change the line:

<g:set var="entityName" value="\${message(code: '${domainClass.propertyName}.label', default: '${className}')}" />

to

<g:set var="entityName" value="\${message(code: '${domainClass.propertyName}.label', default: '${className.replaceAll(/\B[A-Z]/){ " $it" }}')}" />

As you can see, this code:

className.replaceAll(/\B[A-Z]/){ " $it" }

Takes the CamelCase classname, and replaces all capital letters (apart from the first one) with the letter following a space character.

Then when you call generate-views or generate-all, the newly created gsp will have this default name with spaces in it

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 2
    is correct. however, I think he fails to mention that message properties are in the message.properties file in the i18l library. I also believe, that his second solution is an overkill, and it is not very internationaization friendly. – sbglasius Oct 18 '11 at 05:39
  • @sbglasius I should have worded my answer more strongly towards the first method rather than the second. The second was more of a demonstration of how the default scaffolding templates are configurable than a demonstration of the best practice... Sorry about that... I will alter my answer to make this more apparent, as this sort of advice that can be taken the wrong way (and lead people down the wrong path) helps no-one in the long run – tim_yates Oct 18 '11 at 08:40