Skip to main content

Creating an APEX plugin for an Oracle JET component - Part 2

In my previous blogpost I showed how you can embed an Oracle JET component in your APEX application. Now it is time to make a plugin out of the wisdom we gained doing so.
First of all a disclaimer. My intention is to make this plugin and the inner workings as simple as possible. So you can add a lot more functionality, checks etc and therefore add complexity. But this is intended to be as simple as possible.

The plugin consists of three parts: a PL/SQL render function, a snippet of JavaScript and a PL/SQL ajax function.

The render function is defined as :

function render 
( p_region                in  apex_plugin.t_region
, p_plugin                in  apex_plugin.t_plugin
, p_is_printer_friendly   in  boolean 
) return apex_plugin.t_region_render_result 
is

  c_region_static_id      constant varchar2(255)  := apex_escape.html_attribute( p_region.static_id );

begin
  -- Add placeholder div
  sys.htp.p (
     '<div class="a-JET-PictoChart" id="' || c_region_static_id || '_region">' ||
       '<div class="a-JET-PictoChart-container" id="' || c_region_static_id || '_chart"></div>' ||
     '</div>' );
     
  -- Load the JavaScript library   
  apex_javascript.add_library 
  ( p_name      => 'pictoChart'
  , p_directory => p_plugin.file_prefix
  );
  
  -- Initialize the chart
  apex_javascript.add_onload_code
  ( p_code => 'jet.picto.init('||
                  '"#'||c_region_static_id||'_chart", '          || -- pRegionId
                  '"' || apex_plugin.get_ajax_identifier ||'"'   || -- pApexAjaxIdentifier
                 ')'
  );
  
  return null;
end render;

So what it does in these three steps is :
1. Generate a DIV placeholder, just as we saw in that previous post
2. Load the JavaScript file "pictoChart.js",
3. Execute the JavaScript function "jet.picto.init" providing two parameters, the regionId of the DIV and the (internal) identifier of the PL/SQL ajax function.

The contents of the JavaScript file is :

! function (jet, $, server, util, debug) {
    "use strict";
    requirejs.config({
        baseUrl: apex_img_dir + "oraclejet/js/libs",
        paths: {
            "jquery": "jquery/jquery-2.1.3.min",
            "jqueryui-amd": "jquery/jqueryui-amd-1.11.4.min",
            "ojs": "oj/v2.0.0/min",
            "ojL10n": "oj/v2.0.0/ojL10n",
            "ojtranslations": "oj/v2.0.0/resources",
            "promise": "es6-promise/promise-1.0.0.min"
        },
        shim: {
            jquery: {
                exports: ["jQuery", "$"]
            }
        }
    }), jet.picto = {
        init: function (pRegionId, pApexAjaxIdentifier) {
            require(["ojs/ojcore", "jquery", "ojs/ojpictochart"], function (oj, $) {
                server.plugin(pApexAjaxIdentifier, {}, {
                    success: function (pData) {
                        $(pRegionId)
                            .ojPictoChart(pData);
                    }
                });
            });
        }
    }
}(window.jet = window.jet || {}, apex.jQuery, apex.server, apex.util, apex.debug);
// To keep ThemeRoller working properly:
define("jquery", [], function () {
    return apex.jQuery
});

The first function call (requirejs.config) is again the same is we did earlier. Please note that the paths mentioned in here might differ in your environment. You could define those paths as (Application level) Component Settings, but for simplicity I keep them hardcoded in this example.
Notice there is a "jet" namespace defined and within that namespace a nested "picto" namespace. So we could easily extend this file (after renaming it) to other chart types. The "init" method defines the required files and then calls apex.server.plugin passing the PL/SQL ajax function as a parameter. After this ajax function is called, the result - a JSON object - is passed to the ojPictoChart function.
On the last line, as Kyle Hu correctly commented in my previous post, we have to define jquery in order to make ThemeRoller work (again).
So in fact, the JavaScript is very straightforward: in the end just an ajax call passing the result into the ojPictoChart function.

So what is the magic of the last piece, the ajax PL/SQL function? Here it is::

function ajax
( p_region    in  apex_plugin.t_region
, p_plugin    in  apex_plugin.t_plugin 
) return apex_plugin.t_region_ajax_result
is
  c       sys_refcursor;
  l_query varchar2(32767);
