apex always execute validation - oracle

Is it possible to execute validations on page load regardless if it is submitted or just loaded?
I need to implement it for ordinary validations created in processing page section and for min max validations assigned to number field.
Is it possible to implement?

Indeed: having a server side validation will throw an error, but the page has submitted and thus the changed values are in session state. You could try to prevent this by having a plsql validation which would blank out the session state value when an error occurs, but might not be optimal. I think that some javascript could alliviate some of the trouble.
Here is some javascript that restricts the selectable ranges in the to and from datepickers. It won't allow a user to pick a larger from than to date, and vice versa. It also sets the item to readonly, so that the user has to select through the datepicker and can not alter it by hand.
Page > Javascript > Function and Global Variable Declaration
function f_check_date(){
var lFrom = $("#P6_DATE_FROM").datepicker("getDate"),
lTo = $("#P6_DATE_TO").datepicker("getDate");
if(lFrom > lTo || lTo < lFrom){
//in case it does happen
$("#P6_DATE_FROM").val('');
$("#P6_DATE_FROM").val('');
alert('Please select a valid date range.');
} else {
//when a date changes, the other datepicker has to be altered so the
//range is adjusted
$("#P6_DATE_FROM").datepicker("option","maxDate",lTo);
$("#P6_DATE_TO").datepicker("option","minDate",lFrom);
};
};
Dynamic Action, Page Load, Execute javascript
//on load, set the datepicker range in case a date is already present
//when the date changes, call the datecheck function
//and set item to readonly
$("#P6_DATE_FROM")
.datepicker("option","maxDate",$("#P6_DATE_TO").datepicker("getDate"))
.change(f_check_date)
.prop("readonly",true);
$("#P6_DATE_TO")
.datepicker("option","minDate",$("#P6_DATE_FROM").datepicker("getDate"))
.change(f_check_date)
.prop("readonly",true);

Related

D365 - UCI - A validation error occurred. The value 895390001 of 'MULTISELECT' on record of type ENTITY' is outside the valid range. Accepted Values:

I am trying to use the Multiselect option set and want to build it dynamically, the addOption() is populating the multiselect field correctly, but on save of record it is prompting the validation error.
On change of contact lookup, I am populating the abc_multiselect field. It is populating fine dynamically then user selects the required options from multiselect field, but on save of record (Ribbon Save button not custom save event of form) the CRM is not accepting the values.
MSCRM Version
Server version: 9.2.22081.00182
Client version: 1.4.4647-2208.1
function polulate(executionContext){
var formContext = executionContext.getFormContext();
var multiselect = formContext.getControl("abc_multiselect");
var high = {value : 895390001, text : "High"};
multiselect.addOption(high);
}
The error is;
On Popup
One or more of the option values for this picklist are not in the range of allowed values.
Details
Exception Message: A validation error occurred. The value 895390001 of 'abc_multiselect' on record of type 'abc_ENTITY' is outside the valid range. Accepted Values:
ErrorCode: -2147204326
HexErrorCode: 0x8004431a
ErrorDetails:
ApiExceptionSourceKey: Plugin/Microsoft.Crm.ObjectModel.TargetAttributeValidationPlugin
ApiStepKey: fc743e7d-fbea-4695-bdb9-7d78334c8474
ApiDepthKey: 1
ApiActivityIdKey: 3907c6d7-ef4a-437e-946f-55e0f956fc3e
ApiPluginSolutionNameKey: System
ApiStepSolutionNameKey: System
ApiExceptionCategory: ClientError
ApiExceptionMessageName: PicklistValueOutOfRange
ApiExceptionHttpStatusCode: 400
HelpLink: http://go.microsoft.com/fwlink/?LinkID=398563&error=Microsoft.Crm.CrmException%3a8004431a&client=platform
TraceText:
[Microsoft.Crm.ObjectModel: Microsoft.Crm.ObjectModel.TargetAttributeValidationPlugin]
[fc743e7d-fbea-4695-bdb9-7d78334c8474: TargetAttributeValidationPlugin]
Activity Id: 28d5f67f-bf24-4eca-9124-cf95cf06dc30
I also tried to make all option set values hard coded (Added during the multiselect field creation), it worked smoothly. No issue ! But on dynamically population; on save, the CRM is not accepting the values.
I have tried this , this, this and this but all in vain.
Any one can guide, what is missing?
Update 1
function polulate(executionContext){
var formContext = executionContext.getFormContext();
var multiselect = formContext.getControl("abc_multiselect");
multiselect.clearOptions();
var high = {value : 895390001, text : "High"};
multiselect.addOption(high);
}
I also checked by changing the value from 895390001 to 895390000 and even to 100 and 101 but still same issue.
https://stackoverflow.com/a/48011975/5436880
This should solve your issue? most probably option set does not have 895390001 or it is already selected. you could also try to clear all option sets and then add
clear options
For using addOption those options need to be there in metadata first. You cannot add an option that is not present in metadata. Example can be Suppose you have Option A, 1 and 3 in Metadata. now you want to add another option 4 using Javascript "addOption", it is not possible.
In your case, get a maximum possible set or options in the optionset now onload of form or Onchange of field "removeOption " the options that are not required.

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.

