Friday, December 10, 2010

ODTUG Kaleidoscope 2011

kscope11 

1 ½ years ago I went to Monterey to visit the ODTUG Kaleidoscope 2009 conference. I was very impressed with the presenters, content and great atmosphere of the event. After the conference, on my way home, I promised myself to come back to KScope, as a presenter, if possible. This year is the second time I submitted an abstract. And ...

This week I received an email from the ODTUG confirming that my abstract has been accepted for presentation at ODTUG KScope11, June 26-30, in Long Beach, CA.

I feel very honored and happy to get this opportunity.

Join the Cool Kids at Kscope11

Whether you’re interested in my presentation or not, if you are into Oracle Development, have some training time and budget left: Come to Long Beach next year and participate in this unique event. Kscope11 offers:

  • More than 200 technical sessions on Application Express, BI and Oracle EPM, Database Development, Oracle Fusion Middleware, MySQL
  • Five all day symposiums - No extra charge
  • Lunch and learn sessions with Oracle ACE Directors
  • Plenty of time to meet and talk with the experts and other participants

My Abstract

For who is interested, here is the abstract of my presentation:

Presentation Title:  APEX Face/Off - Designing a GUI with APEX Templates and Themes
Session Type:  1 Hour Presentation
Abstract: 

A practical guide to the concept of APEX themes and templates.
Today’s internet sites are often a blend of websites and web applications. Web application interface design is, at its core, Web design. Oracle Application Express provides facilities to customize and manage your application design.
This presentation is for Oracle APEX developers who wish to learn how to provide their applications with a professional looking custom GUI design using web standards HTML and CSS together with APEX templates and Themes.
It will outline the skills, tooling and steps necessary to create a custom APEX GUI design using the concept of APEX templates and themes.
The presentation focuses on the practical aspects, from graphical GUI design to translating and integrating this design into APEX. It will be escorted by live, visual examples, suggest "Best Practices" and discuss the limitations of APEX.

 

I hope to see you in Long Beach next year.

Wednesday, November 24, 2010

Pre-Review: Oracle Application Express 4.0 with Ext JS : RAW

1063EN_MockupCover

 

 

Language : English
Paperback : 320 pages
Release Date : March 2011
ISBN : 1849681066
ISBN 13 : 978-1-84968-106-3
Author : Mark Lancaster

 

March 2011 the book “Oracle Application Express 4.0 with Ext JS”, written by Mark Lancaster, is expected to be published by Packt Publishing, but it’s available NOW already as a RAW edition.

RAW?

What is a RAW edition? Well, basically, it’s a prerelease (Read As we Write). Some chapters are still missing and no guaranties, that anything you’re reading in this RAW edition will actually be in the final book release. So, this article will be a pre-review. Is it worth reading? I think it is. You will see: for this book, RAW means VERY WELL DONE already.

Do be mislead by the title. This book is not solely about how to spice up your APEX GUI with ExtJS. This book discusses application GUI development with APEX in general and extending APEX functionality with ExtJS in particular.

What will you learn from the book?

The book will guide you through the whole installation and setup process of your APEX development environment, discussing the different web server alternatives. One of my favorite chapters here is the explanation of how to combine APEX with Subversion as version control system to automate your build process.

If you’re not familiar with Ext you will get an (APEX free) introduction to get acquainted with Ext, starting with a simple hello-world-like example , learn about CSS manipulation, DOM navigation and manipulation, event handling and finally advance to object notation and namespacing. All in about 30 pages, code examples included. Just enough to get stated without getting bored.

Ext offers lots of web GUI enhancements, but to use those in APEX you will have to work with templates and themes. The book explains the of the APEX model, how to create your own template step-by-step and integrate ExtJS into it.

Once familiar to the basics of ExtJS enabled APEX GUI building, you now will go through a number of detailed examples, creating, modifying and enhancing templates with ExtJS and CSS techniques: Regions, Labels, Lists, Button, Popups, Breadcrumps, Calendars and Reports to start with. Next you will get some examples of how to add some more advanced Ext layout elements to your Application, like the Ext.DatePicker, Auto-growing text areas, auto-completing text fields, tab panels, toolbars and menus.

