Oracle APEX - I need help to setup dynamic search filter on IG report - oracle

I have an IG region where I disabled the toolbar and created my custom search item.
I want user to be able to type the first three characters of a name on the search item (named P8_SEARCH) and the IG report will only show the name(s) that starts with those 3 characters.
This should happen without clicking any button. The IG report query is shown below:
select member_id, first_name, last_name , address, dob, home_phone, cell_phone,
email_address from member_profile where first_name like '%'||:P8_SEARCH||'%';
I also created dynamic action with key release event and True action Execute JavaScript Code shown below:
var keyPressCount=0;
$("#P8_SEARCH").on("keypress", () => {
if (keyPressCount < 2) {
keyPressCount++;
} else {
$s("P8_SEARCH", apex.item( "P8_SEARCH" ).getValue());
}
})
How can I achieve this without submitting the page? I will appreciate any suggestion. Example:

Set an static_id for your IG region, in the dynamic action add apex.region("yourStaticId").refresh();to your JS code, this will refresh only the region.
something like this:
var keyPressCount=0;
$("#P8_SEARCH").on("keypress", () => {
if (keyPressCount < 2) {
keyPressCount++;
} else {
$s("P8_SEARCH", apex.item( "P8_SEARCH" ).getValue());
apex.region("yourStaticId").refresh();
}
})

If the search items are stored in an associated table, my idea is that you could associate a PL/SQL expression to execute using a Process. This process could be executed on a custom action.
Another idea is that you associate the dynamic action with a hidden button press, and make the JavaScript code click on the button. Then, you can 'simulate' the existence of a trigger for your dynamic action with key release event
What do you think?

Related

How to get selected records under bulk edit functionality

I am working on 2016 on-premise MSCRM, I need to check each record in bulk edit and alert the user if something is wrong, I tried to alert it from my update plugin but only general msg appeared, now I'm trying to get all records selected in bulk edit, I googled and found this code :
var formType = Xrm.Page.ui.getFormType();
if (formType == 6)
{
//Read ids from dialog arguments
var records = window.dialogArguments;
}
}
To use the bulk edit formtype I need to add to event onload or onchange on customizations.xml the attribute : BehaviorInBulkEditForm=“Enabled“ (unfortunately not so safe to edit this file) .
My questions:
which selected rows I'll get in onload and onchange event? ,I'm not sure where to use it in that case and if I'll get all the data I need.
Is there a better way/easy to get the data I need or to get the formtype - bulk edit.
Soon I'll be using MSCRM 365 is there any easier solution to this case in the 9.0 version ?
You can use method window.getDialogArguments(); to get ids.
Here is my example:
I added an onLoad event for my form and enabled the BehaviorInBulkEditForm.
function onLoad(formContext) {
var ids = window.getDialogArguments();
console.log(ids);
}
The ids is an array, every element is a selected record id.
['{335A56B7-C717-ED11-B83F-00224856D931}', '{CBBDEBFB-C717-ED11-B83F-00224856D931}', '{3607EFC7-C717-ED11-B83F-00224856D931}', '{325A56B7-C717-ED11-B83F-00224856D931}']

Oracle APEX - how to show an item on page load based on the value of another item

