How i can display pdf file into region oracle apex? - oracle-apex

i want display PDF file into region , i tried that by call application process using below code but always same file open.( plsql dynamic content region)
DECLARE
V_URL VARCHAR2(2500);
BEGIN
V_URL :='f?p=&APP_ID.:1:&APP_SESSION.:APPLICATION_PROCESS=display_emp_blob:::FILE_ID:' ||:P6_ID;
Sys.htp.p('<p align="center">');
sys.htp.p('<iframe src="'||V_URL||'"width="99%" height="1000">');
sys.htp.p('</iframe>');
sys.htp.p('</p>');
END;
and the application process code in below
CREATE OR REPLACE PROCEDURE OPEN_FILE (P_ID NUMBER)
IS
vBlob blob;
vmimetype varchar2(50);
BEGIN
SELECT ORG_FILES.FILE_CONTENT,MIME_TYPE INTO vBlob, vmimetype
FROM ORG_FILES
WHERE ID =P_ID ;
sys.HTP.init;
owa_util.mime_header(vmimetype,false);
htp.p('Content-Length: ' || dbms_lob.getlength(vBlob));
owa_util.http_header_close;
wpg_docload.download_file(vBlob);
apex_application.stop_apex_engine;
exception
when no_data_found then
null;
END;
How i can open different PDF file into region based a value in ITEM (P6_ID) .

I think the problem you have is that the browser caches the file.
You can specify the time the browser caches with the "Cache-control" header option. Below, you have the code that I use (I have this code in the application process, not in the database):
sys.htp.init;
sys.owa_util.mime_header( 'application/pdf', FALSE );
sys.htp.p('Content-length: ' || sys.dbms_lob.getlength( v_blob));
sys.htp.p('Content-Disposition: inline; filename="'|| v_filename || '"' ); -- "attachment" for download, "inline" for display
sys.htp.p('Cache-Control: max-age=3600'); -- in seconds. Tell the browser to cache for one hour, adjust as necessary
sys.owa_util.http_header_close;
sys.wpg_docload.download_file( v_blob );
apex_application.stop_apex_engine;
You can also try some lazy load, which is the way I access my files (It may be that the way to access your file is also part of the problem). This way you make the page load without waiting for the user and then it loads and shows the file. I don't use the iframe tag but the embed tag. The way to do it is as follows:
Create a region with static content with this html
<div id="view_pdf"></div>
creates a dynamic action when the page loads, which executes javascript and add the following code
$('#view_pdf').html('');
var url = 'f?p=&APP_ID.:1:&APP_SESSION.:APPLICATION_PROCESS=display_emp_blob:::FILE_ID:' + apex.item('P6_ID').getValue();
var preview = document.createElement('embed');
preview.type = "application/pdf";
preview.width="100%";
preview.height="625px";
preview.src = url;
$("#view_pdf").append(preview);
You can modify the values depending on what you need. The embed tag uses the default way to view pdf files from browsers.
Also if what you want is to change the pdf without reloading the page you must use the previous javacript in a dynamic action when you change the value of the item.
I hope you find it useful.

My apologies, on the rare occasion I use this region type, I always think it can be refreshed.
https://spendolini.blogspot.com/2015/11/refreshing-plsql-regions-in-apex.html
The solution is to create a classic report that calls a PL/SQL function that returns your HTML.
SELECT package_name.function_name(p_item => :P1_ITEM) result FROM dual

Related

Apex : How to display an error on a page Item created dynamically?

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.

APEX row selector part 2