Update picklist value to null with Sdk.Sync.Update does nothing

Is it possible to update a record's attribute of picklist type with null by using Sdk.Sync.Update? It's not working for me.
Here's what I do:
var detailsObj = updatedDetailsObj; // I get updatedDetailsObj from previous logic, not shown here
var operation = new Sdk.Entity("kcl_operation");
operation.setId(operationId, false); // I have operationId from previous logic, not shown here
operation.addAttribute(new Sdk.String("op_updatedAccount", detailsObj.UpdatedAccount)); // works, get updated
operation.addAttribute(new Sdk.OptionSet("op_updatedExplanation", null)); // doesn't get updated
Sdk.Sync.update(operation);
After the completion of Sdk.Sync.update, the string field get updated, but the picklist field is left with its previous value, instead of null.
I also took a look inside the XML being sent inside Sdk.Sync.update, and indeed, it lacks the pair of "op_updatedExplanation" and null.
How can make it work?
Added:
I'm not doing it inside a form but inside a grid page, so that the user checks several records and I need to make the update on all of them.
standard CRM SDK code (assuming entity name and field name):
Entity operation = new Entity("kcl_operation");
operation.Id = operationId;
operation["op_updatedexplanation"] = null;
service.Update(operation);
where service is an IOrganizationService instance
Please use this snippet to set value as null.
Xrm.Page.getAttribute("op_updatedexplanation").setValue(null);
This will just set the value in the form. You may have to save the form to see the value getting stored in database.
Xrm.Page.data.entity.save();
If the control is disabled - you have to set the submitmode attribute also.
Xrm.Page.getAttribute("op_updatedexplanation").setSubmitMode("always");

jqgrid inline saving with clientArray throws error