A book about APEX 4.0, especially when covering GUI aspects, should spent some pages on Plug-ins and Dynamic Actions. This book will teach you, how to build your (first?) own Plug-in with a simple example, step-by-step and create a AJAX enabled Plug-in and Dynamic Actions.

So far the well done RAW version of the book. What’s still to come? The Mark Lancaster plans include chapters about:

· Interactive Components

· IFramed Tabs and Popup Windows

· Mixing Ext with jQuery

· Performance tuning your JavaScript

Conclusion

I like this book already. Lots of I’m-going-to-try-this-immediately examples, clear writing, good basics and well explained advanced examples make me recommend this book. You should have some experience with Application Express, experience with Ext is not required.

Pity the complete source code of the examples is not yet available on the Packt Publishing site.

I’m looking forward to the finished version. Meanwhile, if you are interested in the RAW edition of the book. Packt offers a nice deal: buy the RAW version of this book and place a pre-order for the print book right now, with a 40% discount on both.

Wednesday, November 17, 2010

Oracle updates APEX Statement of Direction

statementofdirection Oracle just came with an update on its “Statement of Direction” for APEX. Once again Oracle confirms that APEX will continue its efforts to enhance this development platform, which should not be a surprise, but there were often doubts (especially from IT management) whether APEX will be a platform to base long term planning on, preferring ADF as the framework primarily promoted as the-way-to-go. Apex is mature, and will become more mature with the announced enhancements in this SOD.

 

  • Oracle continues to invest in the development and support of Oracle Application Express and new versions of Application Express will be released at least annually.

So, version 4.1 should not be too far away from being released, as 4.0 is almost half a year “old” now (not taking into account the time the EA release was available).

Oracle lists some features planed for the upcoming version, and I just would like to comment on some of them:

 

  • Development for Mobile Applications – Include themes and HTML templates suitable for smart phones and mobile devices.

Creating an APEX GUI for mobile devices using themes and templates is already possible with the current release, in fact, was possible with earlier releases as well. So I’m very curious what the Apex team comes up with, as I’m currently migrating a web application to Oracle/Apex which must be accessible from both: mobile and PC-based browsers.

  • Charting - Provide for chart rendering without using Flash (to enable display on mobile devices).

iWhatever users will be very thankful ;-).

  • Interactive Reporting – Allow multiple reports on one page and support pivot queries.

Great! Finally a pivot feature in Apex. I believe, this is the number 1 missing feature in Interactive reports, which keeps business users from using Apex as “Excel-replacement” analysis tool. Hopefully the user will be able to customize the pivot report just like in Excel.

  • Tabular Forms – Allow multiple tabular forms on one page and continue to expand tabular forms validations.
  • Master-Detail-Detail – Allow the generation of pages to support master-detail-detail relationships.

Not being able to have multiple tabular forms on one page (out-of-the-box) is one of those annoying things almost every developer has experienced when starting to develop with Apex. Developers and customers/users will appreciate this enhancement.

  • Use of ROWID – Allow usage of ROWID for Automatic DML processing (as an alternative to identifying the PK columns).

So a developer will be able to choose between ROWID and (manually identifying) PK columns? That would definitely be nice.

  • Modal Dialogue - Add ability to display a dialog on top of a page (the rest of the page will be grayed out).

This is possible now too, but only by using some JS library or writing your own DIV based layout. A build-in functionality would be of great help, as this often is a wanted functionality.

  • Data Upload - Enable end-users to upload data into an existing table (within an application).

I bet there are numerous Apex applications which have just this functionality. So, no need to come up with custom solutions anymore? Wizard based? How customizable will this feature be? I’m very curious.

Monday, November 1, 2010

It’s the little things in life …

syntax


Sometimes you get information and you ask yourself: "Why didn't I know this? This would have made (certain) things so much easier!" or "I didn't know I could do this". Well, this just happened to me and after asking a few colleges, I found out: I’m not the only Oracle developer who didn't know this (without being too concerned about the statistical relevance of the sample size, I would estimate that about 80% of PL/SQL developers might not know this). So I decided to write this little post.



Consider this piece of code:
CREATE TABLE examples (sample_str VARCHAR2 (100));