begin  
  l_query := p_region.source;
  open c for l_query;
  apex_json.open_object;
  apex_json.write('items', c);

  -- add settings
  apex_json.write('animationOnDisplay' , p_region.attribute_01);
  apex_json.write('columnCount'        , p_region.attribute_02);
  apex_json.write('layout'             , p_region.attribute_03);

  apex_json.close_object;
  return null;
end ajax;

Thus it just takes the region source - a SQL statement -, executes it returning a JSON object. And to these results three of the available options, defined as plugin attributes, are added. Again, as simple as possible. So no validation on the correctness of the SQL (as all APEX Developers can write a correct SQL statement, right). And just a minor part of the available options are exposed in the plugin.

When you create a region based on this plugin you have to provide it with a correct SQL statement - one that will return a valid JSON object according to the pictoChart docs. For example:

select ename||' - '||job||'@'||dname "name"
,      'human' "shape"
,      1 "count"
,      case job
       when 'PRESIDENT' then 'black'
       when 'ANALYST'   then 'blue'
       when 'CLERK'     then 'green'
       when 'MANAGER'   then 'red'
       when 'SALESMAN'  then 'yellow'
       end "color"
from   emp
       join dept on emp.deptno = dept.deptno
order by 2 desc, 4

And if you set the settings as :


You'll get as a beautiful result:
So knowing this, it wouldn't be hard to rebuild the plugin by yourself. But for the lazy readers out there, you can download it here too.
Or probably build another plugin for another JET component!

Post a Comment

Popular posts from this blog

Showing a success message after closing a modal dialog

APEX 5 comes with Modal Dialogs out of the box. Very neat. Especially for adding and changing data. And to minimise the number of time a user has to click, it could be useful to add a "Close Dialog" process after the actual data processing. When the data processing fails, the Dialog stays on top showing the error. When data processing runs fine, the Dialog is closed ... without any confirmation. And this might be scary for a shaky user.

So how can we provide the user some feedback? On Page 4 of the Sample Dialog Application you can see one solution: up on a Dialog Closed Event on the parent page it does a redirect to refresh the parent page appending the success message of the "Close Dialog" process. This has two drawbacks. First, it probably refreshes more than necessary. And second, if you're using multiple layers of dialogs (dialogs that open other dialogs) the message appears in the "parent dialog".
As an alternative you could follow these steps: 1…

A review of APEX World 2017 - Day 1

Last week the SS Rotterdam was the beautiful location of the largest gathering of APEX Developers worldwide. With around 380 (!) attendees a new high was set. And they came from all over the world : I spotted people from The Netherlands, Belgium, Switzerland, Austria, Croatia, Germany, Denmark, Norway, UK, Ireland and the USA. And I even might have missed one or two ….

The event started with a presentation by the “father of APEX”, Mike Hichwa, talking about "Oracle APEX Past, Present and Future”. Of course everyone is curious what the APEX future might bring: Friendly URL’s, automated testing, more JSON, concurrent APEX versions, third party Oauth 2 authentication (think Facebook, Google), APEX app diff and more, a lot more, REST capabilities. And now we have to wait for APEX 5.2 … and that might take a while! 
After this keynote, the conference split up in three tracks. After the coffee break I returned to to big theatre where Geertjan Wielenga talked about "Finally Javas…

It's happening again ... running for the ODTUG Board of Directors 😉

For the third time in a row I'll be running for ODTUG's Board of Directors. But after ending as a runner up twice, I am sure I'm going to make it this time! But not without your help!

My campaign statement this year is:
I have been attending and presenting at Kscope conferences since 2007. This not only resulted in a vast amount of knowledge, but also - and even more important - a huge number of friends from all over the globe.  I want to see ODTUG grow and spread this community feeling even more! 
My experience as an attendee, presenter and content lead has provided the basic foundation to be a director. Next to that, my personality and (global) network will be beneficial to the whole board and organization. 
Since March I have served on the Board of Directors in a limited term for a Director who stepped down due to a career change. This has allowed me to have unique insight of all the things that are going on in and around the ODTUG organization. As the train was already ro…