This is a follow on to "APEX row selector" posted 5 days ago.
The problem was collecting multiple values from an interactive grid. From the excellent links to post supplied I was able to achieve this. However, the next part of the project is to open an edit dialog page and update multiple values.
I added this code to the attribute of the interactive grid:
function (config)
{
var $ = apex.jQuery,
toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(),
toolbarGroup = toolbarData.toolbarFind("actions3");
toolbarGroup.controls.push(
{
type: "BUTTON",
action: "updateCar",
label: "Edit Selected Cars",
hot: true,
});
config.toolbarData = toolbarData;
config.initActions = function (actions)
{
// Defining the action for activate button
actions.add(
{
name: "updateCar",
label: "Edit Selected Cars",
action: updateCar
});
}
function updateCar(event, focusElement)
{
var i, records, model, record,
view = apex.region("ig_car").widget().interactiveGrid("getCurrentView");
var vid = "";
model = view.model;
records = view.getSelectedRecords();
if (records.length > 0)
{
for (i = 0; i < records.length; i++)
{
record = records[i];
alert("Under Development " + record[1]);
vid = vid + record[1] + "||";
apex.item("P18_CAR").setValue(vid);
// need to open next page here and pass parameters
}
}
}
return config;
}
I need to know how to open a form and have the parameter values available to pass to an oracle update script.
Thank you for any help you can provide. I did find some posts but I really need a good example. I have tried everything to no avail.
There are various ways you could do this. Here's one way, perhaps someone else will offer a more efficient option.
The JavaScript options for navigation in APEX are documented here:
https://docs.oracle.com/en/database/oracle/application-express/19.1/aexjs/apex.navigation.html
Since you're trying to open a separate page, you probably want to use apex.navigation.dialog, which is what APEX automatically uses when opening modal pages from reports, buttons, etc.
However, as noted in the doc, the URL for the navigation must be generated server-side for security purposes. You need a dynamic URL (one not known when the page renders), so you'll need a workaround to generate it. Once you have the URL, navigating to it is easy. So how do you get the URL? Ajax.
Create an Ajax process to generate the URL
Under the processing tab of the report/grid page, right-click Ajax Callback and select Create Process.
Set Name to GET_FORM_URL.
Set PL/SQL code to the following
code:
declare
l_url varchar2(512);
begin
l_url := apex_page.get_url(
p_application => :APP_ID,
p_page => 3,
p_items => 'P3_ITEM_NAME',
p_values => apex_application.g_x01
);
apex_json.open_object();
apex_json.write('url', l_url);
apex_json.close_object();
end;
Note that I'm using apex_item.get_url to get the URL, this is an alternative to apex_util.prepare_url. I'm also using apex_json to emit JSON for the response to the client.
Also, the reference to apex_application.g_x01 is important, as this will contain the selected values from the calling page. You'll see how this was set in the next step.
Open the URL with JavaScript
Enter the following code in the Function and Global Variable Declaration attribute of the calling page:
function openFormPage(ids) {
apex.server.process(
'GET_FORM_URL',
{
x01: ids.join(':')
},
{
success: function (data) {
var funcBody = data.url.replace(/^"javascript:/, '').replace(/\"$/,'');
new Function(funcBody).call(window);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
// handle error
}
}
);
}
In this case, I'm using apex.server.process to call the server-side PL/SQL process. Note that I'm passing the value of ids.join(':') to x01. That value will become accessible in the PL/SQL code as apex_application.g_x01. You can use additional items, or you can pass a colon-delimited string of values to just one item (as I'm doing).
The URL that's returned to the client will not be a standard URL, it will be a JavaScript snippet that includes the URL. You'll need to remove the leading and trailing parts and use what's left to generate a dynamic function in JavaScript.
This is generally frowned upon, but I believe it's safe enough in this context since I know I can trust that the response from the process call is not malicious JavaScript code.
Add a security check!!!
Because you're creating a dynamic way to generate URLs to open page 3 (or whatever page you're targeting), you need to ensure that the modal page is protected. On that page, create a Before Header process that validates the value of P3_ITEM_NAME. If the user isn't supposed to be able to access those values, then throw an exception.

How to create a new record and open a page in APEX 5

I'm trying to bind an "Execute PL/SQL Code" to a button using Dynamic Actions then open a page using the new ID (execid)
begin
insert into SMIG_EXECUTION(EXECNAME, CALL, STEPID, DURATIONMIN)
values('bla bla',REPLACE(:P31_CALLTEMPLATE,'#STEPID#',to_char(:P31_STEPID)), :P31_STEPID, 0)
returning execid into :P31_NEWEXECID ;
end;
The PL/SQL code is working, but I can't shake the link to opening the new page as a Dynamic Action and passing that new value as P2_EXECID.
You can accomplish this by using window.open() (javascript function)
open() method opens a new browser window.
Add TRUE ACTION to your existing Dynamic Action
Choose EXECUTE JAVASCRIPT CODE for your Action
Then paste this code:
window.open('f?p='+$v('pFlowId')+':'+$v('pFlowStepId')+':'+$v('pFlowInstance')+'::::<page item here>:<value of the item to be passed>:','_self');
Note:
$v('pFlowId') => APPLICATION ID
$v('pFlowStepId') => PAGE NUMBER
$v('pFlowInstance') => SESSION ID
If multiple items/values needs to be passed, you can do that by listing the items/values with a comma as a delimeter
i.e. 'f?p=.....:P2_ITEM1,P2_ITEM2,P2_ITEM3:1,2,3:';
EDIT: added second parameter

Excel VBA script or macro for linking to new Excel document using a template in it

I have a small family-operated shop and, in the process of speeding things up and/or automating them, I need help on the following matter (will try to explain as well as possible, since I am at a novice level on this kind of stuff.)
So, in my shop we offer a certain service (taking specific measurements of body dimensions along with weight/sugar levels etc etc). I have created an .xlsx document that contains all required fields and saved it as a template for future use. What I need to do is this:
I want to have a "master" Excel file with the names of our customers. From there, each name when clicked should open a new Excel file, using the aforementioned template, which would eventually be saved as each customer's record. I've tried a script for linking to the template but opening it as a new file (with the template in it) but, the problem is that each time I click on the name on the master file it opens a new document altogether, while I need it to open a new document named after the name in the original cell, with the template in it. As far as I can think, this is the best "automation" I can accomplish. Is it plausible? If so, how can I do it?
edit: this is the code, as i found it elsewhere:
'File:
' OfficeTemplate.vbs
'
'Problem:
' A hyperlink from an Office application to an Office template opens the template,
' instead of creating a new file.
' The proposed solution
' support.microsoft.com/kb/278627
' did not work.
'
'Solution:
' Create a hyperlink to a VBS file that starts the process.
'
'Instructions:
' Copy this VBScript into the same directory of your template.
' Rename it so that the VBS file name has the name of the template file in front.
' Example:
' Template name: test.dotx
' VBScript name: test.dotx.vbs
' Create the hyperlink to the VBS file.
Set fso = CreateObject("Scripting.FileSystemObject")
'Get the name of the template
OurName = fso.GetBaseName(WScript.ScriptName)
'Find all files in our directory
For Each File In fso.GetFolder(fso.GetParentFolderName(WScript.ScriptFullName)).Files
'Did we found the template?
If StrComp(OurName, File.Name, vbTextCompare) = 0 Then
'Invoke the default verb
CreateObject("Shell.Application").Namespace(0).ParseName(File.Path).InvokeVerb
'Wait a second to let the application start
WScript.Sleep 1000
'Done
Exit For
End If
Next
this is my template:
http://i215.photobucket.com/albums/cc55/psyclone_tread/templ.jpg
this is the master file, just a column with names and one with phone numbers, i want the names to link to each customer's individual file.
http://i215.photobucket.com/albums/cc55/psyclone_tread/master.jpg
Let me give you a very simple answer for this. Use VBA instead of VBS, and write code inside your master excel as per following illustration.
When you click on the cell with the name,
If File.Exists ("YourFolder\" & ActiveCell.Value & ".xlsx") Then
Workbooks.Open("YourFolder\" & ActiveCell.Value & ".xlsx")
Else
WorkBooks.Add(YourTemplate)
Fill in the details already present in the master sheet to new workbook if needed
NewWorkbook.Save("YourFolder\" & ActiveCell.Value & ".xlsx")
End If

Codeigniter + Dwoo

I got problem when implementing my CMS using Codeigniter 1.7.2 and Dwoo. I use Phil Sturgeon Dwoo library. My problem is I want user create template from the admin panel, it means all template will be stored into database including all Dwoo variable and functions.My questions:
Is it possible to load dwoo template from database?
How to parse dwoo variable or function from database? I tried to load content from database which is include dwoo var and function inside it, and i have tried to do evaluation using dwoo eval() function and phil sturgeon string_parse() but still have no luck.
for example:
my controller
$data['header'] = "<h1>{$header}</h1>"; --> this could be loaded from database
$this->parser->parse('header',$data);
my view
{$header}
This is the error message:
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined index: header_title</p>
<p>Filename: compiled/805659ab5e619e094cac7deb9c8cbfb5.d17.php</p>
<p>Line Number: 11</p>
header_title is dwoo variable that loaded from DB.
Thank you,
It is definitely possible to do this, but for performance reasons it would probably be faster to store the templates as files on the filesystem, even if they're edited by users. If you're smart with file naming you can avoid most hits to the database.
Anyway, if you really want to do it with the database, the following should work:
// rendering the header
$template = '<h1>{$header}</h1>'; // loaded from db, don't use double-quotes for examples or $header will be replaced by nothing
$data = array('header' => 'Hello'); // loaded from db as well I assume
$headerOutput = $this->parser->parse_string($template, $data, true); // true makes it return the output
// now rendering the full page (if needed?)
$data = array('header' => $headerOutput);
$this->parser->parse('header', $data); // no 'true', so goes straight to output
The view would then contain {$header} and the output from the header template is passed to that variable.
Now I'm not sure how CI works so it might be better to just output the result of the first template and skip the second one entirely, but I'll leave that up to you.