INSERT INTO examples (sample_str)
VALUES ('It''s the little things in life ...');

DECLARE
   v_stm VARCHAR2 (1000);
BEGIN
   v_stm := 'insert into examples (sample_str) values (''It''''s the little things in life ...'')';
   EXECUTE IMMEDIATE v_stm;
END;



Take a look at the quotation syntax. Most developers will recognize the double-quote as “escape” for the single quote to be able to insert/assign the quote as part of the string value. This syntax can get really messy, especially in combination with concatenations or nested quotes in dynamic SQL. Such code can be a real pain to debug and maintain. The wrong number of quote’s will result in a “ORA-01756: quoted string not properly terminated” error..

In 10g Oracle introduced a new quoting syntax. This new feature enables us to embed single-quotes in literal strings without having to resort to double, triple or sometimes quadruple quote characters. To use this mechanism, simply prefix the string with a “q”. The syntax is q'[...]', where the "[" and "]" characters can be any of the following (as long as they do not already appear in the string):


  • !
  • {}
  • []
  • ()
  • <>

Using this quoting syntax, the above example would look like this:



INSERT INTO examples (sample_str)
VALUES (q'[It's the little things in life ...]');

DECLARE
v_stm VARCHAR2 (1000);
BEGIN

v_stm := q'[insert into examples (sample_str) values ('It''s the little things in life ...')]';

EXECUTE IMMEDIATE v_stm;

END;

Looks a lot better, doesn’t it?! Well, there is still one of these double quoted syntax things in this example. Guess what: The mechanism even allows you to code nested single-quoting syntax:



DECLARE
v_stm VARCHAR2 (1000);
BEGIN

v_stm := q'[insert into examples (sample_str) values (q'<It's the little things in life ...>')]';

EXECUTE IMMEDIATE v_stm;

END;


Siquis in hoc artem populo non novit amandi, Hoc legat et lecto carmine doctus amet.

Thursday, September 2, 2010

Book review: Oracle Application Express 3.2 – The Essentials and More

 4527EN_MockupCover

Language : English
Paperback : 644 pages [ 235mm x 191mm ]
Release Date : June 2010
ISBN : 1847194524
ISBN 13 : 978-1-847194-52-7
Authors : Arie Geller, Matthew Lyon

 

 

In June, just before the official release of APEX 4.0 and #APEX4 Twitter messages popping up on my desktop every minute, I noticed a tweet from one of the authors of this book saying something like: “...bad timing…just released our book APEX 3.2 – Essentials and More …”. Well, I agree. Just looking at the books title, you might really think: Bad Timing. But, you should never just judge a book by its cover (or Title, in this case).

Just let´s forget about APEX 4.0 for a moment.

This book covers almost all aspects you probably will encounter when developing with APEX. The authors start the book explaining the concepts of APEX and explaining the “APEX Angle” of related (or required) technologies like HTML, CSS, Javascript and AJAX. Once the basics are covered, Application development with APEX is explained in great detail. And by this, I mean: In great detail! No OTN Hands-On like tutorials (step-by-step-click-through-without-further-explanation). Instead, sparse code samples, no more then necessary screenshots and lots, lots, lots of explanations. That´s exactly what I like about this book. It´s not a tutorial and more then just a reference. The authors explain the essence of developing with APEX and beyond. The book concludes in a “Best Practice” Chapter which I think is an excellent subject to finish.

Although the book covers almost all aspects, some aspects are covered just a bit too brief. The chapter about Themes an Templates, for example, is covering only the very basics and is not inviting to start creating a template or theme on your own. Extending APEX with JavaScript libraries like JQuery could have had more attention, as this is common practice nowadays.

I like this book. It is a great companion for ever APEX developer.

But what about the 3.2 / 4.0 bad-timing thing?

Well, there are still lots of environments and applications based on APEX 3.2. It will take a while until all those have been upgraded.  Apex 4.0 is a great step forward, but the basic principles are still the same as in 3.2. Almost all 3.2 techniques and functionality still is there. So this book will help you too when learning and developing in APEX 4.0. If you are aware of the new functionality and keep in mind that the screenshots and examples might look a bit different, this book is still a valid reference. Anyway, I don´t think you will find an APEX 4.0 book this extensive just yet.

Tuesday, June 8, 2010

YAAFPG: Yet Another Apex Football Prediction Game

testApex.oracle.com has been upgraded with the 4.0 Release Candidate. Looks like the APEX team will present the official 4.0 release very soon. Without trying to “predict” the When or Where, I regret that I am not able to participate in this year´s ODTUG Kaleidoscope conference.

With the upgrade, I have my first public accessible application running on version 4.0 live. I tried to combine two exciting things in life: Soccer (or football, as we say in Europe) and Oracle technology. So, if you are just as much looking forward to the upcoming FIFA South Africa World Cup 2010 and APEX 4.0, join my little predictor game: FIFAPEX . It´s free, It´s fun and you can win something: David Peake donated the book “Beginning Oracle Application Express”, written by Rick Greenwald. So, join the game, compare yourself to other enthusiast, and make chance to win and learn all about Oracle Application Express, the tool that was used to build this site.

(BTW: FIFAPEX still open for sponsoring. If you would like to see your companies banner or logo on FIFAPEX in exchange for a small item participants might find appealing to win, just send an email to admin@fifapex.net)

Wednesday, February 10, 2010

Tabular Forms on Complex Views - using INSTEAD OF Triggers

37593089_7cd841cd66 Creating tabular forms in Apex is relative straight forward. One gets fully generated, instant insert/update/delete functionality. Unfortunately (for the form developer), tables are usually part of a more or less complex data model, which is optimized for data storage, rather then for form-layout. Well, Apex offers some possibilities to the developer to enable tabular forms beyond 1:1 table based.

Collections

One alternative is to create your tabular form using the Apex Collection API. There is a good article on Martin Giffy D'Souza’s blog describing this technique.
This collection-approach basically pre-fetches data into a (PL/SQL) collection from a query/cursor. The “collected” data will be displayed in the form. An on-submit page process will store the data submitted from the form into the collection. After this you can perform some validation before submitting the data to table(s) in an on-submit page process.

Database Views

Well, I favor an approach that keeps the data-logic in the database, which is (in my opinion) more accessible to developers, more likely to be re-used and less fragmented (code-wise), thus easer to maintain: Database Views.
Views can be based on several tables or other views. Usually views are used to query data only, but in my case, I would like to perform all DML through an Apex form based on a view. As long as my view is “key-preserving” for the joined table I would like to perform the DML on, this is not a problem.

Key preserved means, the row from the base table will appear AT MOST ONCE in the output view on that table.


When my SQL becomes more complex, using outer joints, aggregations or sub-queries, the resulting view will probably not be updateable anymore without the use of INSTEAD OF Triggers. The INSTEAD OF trigger(s) will handle all the DML processing and hide the processing complexity from APEX.
Applying this view-Approach, you can keep the UI layer (APEX) separated from the data model layer (database).
Let`s go through this step-by-step:
  • create a view which will return all the data you would like to be available in your tabular form
  • implement the DML processing using an INSTEAD OF trigger on this view 
  • build the tabular form UI in APEX based on this using standard APEX processing logic

Example

This example will implement a simple timesheet in APEX. The timesheet should show all projects of the (APEX-) user for a given month. The user must be able to enter "times spend" for every project assigned to him, for every day. The form should only contain one submit button (no add or remove rows button):

Project Name 1 2 . . . 30 31
project 1
project 2
project n

I started creating a new workspace and used the EMP table as starting point. I added some table definitions to hold project-, assignment- and timesheet information.
You can download the complete DDL scripts for this example here.

Preparations

  1. You'll need a workspace associated to a database schema containing the Apex demo objects (DEMO_CUSTOMERS, DEMO_ORDERS, DEMO_STATES, DEMO_USERS, …)
  2. run the timesheet_demo.sql script to create the additional table objects (including some demo data)

Step 1: Create the Pivot View

Have a look at these tables and data I added to the demo application's model:
Table DEMO_PROJECTS defines project with start- and end-date:
select * from demo_projects;

PROJECT_ID PROJECT_NAME                   START_DAT END_DATE 
---------- ------------------------------ --------- --------- 
0 Marketing Campaign Computers   01-OKT-09 31-DEC-10 
1 Marketing Campaign Software    01-JUL-09 31-JUL-10

2 rows selected.


Table DEMO_TIMESCHEETS holds the time spend on an assignment:

select * from demo_timesheets; 

no rows selected.

Now lets join there tables:

SELECT   pj.project_id,
         pj.project_name,
         am.assignment_id,
         us.user_id,
         us.user_name,
         ts.timesheet_date,
         ts.hours
  FROM   demo_projects pj,
         demo_assignments am,
         demo_users us,
         demo_timesheets ts
 WHERE       pj.project_id = am.project_id
         AND am.user_id = us.user_id
         AND am.assignment_id = ts.assignment_id(+);
   
PROJECT_ID PROJECT_NAME                   ASSIGNMENT_ID    USER_ID USER_NAME  TIMESHEET      HOURS 
---------- ------------------------------ ------------- ---------- ---------- --------- ---------- 
0 Marketing Campaign Computers               3         22 SCOTT                          
1 Marketing Campaign Software                5         22 SCOTT                          
1 Marketing Campaign Software                6         23 FORD                          

3 rows selected.

The timesheet table does not contain any data yet. Even if there would be some timesheet data, there is no guaranty there are no gaps in the dates. I would like to have a result with dense dates for all project assignments:

SELECT   prj.*, ts.hours
  FROM   (SELECT   d.thedate,
                   pj.project_id,
                   pj.project_name,
                   am.assignment_id,
                   us.user_id,
                   us.user_name
            FROM   (    SELECT   mindat + LEVEL - 1 thedate
                          FROM   (SELECT   MIN (start_date) mindat,
                                           MAX (end_date) maxdat
                                    FROM   demo_projects)
                    CONNECT BY   LEVEL <= maxdat - mindat + 1) d,
                   demo_projects pj,
                   demo_assignments am,
                   demo_users us
           WHERE   pj.project_id = am.project_id AND am.user_id = us.user_id)
         prj,
         demo_timesheets ts
 WHERE   prj.assignment_id = ts.assignment_id(+)
         AND prj.thedate = ts.timesheet_date(+);
   
THEDATE   PROJECT_ID PROJECT_NAME                   ASSIGNMENT_ID    USER_ID USER_NAME       HOURS 
--------- ---------- ------------------------------ ------------- ---------- ---------- ---------- 
01-JUL-09          0 Marketing Campaign Computers               3         22 SCOTT                
01-JUL-09          1 Marketing Campaign Software                6         23 FORD                 
01-JUL-09          1 Marketing Campaign Software                5         22 SCOTT                
02-JUL-09          0 Marketing Campaign Computers               3         22 SCOTT                
02-JUL-09          1 Marketing Campaign Software                6         23 FORD                 
02-JUL-09          1 Marketing Campaign Software                5         22 SCOTT                
03-JUL-09          0 Marketing Campaign Computers               3         22 SCOTT                
03-JUL-09          1 Marketing Campaign Software                6         23 FORD                 
03-JUL-09          1 Marketing Campaign Software                5         22 SCOTT                
04-JUL-09          0 Marketing Campaign Computers               3         22 SCOTT                 
. . .  

28-DEC-10          1 Marketing Campaign Software                5         22 SCOTT                
29-DEC-10          0 Marketing Campaign Computers               3         22 SCOTT                
29-DEC-10          1 Marketing Campaign Software                5         22 SCOTT                
29-DEC-10          1 Marketing Campaign Software                6         23 FORD                 
30-DEC-10          0 Marketing Campaign Computers               3         22 SCOTT                
30-DEC-10          1 Marketing Campaign Software                5         22 SCOTT                
30-DEC-10          1 Marketing Campaign Software                6         23 FORD                 
31-DEC-10          0 Marketing Campaign Computers               3         22 SCOTT                
31-DEC-10          1 Marketing Campaign Software                5         22 SCOTT                
31-DEC-10          1 Marketing Campaign Software                6         23 FORD                

1647 rows selected.

Now we got a dense dataset, let's build the pivot statement. Well, I could use the 11g pivot function, but to make this statement more generic, I'll use the standard pre-11g way to pivot my timesheet data:
As shown in my lay-out example for the actual form I want to implement, the result of the query should show one row with all the days of a month containing the time entered for a certain project per user. Here it is:


SELECT   theyear || '-' || themonth year_month,
           theyear,
           themonth,
           project_id,
           project_name,
           assignment_id,
           user_id,
           user_name,
           SUM (d1) d1,
           SUM (d2) d2,
           SUM (d3) d3,
           . . .
           SUM (d28) d28,
           SUM (d29) d29,
           SUM (d30) d30,
           SUM (d31) d31
    FROM   (SELECT   EXTRACT (YEAR FROM thedate) theyear,
                     EXTRACT (MONTH FROM thedate) themonth,
                     project_id,
                     project_name,
                     assignment_id,
                     user_id,
                     user_name,
                     CASE WHEN day_in_month = 1 THEN hours ELSE NULL END d1,
                     CASE WHEN day_in_month = 2 THEN hours ELSE NULL END d2,
                     CASE WHEN day_in_month = 3 THEN hours ELSE NULL END d3,
                     . . .
                     CASE WHEN day_in_month = 28 THEN hours ELSE NULL END d28,
                     CASE WHEN day_in_month = 29 THEN hours ELSE NULL END d29,
                     CASE WHEN day_in_month = 30 THEN hours ELSE NULL END d30,
                     CASE WHEN day_in_month = 31 THEN hours ELSE NULL END d31
              FROM   (SELECT   prj.*,
                               ts.hours,
                               EXTRACT (DAY FROM prj.thedate) day_in_month
                        FROM   (SELECT   d.thedate,
                                         pj.project_id,
                                         pj.project_name,
                                         am.assignment_id,
                                         us.user_id,
                                         us.user_name
                                  FROM   (    SELECT   mindat + LEVEL - 1 thedate
                                                FROM   (SELECT   TRUNC(MIN(start_date))
                                                                    mindat,
                                                                 TRUNC (
                                                                    MAX (end_date)
                                                                 )
                                                                    maxdat
                                                          FROM   demo_projects)
                                          CONNECT BY   LEVEL <=
                                                          maxdat - mindat + 1)
                                         d,
                                         demo_projects pj,
                                         demo_assignments am,
                                         demo_users us
                                 WHERE   pj.project_id = am.project_id
                                         AND am.user_id = us.user_id) prj,
                               demo_timesheets ts
                       WHERE   prj.assignment_id = ts.assignment_id(+)
                               AND prj.thedate = ts.timesheet_date(+)))
GROUP BY   theyear,
           themonth,
           project_id,
           project_name,
           assignment_id,
           user_id,
           user_name;

YEAR_MO THEYEAR THEMONTH PROJECT_ID PROJECT_NAME                 ASSIGNMENT_ID USER_ID USER_NAME  D1  D2  D3 … D29 D30 D31 
------- ------- -------- ---------- ---------------------------- ------------- ------- --------- --- --- --- … --- --- --- 
2009-10    2009       10          1 Marketing Campaign Software              6      23 FORD                             
2009-10    2009       10          0 Marketing Campaign Computers             3      22 SCOTT                            
2009-10    2009       10          1 Marketing Campaign Software              5      22 SCOTT                            
2009-11    2009       11          1 Marketing Campaign Software              6      23 FORD                             
2009-11    2009       11          0 Marketing Campaign Computers             3      22 SCOTT                            
2009-11    2009       11          1 Marketing Campaign Software              5      22 SCOTT                            
2009-12    2009       12          1 Marketing Campaign Software              6      23 FORD                             
2009-12    2009       12          0 Marketing Campaign Computers             3      22 SCOTT                            
2009-12    2009       12          1 Marketing Campaign Software              5      22 SCOTT                            
2009-7     2009        7          1 Marketing Campaign Software              6      23 FORD                             
2009-7     2009        7          0 Marketing Campaign Computers             3      22 SCOTT  
. . .  
2010-8     2010        8          0 Marketing Campaign Computers             3      22 SCOTT                            
2010-8     2010        8          1 Marketing Campaign Software              5      22 SCOTT                            
2010-9     2010        9          1 Marketing Campaign Software              6      23 FORD                             
2010-9     2010        9          0 Marketing Campaign Computers             3      22 SCOTT                            
2010-9     2010        9          1 Marketing Campaign Software              5      22 SCOTT                           

54 rows selected.

OK, still no time data, but exactly the lay-out I was looking for.

Step 2: INSTEAD OF view trigger



Editing timesheet data will only effect the table DEMO_TIMESHEETS. For users there will be no difference between insert, update or delete as all fields in the pivot/matrix form will always be visible.

To handle a DML for a single row of DEMO_TIMESHEETS, I will provide a procedure which will:

  • insert a row if the combination of assignment/date does not exist AND hours is not NULL/0
  • update a row if combination of assignment/day does exist AND hours is not NULL/0
  • delete a row if combination of assignment/day does exist AND hours is NULL/0

CREATE OR REPLACE PROCEDURE write_to_timesheet (p_asgnmt_id   IN number,
                                                p_date        IN date,
                                                p_hours       IN number)
AS
BEGIN
   IF p_hours IS NOT NULL AND p_hours <> 0
   THEN
      UPDATE   demo_timesheets
         SET   hours = p_hours
       WHERE   assignment_id = p_asgnmt_id
               AND TRUNC (timesheet_date) = TRUNC (p_date);

      IF sql%ROWCOUNT = 0
      THEN
         INSERT INTO demo_timesheets (assignment_id, timesheet_date, hours)
           VALUES   (p_asgnmt_id, TRUNC (p_date), p_hours);
      END IF;
   ELSE
      DELETE FROM   demo_timesheets
            WHERE   assignment_id = p_asgnmt_id
                    AND TRUNC (timesheet_date) = TRUNC (p_date);
   END IF;
EXCEPTION
   WHEN OTHERS
   THEN
      raise_application_error (-20001, 'Error updating the timesheet!!!');
END;
/

I used the upper pivot SQL-statement to create the view DEMO_TIMESHEET_V. To be able to use this view as basis for my form, I have to make it updateable. The view DEMO_TIMESHEET_V is not inherently updateable. It requires an INSTEAD OF trigger. With an INSTEAD OF trigger, you can write normal UPDATE, INSERT, and DELETE

statements against the view, and the INSTEAD OF trigger works invisibly in the background to make the right actions take place. In this trigger I will call the procedure write_to_timesheet to perform the DML on the underlying table DEMO_TIMESHEETS. In fact, the procedure write_to_timesheet will be called a maximum of 31 times, depending on the month presented in the timesheet. Well, at this point I have to admit, this is not exactly the sexiest code I have ever written, but it does the job and it's pretty easy to understand (and I wonder, why I didn't choose an example with a weekly timesheet form).

CREATE OR REPLACE TRIGGER demo_timesheet_v_io_trg
   INSTEAD OF UPDATE
   ON demo_timesheet_v
   REFERENCING NEW AS new OLD AS old
   FOR EACH ROW
DECLARE
   v_first_day   date;
BEGIN
   v_first_day :=
      TO_DATE ('01' || '-' || :new.themonth || '-' || :new.theyear,
               'DD-MM-YYYY');

   write_to_timesheet (:new.assignment_id, v_first_day + 0, :new.d1);
   write_to_timesheet (:new.assignment_id, v_first_day + 1, :new.d2);
   write_to_timesheet (:new.assignment_id, v_first_day + 2, :new.d3);
   . . .
   write_to_timesheet (:new.assignment_id, v_first_day + 25, :new.d26);
   write_to_timesheet (:new.assignment_id, v_first_day + 26, :new.d27);
   write_to_timesheet (:new.assignment_id, v_first_day + 27, :new.d28);

   -- special treatment for days not valid for some months

   IF EXTRACT (DAY FROM LAST_DAY (v_first_day)) >= 29
   THEN
      write_to_timesheet (:new.assignment_id, v_first_day + 28, :new.d29);
   END IF;

   IF EXTRACT (DAY FROM LAST_DAY (v_first_day)) >= 30
   THEN
      write_to_timesheet (:new.assignment_id, v_first_day + 29, :new.d30);
   END IF;

   IF EXTRACT (DAY FROM LAST_DAY (v_first_day)) >= 31
   THEN
      write_to_timesheet (:new.assignment_id, v_first_day + 30, :new.d31);
   END IF;
EXCEPTION
   WHEN OTHERS
   THEN
      -- Please, do some error handling and allow me
      -- to skip this part for this time...
      RAISE;
END demo_timesheet_v_io_trg;
/

Now I can issue updates against the view:

UPDATE   demo_timesheet_v 
SET   d1 = 4 
  ,   d10 = 5 
  ,   d28 = 6 
  ,   d31 = 7 
WHERE year_month = '2010-2' 
  AND assignment_id = 5
;

And the data will be written into the time sheet table (except the 31-Feb time, so you can't fool your manager):

ASSIGNMENT_ID TIMESHEET      HOURS 
------------- --------- ---------- 
5 01-FEB-10          4 
5 10-FEB-10          5 
5 28-FEB-10          6

3 rows selected.

So far I didn't have to code anything in Apex. In the next step I will build the actual form.

Step 3: build the tabular form in APEX

I promised, that the timesheet form will be completely based on standard Apex functionality (strictly spoken, using the collection approach is standard Apex functionality too), without any additional coding in Apex. Although it's mostly just clicking through the wizards and property screens, I will walk through it step by step:
Assuming you already have created an application or you are using the demo application, the first step will be to create a new page:

Create Page:

  • page type: Form
  • now choose: Tabular Form

The Create Tabular Form wizard appears:

Step "Table / View Owner":

  • select the schema owning the demo objects
  • For "Allowed Operations" choose "Update Only". Remember, the pivot view contains all the rows. There is no need to insert or delete rows.

Step "Table / View Name":

  • select the view DEMO_TIMESHEET_V from the list

Step "Displayed Columns":

  • just select all the columns

Step "Primary Key":

  • Each row of the view can be uniquely identified by the column values of year_month and assignment_id. Select these from the lists.

For those folks, who wondered why I created the year_month column: the reason is, I only can assign two columns as PK columns in the Apex wizard (I remember Oracle Portal had the same restriction. I know there was a workaround in Portal to add additional columns; does anybody know such a "backdoor" in Apex?). To overcome the limitation, you might have to combine two or more columns into one, depending on the complexity of your view.

Important: you won't get any error message while creating the form, but when submitting changes to the form without the correct key, Apex will throw an error:


Error in mru internal routine: ORA-20001: Error in MRU: row= 1, ORA-20001: ORA-20001: Current version of data in database has changed since user initiated update process. <checksum information>, <your MRU statement>.

Step "Primary Key Source":
  • Choose "Existing Trigger" for both primary key columns.

Step "Updateable Columns":
  • Updateable columns will be D1 . . . D31.

Step "Page and Region Attributes":
  • Give the page an appropriate name (like "Timesheet") and accept the defaults for the rest of the properties.

Step "Tab":
  • just accept the default

Step "Button Labels":
  • just accept the default

Step "Branching":
  • just accept the default

Step "Confirm":
  • Click "Finish" and run the page.

The lay-out is not ideal yet. After changing the width of columns D1 ... D31 to "1" and, modifying the headers and hiding some of the ID columns my timesheet form look like this:
timesheet1s

Now I will add two parameters (Year and Month) and modify the query, so only the assignments of the current Apex user will be shown. I'm not going to describe this in detail, but eventually I will use these parameters (select lists) in the source query of the form region:

timesheet3 

With as result:

timesheet4

One last thing to do: prevent the columns of days 29/30/31 from being displayed when not valid for a month. I just place conditions on the Column Attributes of column D29 - D31:


timesheet5 


Conclusion

What I wanted to show is: when developing with Apex, keep in mind that you are running Apex on a very powerful environment: the Oracle database. Preferably use Apex to build your user interface and standard transaction form handling. Complex data logic should preferably be coded in the database, not in the Apex Page processing. No, it's not black & white, eventually you have to find a balance between choosing the database or the Apex approach in individual cases.

PS: if you are getting a "ORA-01445: cannot select ROWID from, or sample, a join view without a key-preserved table", read this post by Tobias Arnold.

themes4apex