Reputation: 1002
I've to display check box checked or not based on some logic which is more than 4 lines of groovy code ... I don't like to write it in GSP page..is there any taglib or some way I can extract the logic out of GSP page. where I could access model boject and request objects.
Upvotes: 1
Views: 798
Reputation: 12334
You have (at least) 3 options:
Model attribute
If you're only doing the complex logic for a single page or a single controller, do the logic in the controller method and pass the boolean result to the view through a boolean:
// in your controller
def myAction() {
[shouldDrawCheckbox: shouldDrawCheckBox(...)]
}
private boolean shouldDrawCheckBox(/* info for decision making */) {
// decision making
}
Service method
If you're going to access this identical logic from several controllers, you can extract the shouldDrawCheckBox
method into a service and again pass the result through the models.
class MyController {
def myService
def myAction() {
[shouldDrawCheckbox: myService.shouldDrawCheckbox(...)]
}
}
class MyService {
boolean shouldDrawCheckBox(...) {
// logic!
}
}
Custom Taglib
If you want to avoid passing the decision through the model, or if the logic is more generally applicable, you can create a custom taglib.
class MyTaglib {
static namespace = "my"
def myCheckbox = { attrs ->
// extract decision info from the attrs
// perform logic with info
if (shouldDrawCheckbox)
out << g.checkbox(attrs: attrs)
}
}
}
In your view:
<my:myCheckbox whateverYourAttribsAre="value" name="..." value="..."/>
Upvotes: 1
Reputation: 17371
Use the g:
namespace. http://grails.org/doc/2.2.x/ref/Tags/checkBox.html
<g:checkBox name="myCheckbox" value="${condition}" />
It doesn't get any simpler then this. All the logic should be done inside the controller.
All the data you need on a page can be passed by the controller. Just return a Map
.
class MyController {
def index() {
def someCondition = true
[request:request, condition:someCondition]
}
}
Upvotes: 0
Reputation:
A TagLib is a good palce to put your logic, you can pass what you need as attributes and do your test:
class MyTagLib {
static namespace = "my"
def somecheckbox= { attrs ->
def model = attrs.remove('model')
if() { //tests goes here
//you can also test if you need to mark the checkbox as checked
if() {
attrs.checked = "checked"
}
out << g.checkbox(attrs: attrs) //remaining attrs will be applied to the checkbox
}
}
}
myview.gsp
<my:somecheckbox model="${model}" name="checkboxname" value="${checkboxValue}" />
Upvotes: 1
Reputation: 50265
Ideally the logic should go to the controller which renders
the gsp and sets a flag in the model
object. If the gsp is a child of a template, then the flag has to pass through. DOM manipulations in view layer is not ideal when we have appropriate binding framework available in grails.
Upvotes: 0