<g:checkBox> click calling a controller function - grails

When the user clicks on the checkbox, I want to call a controller function and pass the current status of checkbox, whether it's checked or not.
I know how to do this using jQuery but I want to do this from the checkBox itself.
<g:checkBox id="customer_checkbox" name="customer_checkbox" value="${checked}" />
Controller function to be called:
class updateController {
def updateIndex () {
// do something
}
}

U need to use remoteFunction from grails taglib. This tag generate for u ajax function:
<select from="[1,2,3,4,5]" onchange="${remoteFunction(action: 'updateIndex', controller:'update',options: '[asynchronous: true]'}" />
For more information go to docs

The checkbox would be a part of the form. Use javascript to invoke the action.
<g:form name="formName" controller="updateController" action="updateIndex">
<!-- Other form elements -->
<g:checkBox id="customer_checkbox" name="customer_checkbox" value="${checked}" onChange="document.getElementById('formName').submit();"/>
</g:form>

Related

Grails <g:if> in <g:select>

I have this <g:select> in a .gsp file. But unlike any ordinary <g:select>'s this one would have the attribute disabled="" if a certain condition is met.
Following the code:
<g:select name="test"
from="${["foo1","foo2"]}"
<g:if test="${true}">disabled=""</g:if> />
It returned an error: Grails tag [g:select] was not closed
But when I change it into this:
<g:select name="test"
from="${["mu1","mu2","mu3"]}"
${ if(true) { println "disabled=\"\"" } }/>
It returned this error: Attribute value must be quoted.
Both of the error message are under the exception, org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
The question is how could we make this work? Is there a possible answer without using a custom TagLib?
The GSP form field tags treat disabled as a boolean property, so you can say
<g:select .... disabled="${true}" />
Generally you should be able to use any expression under the usual Groovy-truth rules but I believe it makes a special case for the strings "true" and "false" (the latter would normally be considered true under Groovy-truth rules as a non-empty string). If in doubt you can always say
disabled="${(someExpression) as boolean}"
No need to use the println, try this
<g:select .... ${(conditional)?"disabled":""} ... />
<g:select disabled="${true}"...
is fine but when you submit and it is a required field the value will not be submitted so use this jQuery code to enable the field when pressing the submit button
$(function() {
$('form').on('submit', function() {
$(this).find(':disabled').removeAttr('disabled');
});
});

How can a custom-validator know which commandButton was clicked

my form has several "submit" buttons,
and the validation of some of the fields depends on which was pressed.
How can I find that out in my custom validator?
The button's client ID get also generated as name of the <input type="submit">. The name=value of the pressed <input type="submit"> get also sent as request parameters. So you could just check for that in the request parameter map.
E.g.
<h:form id="formId">
...
<h:commandButton id="button1" ... />
<h:commandButton id="button2" ... />
</h:form>
with the following in validate() implementation:
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
if (params.containsKey("formId:button1")) {
// Button 1 is pressed.
}
else if (params.containsKey("formId:button2")) {
// Button 2 is pressed.
}
For JSF there will be inbuilt validation messages which will get displayed during Errors..or you can use Validation attributes like "validator & validatorMessages " in primefaces in their respective Tags.

Grails: disable g:datePicker

How does one disable g:datePicker when the page loads?
The code is supposed disable the datePicker when a variable (isCurrent) is true.
<g:if test="${!isCurrent}">
<g:datePicker name="endDate" precision="month" value="${projectInstance?.endDate}" years="${2005..2050}"/>
</g:if>
<g:else>
<g:datePicker name="endDate" precision="month" value="${projectInstance?.endDate}" years="${2005..2050}" disabled="disabled"/>
</g:else>
Don't create the date picker in your <g:else>. Just create a hidden input. If you want it to look the same as a disabled date picker, you can build it without input elements so it will be display-only.
you can also computer wheater or not you want to disable the date picker in the backing controller and pass it into the date picker tag.
view.gsp
<g:datePicker disabled="${diabled}" .... />
controllerView.groovy
def view = {
disabled = true
if (isCurrent)
disabled = false
[disabled, disabled]
}
the javascript call above works nicely as well
disabled="disabled" is the attribute of select not datepicker. Datepicker won't pass along that attribute to your select tags. However, what you can do is to disable your selects using javascript. For example if you are using jQuery you can do something like this:
note: in my example, isCurrent is string change yours accordingly. Put this in the html body after the datepicker tag.
<script type="text/javascript">
if ("${isCurrent}"=='true'){
alert("${isCurrent}");
$("#endDate_month").attr('disabled','disabled')
$("#endDate_year").attr('disabled','disabled')
}
</script>
or just use the select tag directly.

How to find indication of a Validation error (required="true") while doing ajax command

