Display field errors in toastr
Display field errors in toastr
Hi
I am trying to "catch" the field errors from datatables editor json response to display these errors in a toast (toastr.js) as my custom form uses steps and moving to the next step closes the previous step, thus hiding the error div and we are using PHP validation, not client-side...
editor.on( 'initSubmit', function (e, action) {
if ( editor.inError() ) {
toastr.error(editor.error(e));
return false;
}
});
I have successfully managed to display toasts for edit, remove and create, (see example below) but the same approach does not seem to work for errors.
editor.on('submitSuccess', function ( e, json, data, action ) {
if (action === 'create') {
if (json.error) {
console.log('got create error '+json.error)
} else {
toastr.success("Nuwe Lid gestoor!");
}
}
});
I have tried initSubmit, open, submitError etc. with no luck. Another option would be to display the error in the form footer, but again, we would have to assign the error to a variable.
This question has an accepted answers - jump to answer
Answers
You are using the wrong event, I guess. Please try "postSubmit".
Here is an example from my own coding catching an SQL dup key to avoid displaying the SQL error message to the user.
Here is another example that I still use - even though I could use "submitSuccess" now. But some time ago "submitSuccess" didn't pass in the "action" parameter. So this effectively is the same as "submitSuccess" because it also checks for field errors.
HI rf1234,
Thank you. This makes sense and I will implement it using postSubmit rather, however, I still need to catch the actual error in order to display it.
e.g. the client enters 14 characters into the ID number field, but validation on the server-side (PHP) would allow only 13, the error must be displayed in the toast.
I hope this explains it better?
Thanks!
Just use the second example, provoke a field error as you describe and take a look at json.fieldErrors with your debugger. That should contain the error message received from the server.
I have tried the advised method:
It returns undefined, which I assume is because I am incorrectly referencing the object from JSON? How would I correctly catch the error from JSON?
Ideally, it would need to loop through the errors as each error must have its own toast notification in case there is more than one. Any pointers as to how I can achieve this?
I have managed to get it to work. For those looking to use the same solution:
The problem was that I first needed to pass the response to an array and then iterate through it.
Thanks for the pointers rf1234!
Glad you got your problem solved! I have no clue about toastr.js and probably not many people in this forum have. So if your problem isn't really related to some exotic plugin I would recommend you don't mention it because there will be more people to help you if you don't.
rf1234