I have an item on the page which I want to show/hide on page load based on the value of another item. If item2 is Yes, then show item1, or if item2 is No, then hide item1.
I know how to do that using dynamic action and javascript but I want to avoid using javascript. Is there a way to use APEX built-in functionality to do that? I know I can use Show action to hide an item, but I only need to show it if item2 is Yes. The APEX Show action does not have a condition
Also have the same issue with On Change event:
var result = document.getElementById("result");
var status = document.getElementById("status");
if (status.options[status.selectedIndex].text == "Completed") {
var r = confirm("Are you sure you want to set the status to Completed?");
if (r == true) {
apex.submit({request:'STATUS_CHANGE'})
}
} else {
result.value = "";
$x("P2_THE_DATE").value = "";
apex.submit({request:'STATUS_CHANGE'})
}
//set a value of a hidden field for status
apex.item("P2_STATUS").setValue(status.options[status.selectedIndex].text);
Is there a better, more efficient way to do this?
ITEM2 must get its value on load somehow, right? So, use the same code (that populates ITEM2) as a condition for ITEM1 and check whether its value is "Yes" (and display it) or "No" (so don't).
I prefer using a function that returns a Boolean to do so; something like
declare
l_item2 varcahr2(10);
begin
-- this is supposed to look like source for ITEM2
select ...
into l_item2
from ...
where ...;
return l_item2 = 'Yes';
end;
Isn't that a perfect use case to incorporate js - to have a dynamic behavior on a web page. Why would you want to avoid it? I'm just curious.
Anyway, you could however achieve similar behavior, provided the item2 is a Select List or Radio Group.
Set the 'Page Action on Selection' to Submit
Set the source used to 'Only when current values is NULL' - so the value gets stored in the session even after submitting the page.
Have the conditional display for item1 set as "ITEM is NOT NULL" and choose ITEM2 as the item.
If you follow these steps, the ITEM1 would show up after the selection of ITEM2.

How can I create oracle apex server side live validation without need to submit page

I created form for customers, I need to do validate customer name like
1 - type the new name into item P1_CUST_NAME.
2 - after leaving this item go to database and check if this name already exist or not.
3 - display alert or message for the client.
4 - prevent the client from navigating a way from this item until he enter valid data.
Yes, you can create server side validation by using Dynamic Action and JavaScript function apex.server.process.
A basic example to demonstrate-
Create a page item e.g. P4_NAME in your page
Create a page process and select the execution point as "AJAX
CALLBACK".
In below code I am checking the P4_ITEM value, you can write your own logic to validate.
BEGIN
IF :P4_NAME = 'HIMANSHU'
THEN
HTP.prn ('SUCCESS');
ELSE
HTP.prn ('ERROR');
END IF;
END;
Now create a new dynamic action and select the Event as "LOSE FOCUS", Selection Type as "Item(s)" and in Item(s) select the item name.
Create a true action and select "execute JavaScript Code".
In code section, implement apex.server.process like below-
apex.server.process('validate_name',
{
pageItems : '#P4_NAME'
}
,
{
dataType : 'text', success : function(data)
{
if(data != 'SUCCESS')alert(data);
}
}
)
The first argument is the page process name(validate_name) which we have create earlier, second the data you want to submit to the process and third is options.
For more details on apex.server.process
It is done. Refresh your page and check. On validation failure you will get an alert.
You can customize your JS code further to display error messages in more fancy way instead of showing alert.

jqgrid: how send and receive row data keeping edit mode

jqGrid has employee name and employee id columns.
If employee name has changed, server validate method should called to validate name. Current row columns should be updated from data returned by this method.
If employee id has changed, server validate method should called to validate id.
Current row columns should be updated from data returned by this method.
Preferably jqGrid should stay in edit mode so that user has possibility to continue changing, accept or reject changes.
How to implement this in inline and form editing?
I'm thinking about following possibilites:
Possibility 1.
Use editrules with custom validator like
editrules = new
{
custom = true,
custom_func = function(value, colname) { ??? }
},
Issues: How to get data from all columns, make sync or async call and update columns with this call results.
Possibility 2.
Require user to press Enter key to save row.
Issues: how to find which column was changed and pass this column number to server.
How to update current row data from server response.
Possibility 3.
using blur as described in Oleg great answer in
jqgrid change cell value and stay in edit mode
Issues: blur does not fire if data is entered and enter is pressed immediately. How to apply blur in this case ?
In summary server sice calculation/validation should be dones as follows:
If column in changed and focus moved out or enter is pressed in changed column to save, server side sync or if not possible then async method should be called. Changed column name and current edited row values like in edit method are passed as parameters to this method.
This method returns new values for edited row. current edited row values should be replaced with values returned by that method.
Update
Oleg answer assumes that primary key is modified. This factor is not important. Here is new version of question without primary keys and other updates:
jqGrid has product barcode and product name columns.
If product name has changed, server validate method should called to validate name. Current row columns should be updated from data returned by this method.
If product barcode has changed, server validate method should called to validate product barcode.
Current row columns should be updated from data returned by this method.
jqGrid should stay in edit mode so that user has possibility to continue changing, accept or reject changes.
How to implement this in inline and form editing?
I'm thinking about following possibilites:
Possibility 1.
Use editrules with custom validator like
editrules = new
{
custom = true,
custom_func = function(value, colname) { ??? }
},
Issue: custom_func does not fire if input element loses focus. It is called before save for all elements. So it cannot used.
Possibility 2.
Require user to press Enter key to save row.
Issues: how to find which column was changed and pass this column number to server.
Save method should known column (name or barcode change order) and fill different columns. This looks not reasonable.
Possibility 3.
using blur:
colModel: [{"label":"ProductCode","name":"ProductCode","editoptions":{
"dataEvents":[
{"type":"focus","fn":function(e) { ischanged=false}},
{"type":"change","fn":function(e) {ischanged=true}},
{"type":"keydown","fn":function(e) {ischanged=true }},
{"type":"blur","fn":function(e) { if(ischanged) validate(e)} }
]},
To implement validate I found code from Oleg great answer in
jqgrid change cell value and stay in edit mode
Summary of requirement:
If column in changed and focus moved out or enter is pressed in changed column to save, server side sync or if not possible then async method should be called. Changed column name and current edited row values like in edit method are passed as parameters to this method.
This method returns new values for edited row. current edited row values should be replaced with values returned by that method.
Update2
This question is not about concurrency. This is single user and jqGrid issue. Updating means that single user changes product name or barcode and server shoudl provide additonal data (product id and/or name/barcode) is responce of this.
Update 4
I tried code below.
If user enters new code and presses Enter without moving to other row, blur does not occur and validation is not called.
How to dedect in jqGrid save method if cell is dirty or other idea how to force this code to run if enter is pressed to end edit without losing focus from changed foreign key cell ?
function validate(elem, column) {
ischanged = false;
var i, form, row;
var postData = { _column: column };
var colModel = $("#grid").jqGrid('getGridParam', 'colModel');
var formEdit = $(elem).is('.FormElement');
// todo: use jQuery serialize() ???
if (formEdit) {
form = $(elem).closest('form.FormGrid');
postData._rowid = $("#grid").jqGrid('getGridParam', 'selrow');
for (i = 0; i < colModel.length; i++)
eval('postData.' + colModel[i].name + '="' + $('#' + colModel[i].name + '.FormElement', form[0]).val() + '";');
}
else {
row = $(elem).closest('tr.jqgrow');
postData._rowid = row.attr('id');
for (i = 1; i < colModel.length; i++)
eval('postData.' + colModel[i].name + '="' + $('#' + postData._rowid + '_' + colModel[i].name).val() + '";');
}
$.ajax('Grid/Validate', {
data: postData,
async: false,
type: 'POST',
success: function (data, textStatus, jqXHR) {
for (i = 0; i < data.length; i++) {
if (formEdit)
$('#' + data[i].name + '.FormElement', form[0]).val(data[i].value);
else
$('#' + postData._rowid + '_' + data[i].name).val(data[i].value);
}
}
});
}
colModel is defined as:
{"name":"ProductBarCode",
"editoptions": {"dataEvents":
[{"type":"focus","fn":function(e) {ischanged=false}
},
{"type":"change","fn":function(e) {ischanged=true},
{"type":"keydown","fn":function(e) {if(realchangekey()) ischanged=true}
},{"type":"blur","fn":function(e) { if(ischanged) { validate( e.target,ProductBarCode')}}
}]},"editable":true}
It's one from the problems which is much easier to avoid as to eliminate. I have to remind you about my advises (in the comments to the answer) to use immutable primary key, so that is, will be never changed. The record of the database table can be destroyed, but no new record should have the id of ever deleted record.
On any concurrency control implementation it is important that the server will be first able to detect the concurrency problem. It can be that two (or more) users of your web application read the same information like the information about the employee. The information can be displayed in jqGrids for example. If you allow to change the employee id, than the first problem would be to detect concurrency error. Let us one user will change the employee id and another user will try to modify the same employee based on the previous loaded information. After the user submit the midification, the server application will just receive the "edit" request but will not find the corresponding record in the database. The server will have to sent error response without any detail. So the errorfunc of the editRow or the event handler errorTextFormat of the editGridRow should trigger "reloadGrid" reload the whole grid contain.
If you allow to edit the primary key, then I can imagine more dangerous situation as described before. It can be that another user not only change the id of the current editing row to another value, but one could change the id of one more record so, that its new id will be the same as the current editing id. In the case the request to save the row will overwrite another record.
To prevent such problems and to simplify the optimistic concurrency control one can add an additional column which represent any form of the timestamp in every table of the database which could be modified. I personally use Microsoft SQL Server and add I used to add the non-nullable column of the type rowversion (the same as the type timestamp in the previous version of the SQL Server). The value of the rowversion will be send to the jqGrid together with the data. The modification request which will be send to the server will contain the rowversion. If any data will be save in the database the corresponding value in the corresponding rowversion column will be automatically modified by the SQL database. In the way the server can very easy detect concurrency errors with the following code
CREATE PROCEDURE dbo.spEmployeesUpdate
-- #originalRowUpdateTimeStamp used for optimistic concurrency mechanism
-- it is the value which correspond the data used by the user as the source
#Id int,
#EmployeeName varchar(100),
#originalRowUpdateTimeStamp rowversion,
#NewRowUpdateTimeStamp rowversion OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
-- ExecuteNonQuery() returns -1, but it is not an error
-- one should test #NewRowUpdateTimeStamp for DBNull
SET NOCOUNT ON;
UPDATE dbo.Employees
SET Name = #EmployeeName
WHERE Id=#Id AND RowUpdateTimeStamp=#originalRowUpdateTimeStamp;
-- get the new value of the RowUpdateTimeStamp (rowversion)
-- if the previous update took place
SET #NewRowUpdateTimeStamp = (SELECT RowUpdateTimeStamp
FROM dbo.Employees
WHERE ##ROWCOUNT > 0 AND Id=#Id)
END
You can verify in the code of the server application that the output parameter #NewRowUpdateTimeStamp will be set by the stored procedure dbo.spEmployeesUpdate. If it's not set the server application can throw DBConcurrencyException exception.
So in my opinion you should make modifications in the database and the servers application code to implement optimistic concurrency control. After that the server code should return response with HTTP error code in case of concurrency error. The errorfunc of the editRow or the event handler errorTextFormat of the editGridRow should reload the new values of the currently modified row. You can use either the more complex way or just reload the grid and continue the modification of the current row. In case of unchanged rowid you can easy find the new loaded row and to start it's editing after the grid reloading.
In the existing database you can use
ALTER TABLE dbo.Employees ADD NewId int IDENTITY NOT NULL
ALTER TABLE dbo.Employees ADD RowUpdateTimeStamp rowversion NOT NULL
ALTER TABLE dbo.Employees ADD CONSTRAINT UC_Employees_NewId UNIQUE NONCLUSTERED (NewId)
GO
Then you can use NewId instead of the id in the jqGrid or in any other place which you need. The NewId can coexist with your current primary key till you update other parts of your application to use more effective NewId.
UPDATED: I don't think that one really need to implement any complex error correction for the concurrency error. In the projects at my customers the data which are need be edited can not contain any long texts. So the simple message, which describe the reason why the current modifications could not be saved, is enough. The user can manually reload the full grid and verify the current contain of the row which he edited. One should not forget that any complex procedures can bring additional errors in the project, the implementation is complex, it extend the development budget and mostly the additional investment could never paid off.
If you do need implement automated refresh of the editing row I would never implement the cell validation in "on blur" event for example. Instead of that one can verify inside of errorfunc of the editRow or inside of the errorTextFormat event handler of the editGridRow that the server returns the concurrency error. In case of the concurrency error one can save the id of the current editing row in a variable which could be accessed inside of the loadComplete event handle. Then, after displaying of the error message, one can just reload the grid with respect of $('#list').trigger('reloadGrid',[{current:true}]) (see here). Inside of loadComplete event handle one can verify whether the variable of the aborted editing row is set. In the case one can call editRow or editGridRow and continue the editing of the string. I think that when the current row are changed another rows of the page could be also be changed. So reloading of the current page is better as reloading of the data only one current cell or one row of the grid.

Dynamic bind in Lift framework

I am newbie to Lift and I have a question on using bind, Ajax in Lift.
I want to create three dropdown menus using Ajax in a dynamic fashion. I use "Address" as an example to describe what I am trying to achieve. At fist, I only have to display "Country" menu with default set to "None". The user at this point can choose to submit if she wishes to and the address is taken as default. If not, she can provide the precise address. Once she selects the country, the "State" menu should get displayed, and once she selects "State", the "County" menu should be displayed.
With the help of lift demo examples, I tried to create static menus as follow. I created three snippets <select:country/>, <select:state/>, <select:county/> in my .html file and in the scala code, I bind as follows:
bind("select", xhtml,
"system" -> select(Address.countries.map(s => (s,s)),
Full(country), s => country = s, "onchange" -> ajaxCall(JE.JsRaw("this.value"),s => After(200, replaceCounty(s))).toJsCmd),
"state" -> stateChoice(country) % ("id" -> "state_select"),
"county" -> countyChoice(state) % ("id" -> "county_select"),
"submit" -> submit(?("Go!"),()=>Log.info("Country: "+country+" State: "+state + " County: "+ county)
The corresponding replaceCounty, stateChoice, countyChoice are all defined in my class. However, when the country is selected, only the state is refreshed through Ajax call and not the county.
Q1) Is there a way to refresh both the menus based on the country menu?
Q2) How to create the menu's dynamically as I explained earlier?
There is an excellent example code that does just this available at:
http://demo.liftweb.net/ajax-form
If you want to update multiple dropdowns as a result of an AJAX update, you'll want to return something like:
ReplaceOptions(...) & ReplaceOptions(...)
Use SHtml.ajaxSelect for your first select, and static elements for the other two. When the first select changes, you'll return javascript to populate the next select with the result of another SHtml.ajaxSelect call.
def countrySelect : NodeSeq = {
val countryOptions = List(("",""),("AR","AR"))
SHtml.ajaxSelect(countryOptions, Empty, { selectedCountry =>
val stateOptions = buildStateOptions(selectedCountry)
SetHtml("state-select", SHtml.ajaxSelect(stateOptions, Empty, { selectedState =>
// setup the county options here.
}))
})
}
bind(namespace, in,
"country" -> countrySelect,
"state" -> <select id="state-select"/>,
"county" -> <select id="county-select"/>)
In the callbacks for #ajaxSelect you'll probably want to save the values of whatever has been selected, but this is the general approach I'd take.

Resources