I have a form inside a dialog which I close by clicking on commandbutton with ajax ,
like this
<h:commandButton value="Add" action="#{myBean.addSomething(false)}"
id="add_something_id" >
<f:ajax render="#form someTable" execute="#form"
onevent="closeAddNewSomethingDialogIfSucceeded"></f:ajax>
</h:commandButton>
and here is the js code for closing the dialog
function closeAddNewSomethingDialogIfSucceeded(data) {
if(data.status === 'success') {
$("#dialog_id").dialog("close");
}
}
No problems till here...
Now I changed some of the dialog form fields into required="true" and now I want to prevent the closing of the dialog of i got validation errors...
But the ajax data.status still reaches its success state , and I can't figure out what indication of validation failure I can hook on...
any ideas?
Thanks to BalusC answer I did the following:
in JSF , added :
<h:panelGroup id="global_flag_validation_failed_render">
<h:outputText id="global_flag_validation_failed" value="true"
rendered="#{facesContext.validationFailed}"/>
</h:panelGroup>
the f:ajax was changed into
<f:ajax render="#form someTable global_flag_validation_failed_render"
and in js added the following check
if(data.status === 'success') {
if($("#global_flag_validation_failed").length === 0){
$("#dialog_id").dialog("close");
}
}
Not specifically for required="true", but you can check by #{facesContext.validationFailed} if validation has failed in general. If you combine this with checking if the button in question is pressed by #{not empty param[buttonClientId]}, then you can put it together in the rendered attribute of the <h:outputScript> as follows:
<h:commandButton id="add_something_id" binding="#{add}" value="Add" action="#{myBean.addSomething(false)}">
<f:ajax execute="#form" render="#form someTable" />
</h:commandButton>
<h:outputScript rendered="#{not empty param[add.clientId] and not facesContext.validationFailed}">
$("#dialog_id").dialog("close");
</h:outputScript>
(note that you need to make sure that the script is also re-rendered by f:ajax)
A bit hacky, but it's not possible to handle it in the onevent function as the standard JSF implementation doesn't provide any information about the validation status in the ajax response.
If you happen to use RichFaces, then you could just use EL in the oncomplete attribute of the <a4j:xxx> command button/link. They are namely evaluated on a per-request basis instead of on a per-view basis as in standard JSF and PrimeFaces:
<a4j:commandButton ... oncomplete="if (#{!facesContext.validationFailed}) $('#dialog_id').dialog('close')" />
Or if you happen to use PrimeFaces, then you could take advantage of the fact that PrimeFaces extends the ajax response with an additional args.validationFailed attribute which is injected straight in the JavaScript scope of the oncomplete attribute:
<p:commandButton ... oncomplete="if (args && !args.validationFailed) $('#dialog_id').dialog('close')" />
(note that & is been used instead of &, because & is a special character in XML/XHTML)
Or you could use the PrimeFaces' RequestContext API in the bean's action method to programmatically execute JavaScript in the rendered view.
RequestContext.getCurrentInstance().execute("$('#dialog_id').dialog('close')");
No conditional checks are necessary as the bean's action method won't be invoked anyway when the validation has failed.
Two things
1) Checking for an error in the 'onevent' function
Surely you have a message tag for the mandatory field?
<h:message id="m-my-field-id" for="my-field-id" errorClass="error-class"/>
So you can check for the error-class something like
var message = $('#m-my-field-id');
if(message.hasClass('error-class'){
//do this
}
else{
//do that
}
2) The DOM isn't up to date on success
Yes, I can see the message on the page in Firefox, yet jQuery tells me it is not there.
I have found that using the smallest possible timeout is sufficient to fix this
setTimeout(
function(){
setErrorStyle(source.attr('id'));
},
1
);
I think you should take a look at PrimeFaces' RequestContext. This would help you trigger client-side code on the server side.
#BalusC
in your example code the clientId of the button is not set as a param because it is a AJAX request. So
not empty param[add.clientId] is always false.
But this works:
param['javax.faces.source'] eq add.clientId
(tested with jsf-impl-2.2.12.redhat-1)
regards

JSF - Richfaces, process submitted form data and then confirm to continue or cancel

I want to show a confirmation dialog to continiue or cancel a save operation when a form is submitted. I have a form with a save button which is calling an action methode to persist data in the form.
When save button is clicked, a file will be readed on serverside before the form data is persisted. Data from the file will be joined into form data and then te form data will be persisted. I need some values from the form to define which file will be readed. There is no problem so far. When a FileNotFoundException throwed or the neccessary data from the file is not found, then i want to show a confirmation dialog to continiue or cancel save operation with caused message.
Does anybody have some examples or any ideas how to handle this? Do i need to use a4j? Thanks.
I am using Rifchfaces 3.3.3 and Seamframework 2.2.
At first i have to correct my question title. It is not going on "processing submitted form data" but a form data that will be submitted after some validation.
Now the solution.
For example I have following in my form:
some filelds
an a4j:commandButton to reRender the fields and perform doSomeStuff() action
an hidden h: or a4j:commandButton to submit the form.
1- User clicks on 'fake' submit button which is an a4j:commandButtton,
2- Ajax call updates fields in reRender attribute
3- After that,method doSomeStuff() is performed with rerendered field values
4- In the end Javascript will run to submit form or not.
Form:
<h:form id="myForm">
<h:inputText id="name" value="#{personHome.person.name}"/>
<h:inputText id="surname" value="#{personHome.person.surname}"/>
<a:commandButton value="Save" reRender="name, surname"
action="#{personHome.doSomeStuff()}"
oncomplete="return checkMessage('#{personHome.success}')"
id="a4jSave" />
<h:commandButton id="save" value="Save"
action="#{personHome.persist}"
style="visibility:hidden" />
</h:form>
JavaScript:
<script language="javascript">
function checkMessage(success) {
if(success =='false')
{
return confirm('Do you want to submit this form?') ? submitForm() : false;
} else {
submitForm ();
}
}
function submitForm() {
document.getElementById('myForm:save').click();
return false;
}
</script>
Yes you need to use a4j.
Try something like that (non tested, but follow the algorithm) :
<a4j:commandButton onclick="if(messageHasToBeDisplayed){Richfaces.showModalPanel('modalId');}else{doSomeStuff();}" />
...
<a4j:jsFunction name="doSomeStuff" action="#{controller.doSomeStuff}" reRender="..."/>
This shows you how to display a modal panel if necessary.
Without more code I can't help you more, but I think this should help you...

Resources