Saturday, 1 August 2020

New Plug-in: Reacting on changed content of APEX Autocomplete Item

Why use Text Field with autocomplete

Right now I am developing a series of mobile applications for personal use. And of course I learn a lot about developing with Oracle APEX for mobile.
I like to use auto complete items in mobile apps because to my opinion select lists are less suited for mobile use most of the time. One of the reasons is that in long lists, in contrast to in desktop applications, you cannot filter on the first character. Because you do not have a keyboard! So you have to scroll a lot. On iPhone this takes place on the bottom of the screen where you see only about three items at a time. I once checked in for a flight using the mobile app from the airline. I had to select my country (The Netherlands) from a select list of some 200 countries four times. And each time it took me about 30 secs to scroll through the 170 countries until I reached The Netherlands.
With an autocomplete item it would take 2 secs to type in a discriminating 3 or 4 characters to get to the result.
So that is why I prefer to use Autocomplete items. But I found out there is a problem with reacting on when the content of such an item changes. A Dynamic Action of type Change does not fire when the value of an Autocomplete item is selected.

Reacting on change of Text Field with autocomplete

A quest for an answer on the internet revealed, that a special event type should be used. Under the heading Component Events we can find: Update [Text Field with autocomplete].

When using this event to define a Dynamic Action, the DA fires the moment a value from the suggestion list of the autocomplete item is chosen. So contrary to the Change event the focus is still on the Autocomplete item. Furthermore there is no reaction on values entered that are not in the suggestion list.

So I started off to find a way to detect changes in the Text Field with autocomplete.
I defined a On Focus DA in which the current value is stored into an attribute old-value of the input item. In a Lose Focus DA this value is retrieved and compared to the current value of the item. If there is a difference, action can be taken. Then I selected a value form the auto complete suggestion list. This took the focus away from the Autocomplete item, and the change event was triggered.
So the Lose Focus DA does not work.
With some googling I found out that only input, select, textarea, anchor and button elements can receive focus. So I could try to implement the code in Lose Focus in the Get focus actions for the other elements. And this works!

But it is quite cumbersome to define these actions for each Autocomplete item and all the other elements we want to monitor. Besides the task would be difficult for developers who are not so familiar with JavaScript. So I decided to create a plug-in for it.

Autocomplete change detection DA Plug-in

So I have developed a plug-in for watching changes in Autocomplete items and triggering an event when a change is detected.
You can find the plug-in on apex.world
You can apply this plug-in on Page Load. The plug-in automatically watches all Text Fields with autocomplete on the page.

When the value of an Autocomplete item is changed, an event is fired from that autocomplete item. You can find the event in the event in the Component Event chapter of the Event list, as you can see in the DA definition below:




Happy APEXing.





APEX 20.1 nugget: Mega menu's

A few days ago I downloaded and installed APEX 20.1. I was inspired by the presentations of Shakeeb Rahman and Patrick Wolf on ODTUG Learn from home. They talked about mega menu and user friendly URL's. And I thought, I want to have this too!

So I downloaded the installation package, studied the installation/upgrade manual carefully, and followed the instructions as well as possible. In the past I have had troubles with ords and static files support after upgrading, costing me hours to fix. This time everything went smoothly and after performing all the indicated steps I fired up my new APEX 20.1, and it worked :-).
I suppose it pays to RTFM.

Mega menu's

Mega menu's provide a large menu, where you have all the menu options available at once. 
In my APEX demo application the menu's have been a constant struggle for me. I wanted all the pages to be reachable from the menu directly, but this way the menu grew too long and the options disappeared below the bottom of the screen (even on my 27" iMac!). 
So mega menu's were very promising. And indeed they did fulfill my expectations.:




The nice thing is that Mega menu's work on the same data as the original APEX side menu. So initially you do not have to change anything to start using them. Just change some setting in the User Interface and you have your own Mega Menu:



You can visit my APEX demo application https://www.speech2form.com/ords/detora/r/opfg to see the Mega Menu in action. It took me about half an hour to reconstruct the menu. Btw, do you notice the user friendly URL? 

