return back the value of g:textfield - grails

how can i show back the g:textfield value if the value already havebeen taken.
example :
<input type="text" name="simbol" id="simbol" value="${simbol}"/>
when input the textfield with "1A" then SAVE to database, then i input again with type "1A" again. it will be error because i protect with unique : true, when eror it will be return the input page..
and filled by "1A"
how can i do to get the "1A" when save error and return to the page?
catch(Exception E)
{
[simbol: params.simbol?: "",nama : params.nama?:""]
flash.message = "Simbol Sudah Dipakai !!! "
redirect (action:"tambah")
}
i use try cacth to throw unique save error.
and
[simbol: params.simbol?: "",nama : params.nama?:""], this line i tried to throw/get back the value when save eror or unique

You need put back data into model and `render page.
In your code you redirect without params at all.
This is the common way to do that you need. (Controller code)
def unInstance = new Un(params)
if (!unInstance.save(flush: true)) {
render(view: "create", model: [unInstance: unInstance])
return
}
....
}

Related

How to resolve 'groovy.lang.MissingMethodException' ...Possible solutions: notify(), render(java.lang.String)

I am very new to Groovy and this is an old application where the author is no longer with our organization. None of the previous questions that look similar offered any help. The application needs to send a simple message to the user to warn they are missing an entry before they con continue on.
I have made no fewer than 20 changes from flash.message to confirm. Flash causes the application to jump all the way to the user login function. This confirm is giving a crash message: Error 500: Executing action [submitrequest] of controller [SdrmController] caused exception: Runtime error executing action
def submitrequest = {
def testChecker
testChecker = [params.fullExpName].flatten().findAll { it != null }
log.info('testChecker.size = ' + testChecker.size)
if (testChecker.size > 0) {
if (!confirm('Submitting can not be undone, are you sure?')) return
} else {
if (!confirm('You have to pick an expedition. Please return to your Request and pick at least one expedition.')) return
} else {
return
}
}
// rest of long time working code here
}
Expected Result is a simple message to screen tell the user to pick an "Expedition" from a list and then the code returns to the same point so the user can make the change then hit the submit again.
Then full message:
No signature of method: SdrmController.confirm() is applicable for argument types: (java.lang.String) values: [You have to pick an expedition. Please return to your Request and pick at least one expedition.] Possible solutions: notify(), render(java.lang.String)
-- flash.message worked for our situation.
`legChecker = [params.programLeg].flatten().findAll{it!=null}
if(requestInstance.futurePast == "future" && expChecker.size<1) {
flash.message = " you must select a future expedition "
render(view: 'stepstart', model: [....])
return
}`

Error exporting excel on first attempt

def exportExcel(){
if(!params.max) params.max = 10
if(params?.type && params.type != "html"){
response.contentType = grailsApplication.config.grails.mime.types[params.type]
response.setHeader("Content-disposition", "attachment; filename=agents.${params.extension}")
List fields = ["orgTypeId", "name"]
Map labels = ["orgTypeId":"DP Id", "name":"Name"]
def upperCase = { domain, value ->
return value.toUpperCase()
}
Map parameters = [title: "Agent List", "column.widths":[0.15, 0.4]]
Map formatters = [name: upperCase]
exportService.export(params.type, response.outputStream, Agent.list(params), fields, labels, formatters, parameters)
}
render(view: 'index',model: [organizationTypeCount: Agent.count(), organizationType: Agent.list(params)])
}
This is my code to export excel. When I click on export button. It show Failed-Network error.
If I resume download it will be downloaded.
This is the error : java.lang.IllegalStateException: getOutputStream() has already been called for this response
Please help me resolve this issue.
You cannot write attachment data to the output stream, and then render the index view; that is trying to render your view to the same output stream that you already sent the attachment to. If you remove the line rendering the index view, your code should work as expected.
If you need to generate an attachment/download AND move to another view in your browser, you will need to send two requests to do that.

How to integrate the element label into the validation error message in ZF2?

I have a form, where the error messages have to be displayed bundled at one place. The default messages are general, so the user sometimes doesn't know, which message is for which form field:
A record matching the input was found
Value is required and can't be empty
The input is not a valid email address...
I could write a custom message for every field, but is much effort and copy&paste.
So, I'd like to display the messages like this:
My element Foo label: A record matching the input was found
My element Bar label: Value is required and can't be empty
My element Buz label: The input is not a valid email address...
How to achieve this?
ZF2 seems not to provide a solution for this requirement. My solution/workaround is to override the Zend\Form\View\Helper\FormElementErrors replacing these lines of the FormElementErrors#render(...) by
$this->prepareMessagesToPrint($messages, $messagesToPrint, $element, $escapeHtml);
and add a method, that process the $messages as desired:
protected function prepareMessagesToPrint($messages, &$messagesToPrint, $element, $escapeHtml) {
foreach ($messages as $nameOrType => $elementOrError) {
if (is_string($elementOrError)) {
$elementLabel = $element->getLabel()
? '<b>' . $this->view->translate($element->getLabel()) . '</b>' . ': '
: null
;
$message = $escapeHtml($elementOrError);
$messagesToPrint[] = $elementLabel ? $elementLabel . $message : $message;
} elseif (is_array($elementOrError)) {
$newElement = $element->get($nameOrType);
$this->prepareMessagesToPrint(
$elementOrError, $messagesToPrint, $newElement, $escapeHtml
);
}
}
}

Grails: Clear errors when passing object to view

I am checking if my user has entered the same password twice in controller:
if(params.password1 != "" || params.password2 != "") {
// change password
if(params.password1 != params.password2) {
user.errors.rejectValue('password', 'noMatch')
}
user.password = params.password1
}
if (user.errors.errorCount > 0 || !user.save()) {
println user.errors.errorCount
render(view: "edituser", model: [userInstance: user])
return
}
I get the correct user error count displayed in console so my if-clause works and Grails does not re-validate the object by using double pipe.
When I have a look into my GSP I get the following message:
grails.validation.ValidationErrors: 0 errors
It seams like Grails clears all errors or uses an other object. It's curious, because my custom validator in my domain class works fine...

Grails sImple chat - Chat messages not displaying on screen

Following is a code fragment obtained from Grails website.
<script>
function messageKeyPress(field,event) {
var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
var message = $('#messageBox').val();
if (theCode == 13){
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="temp"/>
$('#messageBox').val('');
return false;
} else {
return true;
}
}
function retrieveLatestMessages() {
<g:remoteFunction action="retrieveLatestMessages" update="chatMessages"/>
}
function pollMessages() {
retrieveLatestMessages();
setTimeout('pollMessages()', 5000);
}
pollMessages();
</script>
The above code worked but when i added the Controller it stopped working. I meant that the records gets saved in the DB, but i am not able to retrieve the data and display on screen.
This is what i did
<g:remoteFunction controller="message" action="retrieveLatestMessages" update="chatMessages"/>
The MessageController function is as follows:
#Secured([ 'ROLE_USER'])
def retrieveLatestMessages() {
println "test"
def messages = Message.listOrderByDate(order: 'desc', max:1000)
[messages:messages.reverse()]
println messages
}
The above controller function gets executed (I see the println statements on console), but the data isn't getting populating on the screen.
Can someone help me out here
UPDATE
[{"class":"myPro.Message","id":3,"date":"2014-07-23T17:31:58Z","message":"dfdf","name":"hi"},{"class":"myPro.Message","id":2,"date":"2014-07-23T17:31:56Z","message":"dfdfdf","name":"dd"},{"class":"myPro.Message","id":1,"date":"2014-07-23T17:31:18Z","message":"xxxx","name":"fie"}]
Your method - retrieveLatestMessages() action in your case - must return a model, but it returns the output of println instead.
To make your code work, you must place the model in the last line, or explicitly return it by using return statement:
def retrieveLatestMessages() {
println "test"
def messages = Message.listOrderByDate(order: 'desc', max:1000)
println messages
[messages:messages.reverse()]
}
Try this
import grails.converters.JSON
#Secured([ 'ROLE_USER'])
def retrieveLatestMessages() {
println "test"
def messages = Message.listOrderByDate(order: 'asc', max:1000)
render messages as JSON
}
Enjoy.
I had this sample app working on mine with no issues but here is the thing, this process requires you to poll the page consistently and it is resource intensive:
I ended up writing a domainClass that was bound to a Datasource that was using the HQL db and was outside of my own app, the process requires a DB table to stream chat....
Alternative is to move away from polling and use websockets:
check out this video
https://www.youtube.com/watch?v=8QBdUcFqRkU
Then check out this video
https://www.youtube.com/watch?v=BikL52HYaZg
Finally look at this :
https://github.com/vahidhedayati/grails-websocket-example
This has been updated and includes the 2nd method of using winsocket to make simple chat ....

Resources