I'm working with APEX 19.2. I'm trying to handle constraint errors with an error handling function.
I have an interactive grid built on a table with unique constraint. I created constraint_lookup that matches constraint name with message.
I created a function mainly based on Oracle Doc example (that is for example in package wwv_flow_error_api)
The only thing I changed was the display location:
l_result.display_location := case
when l_result.display_location =
apex_error.c_on_error_page then
apex_error.c_inline_with_field_and_notif
else
l_result.display_location
end;
Right now when I'm trying to add a value with non-unique value I get a message in notification like I wanted, but I don't know how to handle it to show error in notification and with the field (like in apex validation, where you can associate item)
I tried to list all apex_error attributes and I get
p_error
message ORA-00001: naruszono więzy unikatowe (#CONSTAINT_NAME#)
additional_info
ORA-00001: naruszono więzy unikatowe (#CONSTAINT_NAME#)
display_location ON_ERROR_PAGE
association_type
page_item_name
region_id
column_alias
row_num
model_instance_id
model_record_id
apex_error_code
original_message
original_additional_info
ora_sqlcode -1
ora_sqlerrm ORA-00001: naruszono więzy unikatowe (#CONSTAINT_NAME#)
error_backtrace
error_statement "ADM"
l_result
message #ERROR MESSAGE#
additional_info ORA-00001: naruszono wiezy unikatowe (#CONSTAINT_NAME#)
display_location INLINE_WITH_FIELD_AND_NOTIFICATION
page_item_name
column_alias
How to connect field from constraint with the field in interactive grid?
You should add p_page_item_name parameter. For example:
p_message => 'Employee name cannot be null',
p_display_location => apex_error.c_inline_with_field_and_notif ,
p_page_item_name => 'P10_NAME');
Can you update your error handling function with the following code please. It adds additional debug statements.
if p_error.ora_sqlcode in (-1, -2091, -2290, -2291, -2292) then
l_constraint_name := apex_error.extract_constraint_name (
p_error => p_error );
apex_debug.info( 'Raised constraint error: %s', l_constraint_name );
begin
select message
into l_result.message
from constraint_lookup
where constraint_name = l_constraint_name;
apex_debug.info( 'Constraint found, new message: %s', l_result.message );
exception when no_data_found then
apex_debug.info( 'Constraint not found in constraint_lookup' );
end;
end if;
Run your application in debug mode and reproduce the error. After that you can use View Debug to find out if your constraint_lookup entry is actually used.
Related
Method in Dao Interface
#RegisterRowMapper(MapMapper.class)
#SqlQuery(
"SELECT Table1.tenantId,Table1.sacTenantId, sacLogId,currentStep,status from Table1 inner join Table2 on Table1.tenantId = Table2.tenantId where <if(tenantId)>Table1.tenantId = :tenantId and<endif> Table2.status = 'FAILED'")
List<Map<String, Object>> getTenantFailedJobDetails(#Define("tenantId") #Bind("tenantId") String tenantId);
Error trace:
"level":"ERROR","categories":[],"msg":"Servlet.service() for servlet
[dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is
org.jdbi.v3.core.statement.UnableToCreateStatementException: Error
rendering SQL template: 'SELECT Table1.tenantId,Table1.sacTenantId,
sacLogId,currentStep,status from Table1 inner join Table2 on
Table1.tenantId = Table2.tenantId where <if(tenantId)>Table1.tenantId
= :tenantId and Table2.status = 'FAILED'' [statement:"null", arguments:{positional:{0:DUMMY-TENANT}, named:{tenantId:DUMMY-TENANT},
finder:[]}]] with root
cause","stacktrace":["org.jdbi.v3.core.statement.UnableToCreateStatementException:
Undefined attribute for token '' [statement:"null",
arguments:{positional:{0:DUMMY-TENANT}, named:{tenantId:DUMMY-TENANT},
finder:[]}]"
What could be wrong with the if condition?
To make if condition in jdbi query work I added annotation #UseStringTemplateEngine of package org.jdbi.v3.stringtemplate4 to the Dao method
If tenandId is not null then where clause will be
Table1.tenantId = :tenantId and Table2.status = 'FAILED'
else where clause will be just
Table2.status = 'FAILED'
One more information to add, for the else part annotation #AllowUnusedBindings package org.jdbi.v3.sqlobject.customizer is required
The syntax you posted is stringtemplate4, so you need to use the stringtemplate 4 engine (which you select with the annotation that you posted). Otherwise you end up with the default engine which does support only very simply substitutions (and not st4 syntax).
Requirement -
Below fields to be displayed on a APEX page for any Jira issue created.
Issue Number/Issue Id
Summary
Description
Status
Assignee
Example, user01 and user02 both having access to Oracle APEX and Jira. user01 created 3 issues and user02 created 5 issues in Jira. Now when user01 who logs into Oracle APEX, should see 3 issues and when user02 who logs into Oracle APEX, should see 5 issues on a APEX page.
https://jira.local.com/jira/rest/api2
I'm new to APEX Rest service call and request to all of you to provide some sample APEX code to call Jira REST API using username/password for the above requirement.
Thanks all.
I have done something similar before. In my case, the goal was to get all the issues of project PRJ001 (Jira Project Key) from Jira and store them in a local database table (J_ISSUES), periodically, so I've created a Job that executed the following procedure from time to time:
create or replace PROCEDURE "JIRA_SYNC_ISSUES" as
var_response CLOB;
var_counter number := 0;
var_total number := 1;
var_prj_key varchar2(10);
begin
var_prj_key := 'PRJ001';
var_total := 1;
var_counter := 0;
while var_total > var_counter
loop
apex_session.create_session (p_app_id => 107, p_page_id => 1, p_username => 'USERNAME01');
var_response:= apex_web_service.make_rest_request(
p_url => 'https://yourcompany.atlassian.net/rest/api/2/search?jql=project="'|| var_prj_key ||'"&maxResults=100&startAt=' || var_counter || '',
p_http_method => 'GET',
p_credential_static_id => 'oud_rest'
);
SELECT JSON_VALUE(var_response, '$.total' RETURNING NUMBER) into var_total
FROM DUAL;
for i in (SELECT *
FROM
JSON_TABLE(var_response, '$.issues[*]'
COLUMNS (
key VARCHAR2(100) PATH '$.key',
prj_key VARCHAR2(100) PATH '$.fields.project.key',
status VARCHAR2(100) PATH '$.fields.status.name',
updated VARCHAR2(100) PATH '$.fields.updated',
assignee VARCHAR2(100) PATH '$.fields.assignee.name',
time_spent NUMBER PATH '$.fields.timespent'
)))
loop
begin
insert into j_issues (jis_key, jis_jpr_key, jis_status, jis_updated, jis_assignee, jis_time_spent)
values (i.key,
i.prj_key,
i.status,
to_timestamp(substr(i.updated,1,10)||' '||substr(i.updated,12,8),'YYYY-MM-DD HH24:MI:SS'),
i.assignee,
i.time_spent);
exception
when dup_val_on_index then
update j_issues
set jis_jpr_key = i.prj_key,
jis_status = i.status,
jis_updated = to_timestamp(substr(i.updated,1,10)||' '||substr(i.updated,12,8),'YYYY-MM-DD HH24:MI:SS'),
jis_assignee = i.assignee,
jis_time_spent = i.time_spent
where jis_key = i.key;
end;
var_counter := var_counter + 1;
end loop;
end loop;
end jira_sync_issues;
In the first part it is authenticating and making the call to the API. In the second, it takes the var_response and inserts it into the required table.
For the first part, I've read this: https://www.jmjcloud.com/blog/simplifying-apex_web_service-oauth2-client-credentials
For the second: https://docs.oracle.com/database/121/SQLRF/functions092.htm
Notice the var_counter and var_total variables. They are used to iterate through the Jira responses, because there is a limit of items being retrieved in each response. So, if you are expecting more than that limit, you should make more calls to retrieve them.
If the volume of issues is big, there are advantages in doing a scheduled sync like this instead of letting the user wait for the entire result. After the data is in your database, you can just query it as usual.
Let me know if it helps ;)
I'm running Apex 19.2
I have a page with some items created dynamically as follows :
HTML clob;
Html := APEX_ITEM.textarea(p_idx=>32, p_value=>'MyValue',p_item_id=>'MyId',p_attributes=>'class="textarea"');
htp.p(HTML);
The page items are generated correctly :
<textarea name="f32" rows="4" cols="40" wrap="VIRTUAL" class="textarea" id="MyId"></textarea>
I'm also adding the item wrapper to match the static Items layout created from the designer.
<div class="t-Form-inputContainer col">
<div class="t-Form-itemWrapper">
<textarea name="f32" rows="4" cols="40" wrap="VIRTUAL" class="textarea" id="MyId"></textarea>
</div>
<span id="MyId_error_placeholder" class="a-Form-error"></span>
</div>
In the validation, I'm checking some rules from apex_application.g_fn arrays and I would like to show an error on the item created via :
apex_error.add_error(p_message => 'error', p_display_location => apex_error.c_inline_with_field_and_notif, p_page_item_name=> 'MyId');
After validation, the error is not shown next to the item created. Notification also appears but it's empty. However If I try to show the same error on a static item created in the designer. The error is shown properly.
Can anyone help please ?
Thanks.
As you've found, APEX_ITEM doesn't work with APEX_ERROR in the way that you'd like it to. Marc's comments here indicate that APEX_ITEM will likely not be developed further, so it probably never will. https://stackoverflow.com/a/61737128/3010084
Your best option might be to move your validation logic to a stored procedure. Do all the validation in one call via parameters. In addition to the regular parameters, add a parameter that indicates if the response should be JSON or not. If so, just return a JSON document with the errors, otherwise use apex_error. This will allow you to call the validation logic via Ajax to show the errors where you like, but also on submit/page processing (because client-side validation can't be trusted).
Here are some steps you can follow to see how this works... First, compile the following procedure in your schema:
create or replace procedure validate_thing(
p_description in varchar2,
p_return_json in boolean,
p_json_result out json_object_t
)
is
l_errors_arr json_array_t := json_array_t();
l_error_obj json_object_t := json_object_t();
l_item_id varchar2(30);
l_error_message varchar2(255);
begin
if length(p_description) > 10
then
l_item_id := 'description';
l_error_message := 'Description should be less than 10 characters.';
if p_return_json
then
l_error_obj := json_object_t();
l_error_obj.put('pageItem', l_item_id);
l_error_obj.put('message', l_error_message);
l_errors_arr.append(l_error_obj);
else
-- Server-side code will not worry about displaying the error with the item as
-- this is just a backup for the client-side validation
apex_error.add_error(
p_message => l_error_message,
p_display_location => apex_error.c_inline_in_notification
);
end if;
end if;
if p_return_json
then
p_json_result := json_object_t();
if l_errors_arr.get_size() > 0
then
p_json_result.put('status', 'error');
p_json_result.put('errors', l_errors_arr);
else
p_json_result.put('status', 'success');
end if;
end if;
end;
As you can see, the procedure has logic to do client-side validations (JSON) or server-side validation (APEX_ERROR). You would need to add additional parameters and logic as needed for the form.
Create a new blank page in your app and go to the Page Designer for the new page. Right-click Content Body (under Regions) and select Create Region. Set the region's Type to PL/SQL Dynamic Content and add the following code to the PL/SQL Code attribute:
declare
html clob;
begin
-- The div and fieldset wrappers are needed so that APEX will generate an error
-- message template automatically to display the error inline.
html := '<div><fieldset>';
html := html || APEX_ITEM.textarea(p_idx=>32, p_value=>'MyValue',p_item_id=>'description',p_attributes=>'class="textarea apex-item-textarea"');
html := html || '</fieldset></div>';
htp.p(html);
end;
That code uses apex_item to add an item to the page dynamically. Note, the value passed to p_item_id, as that's important. The apex-item-textarea class is needed for error styling and the div and fieldset wrappers are needed to display error messages inline.
Select the Processing tab in Page Designer. Right-click Ajax Callback and select Create Process. Set Name to DO_VALIDATIONS and enter the following code in the PL/SQL Code field.
declare
l_result json_object_t;
begin
validate_thing(
p_description => apex_application.g_x01,
p_return_json => true,
p_json_result => l_result
);
htp.p(l_result.to_string());
end;
That is the code that will call validate_thing with p_return_json set to true. Note that the value of "description" is being passed in via apex_application.g_x01. You have g_x01 - g_x20 to work within this way. There are various options you could leverage to sent values in via Ajax, this is just one example. See see the doc on apex.server.process (used next) for more info.
Return to the rendering tab, right-click the new region, and select Create Button. Set the Button Name to SUBMIT. Right-click the SUBMIT button and select Create Dynamic Action. Set the Name to SUBMIT clicked. Select the default Show action, set its Action to Execute JavaScript Code, then add the following code to the Code field:
apex.server.process(
'DO_VALIDATIONS',
{
x01: $x('description').value
},
{
success: function(result) {
apex.message.clearErrors();
if (result.status === 'error') {
for (var idx = 0; idx < result.errors.length; idx++) {
result.errors[idx].type = 'error';
result.errors[idx].location = ['page', 'inline'];
result.errors[idx].unsafe = false;
}
apex.message.showErrors(result.errors);
} else if (result.status === 'success') {
apex.page.submit('SUBMIT');
}
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR, textStatus, errorThrown)
}
}
);
This is the JavaScript code that will invoke the new DO_VALIDATIONS Ajax process. If errors are returned from the server, apex.message.showErrors will display them. Otherwise, the page is submitted for processing.
Select the Processing tab, right-click Processing, and select Create Process. Set Name to Do Validations and enter the following code in the PL/SQL Code attribute:
declare
-- Only needed to call validate_thing, not used.
l_result json_object_t;
begin
validate_thing(
p_description => apex_application.g_f32(1), -- This is where the item's value will be when submitting normally
p_return_json => false, -- This tells validate_thing to use apex_error
p_json_result => l_result
);
end;
That code will invoke validate_thing with p_return_json set to false. This will rerun the validations on the server-side to ensure they are enforced there. As it's just a backup for the client-side call, I don't worry about displaying errors inline with the items (the JS will do that).
Right-click Processing again and select Create Process. Set Name to Do Work and just enter null; for the PL/SQL Code Attribute. Set Success Message to It ran.. Under Server-side Condition, set Type to PL/SQL Expression and enter not apex_error.have_errors_occurred in the PL/SQL Expression field.
This process represents the actual business logic you want to run after validations have passed. You will only see the success message after clicking submit if both the Ajax and server-side validations have passed.
If you wish the test the server-side validations, add this line of JavaScript code in the Dynamic Action, just before the line that submits the page:
$x('description').value = '12345678910';
That will update the value of the text area to exceed the limit enforced by the server.
I have a dynamic action doing the below ,
Submit page ,
Successful Alert message,
Log out and redirect to another website (www.google.com),
And I have two required item in page.
When pressed the button and the item is null ,the successful Alert message appears and after that the system shows the error (the item is required). How can I show the successful alert message only when the process and validation are done without errors ,and when ok is pressed in the alert message redirect to website and log out from the sessions
There are different ways you could approach this. You're currently using a mix of Dynamic Actions and page-level validations and processes that aren't going to play well together. I suggest you move all the logic to Dynamic Actions. Here are step by step instructions to do what I think you're trying to do. You can learn from this and then integrate what you want back to your solution.
Create a new blank page. Mine was page 17. You'll need to update references to "P17" with your page number if it's different. Disable the page level attribute Warn on Unsaved Changes to prevent prompts before the redirect to Google.
Add a new HTML region to the page.
Add a new item to the region. Set Name to P17_FIRST_NAME and leave the default Type of Text Field.
Add a new item to the region. Set Name to P17_LAST_NAME and leave the default Type of Text Field.
Add a new item to the region. Set Name to P17_RESULT, Type to Hidden, and Value Protected to No. This item will be used to transfer messages from the server to the client via Ajax.
Add a button to the region. Set Name to RUN_PROCESS and Action to Defined by Dynamic Action.
Create a new Dynamic Action that fires when the button is clicked. The easiest way to do this is to right-click the button and select Create Dynamic Action. Set the Name to RUN_PROCESS clicked.
Select the Show action that was created by default for the Dynamic Action. Set Action to Execute PL/SQL Code and copy-paste the following code into the PL/SQL Code attribute.
declare
l_result_obj json_object_t := json_object_t();
l_errors_arr json_array_t := json_array_t();
l_error_obj json_object_t;
begin
if :P17_FIRST_NAME is null
then
l_error_obj := json_object_t();
l_error_obj.put('pageItem', 'P17_FIRST_NAME');
l_error_obj.put('message', 'First Name is required.');
l_errors_arr.append(l_error_obj);
end if;
if :P17_LAST_NAME is null
then
l_error_obj := json_object_t();
l_error_obj.put('pageItem', 'P17_LAST_NAME');
l_error_obj.put('message', 'Last Name is required.');
l_errors_arr.append(l_error_obj);
end if;
if l_errors_arr.get_size() > 0
then
l_result_obj.put('status', 'error');
l_result_obj.put('errors', l_errors_arr);
:P17_RESULT := l_result_obj.to_string();
return;
end if;
null; -- do "success" processing here
l_result_obj.put('status', 'success');
l_result_obj.put('message', 'Hi ' || :P17_LAST_NAME || ' ' || :P17_LAST_NAME ||
'! You will now be redirected to Google.');
:P17_RESULT := l_result_obj.to_string();
end;
As you can see, the validations are now being done inside the process. The PL/SQL code is making use of the JSON types introduced with Oracle 12.2. If you're on an older version of the database, you can adapt the code to use APEX_JSON instead.
While still in the Execute PL/SQL Code action, set Items to Submit to P17_FIRST_NAME,P17_LAST_NAME and Items to Return to P17_RESULT. This is how you can transfer values from the page into session state before the process executes and then back to the page after the process finishes executing.
Create a new Dynamic Action that fires on the Change event of P17_RESULT. The easiest way to do this is to right-click the item and select Create Dynamic Action. Set the Name to P17_RESULT changed.
Select the Show action that was created by default for the Dynamic Action. Set Action to Execute JavaScript Code and copy-paste the following code into the Code attribute.
var result = JSON.parse($v('P17_RESULT'));
apex.message.clearErrors();
if (result.status === 'error') {
for (var idx = 0; idx < result.errors.length; idx++) {
result.errors[idx].type = 'error';
result.errors[idx].location = ['page', 'inline'];
result.errors[idx].unsafe = false;
}
apex.message.showErrors(result.errors);
} else if (result.status === 'success') {
apex.message.alert(result.message, function(){
apex.navigation.redirect('https://google.com');
});
}
The JavaScript code takes the result from the process and either displays error messages or an alert. I'm using apex.message.alert instead of apex.message.showPageSuccess because the former supports a callback when the message is dismissed. When the message is dismissed, apex.navigation.redirect takes the user to Google.
Here's what it should look like in the end:
I hope there's enough information here for you to understand what's going on. Let me know if you have any questions. You'll find the documentation for apex.navigation and apex.message here: https://apex.oracle.com/jsapi
P.S. Here's an example of what the PL/SQL code would look like using APEX_JSON.
declare
l_error_count pls_integer := 0;
l_result_obj clob;
begin
apex_json.initialize_clob_output;
apex_json.open_object();
apex_json.open_array('errors');
if :P17_FIRST_NAME is null
then
l_error_count := l_error_count + 1;
apex_json.open_object();
apex_json.write('pageItem', 'P17_FIRST_NAME');
apex_json.write('message', 'First Name is required.');
apex_json.close_object();
end if;
if :P17_LAST_NAME is null
then
l_error_count := l_error_count + 1;
apex_json.open_object();
apex_json.write('pageItem', 'P17_LAST_NAME');
apex_json.write('message', 'Last Name is required.');
apex_json.close_object();
end if;
apex_json.close_array();
if l_error_count > 0
then
apex_json.write('status', 'error');
apex_json.close_object();
:P17_RESULT := apex_json.get_clob_output();
apex_json.free_output;
return;
end if;
null; -- do "success" processing here
apex_json.write('status', 'success');
apex_json.write('message', 'Hi ' || :P17_LAST_NAME || ' ' || :P17_LAST_NAME ||
'! You will now be redirected to Google.');
apex_json.close_object();
:P17_RESULT := apex_json.get_clob_output();
apex_json.free_output;
end;
I have an Interactive report in Apex 5, and each time the page load, I want it to look exactly as it was shown the first time I ran it, with default settings.
The problem is that if the user applies any filter, or hide columns, the next time the page loads, the report remembers that configuration.
I tried to use the APEX_IR.RESET_REPORT procedure undocumented here:
https://docs.oracle.com/database/121/AEAPI/apex_ir.htm#BABEJAFB
but it either doesn't works, or only undoes the last change, or needs many runs to actually work.
I tried a dynamic action at page load with this code:
DECLARE
v_region_id APEX_APPLICATION_PAGE_REGIONS.REGION_ID%TYPE;
BEGIN
SELECT region_id INTO v_region_id
FROM APEX_APPLICATION_PAGE_REGIONS
WHERE application_id = :APP_ID
AND page_id = :APP_PAGE_ID
AND static_id = 'Images_Report';
APEX_IR.RESET_REPORT(
P_page_id => :APP_PAGE_ID,
P_region_id => v_region_id,
p_report_id => null
);
END;
And I also tried this code
DECLARE
v_region_id APEX_APPLICATION_PAGE_REGIONS.REGION_ID%TYPE;
BEGIN
SELECT region_id INTO v_region_id
FROM APEX_APPLICATION_PAGE_REGIONS
WHERE application_id = :APP_ID
AND page_id = :APP_PAGE_ID
AND static_id = 'Images_Report';
APEX_IR.RESET_REPORT(
P_page_id => :APP_PAGE_ID,
P_region_id => v_region_id,
p_report_id => APEX_IR.GET_LAST_VIEWED_REPORT_ID(
p_page_id => :APP_PAGE_ID,
p_region_id => v_region_id
)
);
END;
I expect the report to look as in default state (on first run), every time I load the page.
Instead the report shows the last state, even if the user logs out, logs in and restarts the application.
Send RIR as the clear cache parameter in your URL
https://docs.oracle.com/database/apex-5.1/HTMDB/linking-to-interactive-reports.htm#GUID-B917CEB3-A0B9-414B-A90A-7B44DD15EA67
URL would look like
f?p=102:94:6722612001859::NO:RIR::
https://docs.oracle.com/database/apex-5.1/HTMDB/understanding-url-syntax.htm#HTMDB03019
The documentation states this regarding the apex_ir.reset_report procedure
This procedure should only be used in page submit processes.
Which could be why you had trouble