Of course once you have got your menu, you can tweak the content to your liking. Watch this video by Shakeeb Rahman on Mega Menu's. Unfortunately I was not able to find a recording of the webinar from ODTUG Learn from Home Series in which Shakeeb demonstrates what you can do with Mega Menu's in great detail. 

Happy APEXing

Wednesday, 12 February 2020

Oracle APEX Geolocation 1: How to get your location


-->
Some decades ago people used to work in an office. And occasionally they went on business trips. Nowadays users are much more mobile. They can work from home, form the office or from a field location. So their location varies and it can be useful information for the applications they use.The location might be tied to a customer or a fact that should be reported. This series of blogposts will deal with determining the location in Oracle APEX, and how to use and display it:

Part 2: Using Oracle Spatial
Part 3: Display location(s) on map
Part 4: Correct locations on map
Part 5: Getting location data from photos

The parts without link are not yet available.

There is an example application available at :  https://github.com/dickdral/apex_location_demo

Getting your location in the browser

In order to retrieve your GPS location in the browser some JavaScript needs to be applied:


function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        alert(`Latitude: ${position.coords.latitude} \n` +
              `Longitude: ${position.coords.longitude}`);
    });
  } else {
    alert("Geolocation is not supported by this browser.");
  }
}

The most important line is the call to navigator.geolocation.getCurrentPosition.
 This is the function to retrieve the GPS location. As this may take several seconds the function is asynchronous.  The function to be performed after retrieval of the location is the argument for the function. There also is a check when the function is not available.
After the call JavaScript will immediately continue with others tasks. Otherwise the page would hang until the function returns.

NB The function can only be called from a https web site.

Accuracy

In ideal situations the accuracy of the location is within a few meters. In less favorable situations this might expand to tens of even hundred of meters. Especially in an urban environment with many high buildings the visiblity of the GPS sattelites is less good and the accuracy is less accordingly.
More information on GPS accuracy can be found  here

Privacy

Privacy can be an issue when you retrieve and store the location of employees, customers etc. The privacy legislation differs per country.
As of May 2018 the General Data Protection Regulation is issued by the EU. This law contains high penalties for offenders. It is wise to take notice of the privacy regulations in the countries where the application will be used.

Getting location using a APEX plug-in

For APEX developers it is not necessary to write JavaScript to retrieve the GPS location. You can use the Store location plug-in that can be found on https://apex.world.

After importing the plug-in in your application, you can reference it in a dynamic action. All you need to fill in are the APEX items to store the latitude and longitude once the location is retrieved.



To define follow-up actions a custom DA can be defined acting on the event location-retreived.



Happy apexing ;-)

Saturday, 21 December 2019

Missing grid layout attributes for APEX items

Whilw preparing for a new presentation I created a new application using the APEX Create Application Wizard and started to create pages and adding items.
While doing so I noticed I missed the usual Grid layout attributes in the Layout section of the item attributes:


No column info etcetera. :-(.
I have spent at least an hour looking for a setting that governs this behavior. Without a result...
Also Google did not provide me with the right answers.

Until I created a new application with all the optional pages. When I set out to examine one of these pages I noticed that the region in the Breadcrumb position did not have the grid layout attributes either.
Going back to my other application I saw that all the regions were created in the Breadcrumb Bar position...
So moving the regions to the Content Body give me back my Grid Layout options (I really missed them).

Happy APEXing


Thursday, 7 November 2019

Internet Explorer does not show content of Modal Dialog

In my current assignment I develop using either Firefox or Chrome. But the organization also uses Internet Explorer 11. 

So this morning one of the testers calls me and shows an empty Modal Dialog in Internet Explorer. When using Firefox or Chrome the Modal Dialog shows the expected content. So where is the difference. 



So I reproduce the situation in the Development environment and there the same behavior shows when using Internet Explorer: an empty modal dialog. After opening the Developer Tools the cause shows in the console window: a Javascript error. 

Invalid character

The error points to the JS code below:

$( `[headers="${id}"] input[type="checkbox"]`).each(function() {
    if ( $(this).prop('checked') != checked_status ) {
        $(this).click(); 
    }
});

In the above code snippet a template string is used enclosed with the backtick character (`). You can find more information on this technique on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals. And at the end of the page there is a compatibility table, in which it is clear that Internet Explorer does not support this feature. 

 
It is clear that this feature is not supported by IE :-(. 

After a change of the code to: 

$( '[headers="'+id+ '"] input[type="checkbox"]').each(function() {

the modal window showed its content again in IE. 

So when coding for IE be sure not to use too modern JavaScript. Or use a tool like Babel that supplies backward compatibility. 

Pff...

But still, it is quite tricky that a JavaScript error on startup prevents the whole APEX page to be displayed. 

Happy APEXing


Friday, 2 August 2019

Oracle APEX Plug-in to retrieve GPS location

Your smartphone is aware where it is using its GPS capabilities. From HTML it is possible to retrieve this GPS location. For this you will have to write some JavaScript.
The new Store location plug-in relieves you from writing the Javascript code. Use it by:

  • downloading the plug-in from apex.world
  • importing the plug-in into your application
  • create two items on a page for the GPS coodinates (lattitude and longitude). They may be hidden items
  • creating a Page Load dynamic action on the page referencing the plug-in in the action
  • filling in the names of the GPS coordinate items in the plug-in attributes
That's all! Run your page on a smart phone and the items will be filled with the GPS coordinates of your current position. For security reasons the smartphone might ask you for permission to access the GPS sensor. 

Acting upon the GPS location

Retrieving the GPS location is an asynchonous process. That means that the process is started and at some later point in time the result is stored in the items. This means that adding another in the Page Load dynamic action will access empty GPS location items because the process is not finished. 
To act upon the coordinates you need to define a custom dynamic action with the following specification:


In the actions you can for example define a PL/SQL action with the GPS coordinate items as inputs. 

In this blogpost you find a full example for applying the plug-in. 

Happy APEXing

Creating a mobile app with APEX - Part 10: Use your location

Your phone is packed with all kind of sensors. Many of them you can not use in JavaScript, but you can access the GPS sensor to retrieve your location. In this blogpost we will access the GPS location and use it in our application.

On the Activity page the GPS Location will be retrieved. When the record is entered when the user is still on the location of the activity she can check Use location. With this item checked the GPS location is stored with the activity.
When the page is opened to enter a new activity the GPS location is retrieved. It is compared to the GPS locations in the database and if possible it will provide a default value for the Location item.

We will:

  • update the database to add columns to store the location
  • import a plug-in to retrieve the GPS location
  • add items on the Activity page to store the location
  • add Dynamic Actions on the Activity page to act on the GPS location
  • use the stored location to provide a default value for the column Location

Update the database objects

There are some changes needed in the database to accommodate the location data. 
The columns act_lattitude and act_longitude are added to the table ttm_activity. We also add a column act_sdo_location which is of the type sdo_geometry to be able to use Oracle Spatial functions. 
The trigger on ttm_activity is changed to construct the column act_sdo_location from act_lattitude and act_longitude.
The view ttm_activity_vw and it's instead of trigger are changed to support the new columns. 
The package ttm_alg is expanded with a function to yield a default value for location

Download the change script from here and execute it. 

Import the Store Location plug-in

Download the Store Location plug-in from APEX World. (Go to the Plug-ins page and search for store location)

Load into the application plug-ins:
  • Go to Shared Components > Plug-ins
  • Press Import
  • Select the plug-in file
  • Hit Next
  • Press Next again
  • Hit the button Install Plug-in
The plug-in is installed and ready for use. 

Add items to the Activity page

Items are needed to store the GPS coordinates that are retrieved by the plug-in. 
Furthermore we need a check box to indicate whether the record is entered on the location of the activity. 

  • Go to page 15
  • Go to P15_ACT_LOCATION and press the right mouse button
  • Select Create Page Item
    • Name: P15_USE_LOCATION
    • Type: Checkbox
    • Appearance > Template: Hidden
    • List of Values:
      • Type: Static Values
      • Static Values: STATIC:Use location;Y
  • Create another item:
    • Name: P15_ACT_LATTITUDE
    • Type: Text Field
    • Label: Lattitude
    • Source:
      • Type: Database Column
      • Database Column: ACT_LATTITUDE
  • And another one:
    • Name: P15_ACT_LONGITUDE
    • Type: Text Field
    • Label: Longitude
    • Source:
      • Type: Database Column
      • Database Column: ACT_LONGITUDE

Adding the Dynamic Actions

Two dynamic actions will be added. One to retrieve the GPS location and another to react on the retrieval of the location. These are separate actions because the retrieval of the GPS location is an asynchronous process. 

  • Go to page 15
  • Go to the Dynamic Actions tab
  • Right click on Page Load and click Create Dynamic Action
    • Name: Page Load - Retieve GPS location
    • Select the Action
      • Change Identification > Action to Store Location [Plug-In]
      • In Settings:
        • Lattitude Item: P15_ACT_LATTITUDE
        • Longitude Item: P15_ACT_LONGITUDE
  • Right click on Page Load and click Create Dynamic Action
    • Name: Location retrieved
    • When:
      • Event: Custom
      • Custom Event: location-retrieved
      • Selection Type: jQuery Selector
      • jQuery Selector: html
    • Select the Action
      • Action: Execute PL/SQL Code
      • Settings > PL/SQL Code:
:P15_ACT_LOCATION := nvl(:P15_ACT_LOCATION
       , ttm_alg.default_location(:P15_ACT_LATTITUDE,:P15_ACT_LONGITUDE));
      • Items to Submit: P15_ACT_LATTITUDE,P15_ACT_LONGITUDE
      • Items to Return: P15_ACT_LOCATION
The last Dynamic Action retrieves a default value for the field Location based on the GPS location. The default value is retrieved in the function ttm_alg.default_location that uses an Oracle Spatial query to find activities that have been recorded close to the current GPS location. The query is discussed in the last paragraphs of this post. 

Eating the pudding

The proof is in..., well you know. 
So let's try it. 
  • log in to the application on your phone
  • press New activity
  • after the page has been opened your permission to use the location is asked. Confirm it.
  • now scroll down to the bottom
  • (after some time) you will see the GPS coordinates
  • fill in the items of the activity
  • enter in  Location: test GPS location
  • check Use Location, else the GPS location will not be stored
  • accept the changes
  • press New again
  • scroll down to the bottom
  • (after some time) you will see the GPS coordinates
  • Location should then contain the value you entered for the previous record: test GPS location
If things do not work as expected use the Chrome Inspector (or any other Developer tools) to examine what is wrong. 

Background on selecting the default value

Based on the GPS coordinates the default value for the Location field is determined. This is done using a spatial query:

      select act_location
      from   ttm_activities
      where  act_lattitude is not null 
        and  act_longitude is not null
        and  act_use_location = 'Y'
        and  sdo_geom.within_distance(act_sdo_location,0.2
                , sdo_geometry(2001,8307
                              ,sdo_point_type(p_longitude,p_lattitude,null)
                              ,null,null),1,'unit=km')   
             = 'TRUE'
        order by sdo_geom.sdo_distance(act_sdo_location
                , sdo_geometry(2001,8307
                              ,sdo_point_type(p_longitude,p_lattitude,null)
                              ,null,null),1,'unit=km')   
      ; 

This query uses the Oracle Spatial function sdo_geom.within_distance to find all the records with a GPS location within 200 m's (the value 0.2) from the given GPS coordinates. This proves to be a reasonable distance to correct for the bias in GPS location. 
The records are sorted based on the distance to the coordinates which is retrieved using the function sdo_geom.sdo_distance. This way if the query delivers more than one row the one closest to the the given point is selected. 


Using Oracle Spatial functions

The Oracle Spatial functions expect arguments in the  form of a SDO Geometry objects. The column act_sdo_location is already stored as such an object. The GPS coordinates are numbers and need to be converted to a SDO Geometry object:

sdo_geometry(2001,8307
            ,sdo_point_type(p_longitude,p_lattitude,null)
                              ,null,null),1,'unit=km')

Without going to deep into the complex geometry subjects: 
  • the first parameter 2001 indicates that the shape is a point. You can also have lines, polygons etc. 
  • the second parameter 8307 references the coordinate system
  • you notice the values for longitude and lattitude in the call to sdo_point_type
  • the last parameter indicates that the unit used is kilometers. 
  • more detailed information can be found in the Oracle documentation
To be able to compare values the coordinate system and the unit used should be consistent in database and code.