I am new to jqGrid and have created a simple grid with local data with editurl set to clientArray. I am using inline navigation. I can edit a row and when I press the save button, the rows gets update. So far so good.
When I press on add row button, a new empty is row is inserted. When I type in there some data and click on the save button, I get the error message:
Uncaught TypeError: Cannot read property 'extraparam' of undefined jquery.jqGrid.min.js:398
The documentation only tells how the saveRow method should be called. But, apparently the inline navigator is calling it automatically. Which is perfect. But I guess I still need to set some parameters correctly so that it does not throw the error and saves the newly added row.
Hope some jqGrid guru has a good tip. Thanks.
function createTable(data,colNames,colModel,caption ){
...
$(table).jqGrid({ data:data,
datatype: "local",
height: 'auto',
colNames:colNames,
pager:'#'+pagerid,
colModel:colModel,
viewrecords: true,
caption:caption,
editurl:'clientArray',
});
var nav = $(table).jqGrid('navGrid','#'+pagerid,{edit:false,add:false,del:false});
$(table).jqGrid('inlineNav','#'+pagerid);
$(table).jqGrid('gridResize',{minWidth:350,maxWidth:800,minHeight:80, maxHeight:350});
$('#gbox_'+tableid).draggable();
}
You are right, It's a bug in inlineNav method. The lines
if(!o.addParams.addRowParams.extraparam) {
o.addParams.addRowParams.extraparam = {};
}
uses o.addParams.addRowParams.extraparam, but default value of parameter of addParams (see here) defined as addParams : {} and not as addParams : {addRowParams: {}}. So the expression o.addParams.addRowParams is equal undefined and o.addParams.addRowParams.extraparam is the same as undefined.extraparam which produce null reference exception.
I posted the corresponding bug report to trirand and the problem will be fixed in the next version of jqGrid.
As a workaround you can replace the line
$(table).jqGrid('inlineNav','#'+pagerid);
with the line
$(table).jqGrid('inlineNav','#'+pagerid, {addParams: {addRowParams: {}}});
Some common additional remarks to your code:
I strictly recommend that you always use gridview: true option which will improve performance of your code without any disadvantages
I recommend you to use autoencode: true option per default. Per default jqGrid interpret input data of the grid as HTML fragments which must be well formatted. So if you would try to display the data like a < b you can have problems because < is special character in HTML. If you would use autoencode: true option the input data will be interpreted as text instead of HTML fragments.
I recommend you remove index property from your model if you assign always the same value for index and name properties.
I recommend you to provide id property with unique values for every item of the input data. You should understand that jqGrid always assign id attribute for every row of grid. The value must be unique over all HTML elements on the page. If you get the data from the server and the data have native unique id from the database it's recommended to use the value as the value of id property. If you don't specify any id property jqGrid assign values 1, 2, 3, ... as the id values of rows (rowids). If you use more as one jqGrids on the page and don't provide unique id values you will have id duplicates which is HTML error.
I recommend you to use idPrefix option of jqGrid. If you have two grids on the page and you don't fill (and don't need) any id for data items then you have have id duplicates (id="1", id="2" etc in both grids). If you would define idPrefix: "g1_" for one grid and idPrefix: "g2_" option for another grid then the rowids of the first grid will be id="g1_1", id="g1_2" etc in the first grid and id="g2_1", id="g2_2" in the second grid. Even if you fill the id from the server then you provide unique id inside one table, but the ids from two tables of database can have the same id. So the usage of different idPrefix option for every grid will solve the problem of id duplicates in very simple way.
I'm having this same issue but my jqgrid markup is completely different (maybe newer version?)
I can use inline to edit and save a row, but adding a row will not save. I am not sure what the issue is.
<?php
ini_set("display_errors","1");
require_once 'jq-config.php';
// include the jqGrid Class
require_once ABSPATH."php/jqAutocomplete.php";
require_once ABSPATH."php/jqCalendar.php";
require_once ABSPATH."php/jqGrid.php";
// include the driver class
require_once ABSPATH."php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = 'SELECT Serial, Type, Customer, Date, Notes FROM rmas';
$resize = <<<RESIZE
jQuery(window).resize(function(){
gridId = "grid";
gridParentWidth = $('#gbox_' + gridId).parent().width();
$('#' + gridId).jqGrid('setGridWidth',gridParentWidth);
})
RESIZE;
$grid->setJSCode( $resize);
// set the ouput format to json
$grid->dataType = 'json';
$grid->table ="rmas";
$grid->setPrimaryKeyId("Serial");
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('rmaform.php');
$grid->cacheCount = true;
//$grid->toolbarfilter = true;
$grid->setGridOptions(array(
"caption"=>"RMAs",
"rowNum"=>50,
"sortname"=>"Serial",
"hoverrows"=>true,
"rowList"=>array(50,100,200),
"height"=>600,
"autowidth"=>true,
"shrinkToFit"=>false
));
$grid->callGridMethod('#grid', 'bindKeys');
// Change some property of the field(s)
$grid->setColProperty("Serial", array("align"=>"center","width"=>40));
$grid->setColProperty("Type", array("align"=>"center","width"=>40));
$grid->setColProperty("Customer", array("align"=>"center","width"=>65));
$grid->setColProperty("Date", array("align"=>"center","width"=>40));
$grid->setColProperty("Notes", array("align"=>"left","width"=>500));
// navigator first should be enabled
$grid->navigator = true;
$grid->setNavOptions('navigator', array("add"=>false,"edit"=>false,"excel"=>true));
// and just enable the inline
$grid->inlineNav = true;
$buttonoptions = array("#pager", array(
"caption"=>"Enable Cells",
"onClickButton"=>"js:function(){ jQuery('#grid').jqGrid('setGridParam',{cellEdit: true});}", "title"=> "Enable Excel like editing"
)
);
$grid->callGridMethod("#grid", "navButtonAdd", $buttonoptions);
$buttonoptions = array("#pager", array(
"caption"=>"Disable Cells",
"onClickButton"=>"js:function(){ jQuery('#grid').jqGrid('setGridParam',{cellEdit: false});}" , "title"=> "Disable Excel like editing"
)
);
$grid->callGridMethod("#grid", "navButtonAdd", $buttonoptions);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>

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.

Resources