Thursday 27 February 2020

Oracle APEX trigger JavaScript action after PLSQL validation

Oracle APEX validation JavaScript after PLSQL

Execute JavaScript after server side validations

 

apex.message.setThemeHooks to the rescue

 

Simple use case you have lots of existing PL/SQL validation on the page already implemented and you want to add new one that should validate and as it completes and raises error message you want to execute some JavaScript code.

In example below after I click Validate a popup message comes up and I need to show a region using JS.


How would we achieve this?

There are many blog posts covering both client and server side validations so I will not go into deep details here. Point to take is since we are doing PL/SQL validation here we are talking about server side validation. 


From what I know there is no silver bullet how you can simply call and execute JS from PL/SQL code so what is the catch.

This is how my validation is defined


It does not do much as it is more to showcase this demo. Every time button Validate is clicked it will fail and raise a validation error.

How do we execute a JavaScript call after my validation raises a popup on a screen?

Luckily there is very handy method exposed to us through apex.message widget called setThemeHooks which some of you may have come across if you ever wanted to auto dismiss your SUCCESS or ERROR messages on a screen in Universal Theme.

What this will allow us is to listen for APEX notification message being shown (or hidden) on a screen when validation fails which is perfect place for us to orchestrate JS actions we want to execute immediately after it.

If we now add little bit of JavaScript code to our page Execute when Page Loads section
apex.message.setThemeHooks({
    beforeShow: function( pMsgType, pElement$ ){
        if ( pMsgType === apex.message.TYPE.ERROR ) {
          alert('MESSAGE Triggering');               
        }
    }
});
We are catching the moment error messages are showed on a page. Since we are here now talking JavaScript it is not hard to trigger additional JS calls we want to do.

Note that code in my demo is actually this 
apex.message.setThemeHooks({
    beforeShow: function( pMsgType, pElement$ ){
      if ( pMsgType === apex.message.TYPE.ERROR ) {
        if ( $('li.a-Notification-item:contains("LINOTEST")').length > 0 ){
             alert('Good point');               
            }
        }
    }
});
where I am only filtering messages that contain certain text. At this point I can easily do something like $('#my_region_id').show(); and region would show up after my validation failed. 



I know we can argue if this is the best way to handle the situation but still knowing how to hook/listen for your validation messages might come handy in other situations too. 

Live demo.

Thanks,
SLino


 

1 comment:

  1. A lot of thanks for sharing this. It's easy to follow.

    ReplyDelete