I am looking to dynamically update a field in an edit form based on changes made to another field. The idea is that when field1 is modified, an AJAX script will call the controller to calculate a new value for field2 and then update the template accordingly. However, the controller requires two values: the value of field1 and the object being edited in order to render the template properly.
<script>
$(document).ready(function(){
$( document ).on('change', '.availableCert', function ( event ){
$.ajax({
url: '${g.createLink( controller:'offerDetail', action:'updatePrice' )}',
data: {availableCert:this.value, id:this.id},
type: 'get'
}).success( function ( data ) { $( '#updatePrice' ).html( data ); });
});
});
</script>
<script>
$(document).ready(function(){
$( document ).on('change', '.adjustPrice', function ( event ){
$.ajax({
url: '${g.createLink( controller:'offerDetail', action:'updatePrice' )}',
data: {adjustPrice:this.value, id:this.id},
type: 'get'
}).success( function ( data ) { $( '#updatePrice' ).html( data ); });
});
});
</script>
<script>
$(document).ready(function(){
$( document ).on('change', '.volumeOffered', function ( event ){
$.ajax({
url: '${g.createLink( controller:'offerDetail', action:'updatePrice' )}',
data: {volumeOffered:this.value, id:this.id},
type: 'get'
}).success( function ( data ) { $( '#updatePrice' ).html( data ); });
});
});
</script>
This snippet shows part of the template where the fields are displayed:
<g:select class="availableCert" name="availableCert" from="${offerDetail.availableCert}" value="${offerDetail.choosedCert}" />
</td>
<td> FSC: ${offerDetail.priceFSC}</td>
<td> UC: ${offerDetail.priceUC}</td>
<td> CW: ${offerDetail.priceCW}</td>
<td> PEFC: ${offerDetail.pricePEFC}</td>
<td>
EndPrice: ${offerDetail.endPrice}
</td>
Therefore, to render this field correctly, the controller needs access to the object ${offerDetail} so that the template can display it appropriately.
I'm not sure how the JavaScript code can retrieve this object, but I believe there might be a simpler solution than what I currently envision. Am I missing something?
Here is the relevant code from the controller:
def updatePrice() {
def OfferDetail od
if (params.id != null){
od = OfferDetail.get(params.id)
}
if (params.availableCert != null) {
od.choosedCert = params.availableCert
} else if (params.adjustPrice != null) {
od.priceAdjust = params.adjustPrice.toBigDecimal()
} else if (params.volumeOffered != null) {
od.volumeOffered = params.volumeOffered
} else {}
render template: "offerDData", model: [offerDetail:od]
}