CRM 2011 - JavaScript - Where to set Business Required - javascript

In a form, we want the Reject Reason to be set as Required if the value in the Option Set field Decision is selected as Reject. I wrote a JS function which is then associated with OnChange of field Decision and I set the Reject Reason field to be Required.
if (decisionOptionSetValue == 100000006 && decisionOptionSetText == "Reject") {
Xrm.Page.getAttribute("new_rejectionreason").setRequiredLevel("required");
}
Now, the above worked fine with no issues.
The problem is if I open the same record, I can happily remove the value from the Reject Reason field (new_rejectionreason) and it will not throw an error because, my code fires only when we have a Change of value of the Decision option set which, in this case, has not happened.
Now, where do check to prevent these?
Option 1: Do I have an OnChange on the new_rejectionreason field so that I check if the value has been changed?
Option 2: Do I do the check as part of OnSave before I save the form and prevent the form from saving (?) and set this field as Required
Option 3: Do I do the check as OnLoad and set the field new_rejectionreason as Required
Any other option?

In my opinion the best choice is Option 3. Because you warning user that the field new_rejectionreason is required and don't wait for a save form to warning that. For option 1 you have to force a onchange in new_rejectionreason and this way is not simple to understand later why force the onchange.
Another option that i don't recommend but is another way is doing this verification in plugin and launch a InvalidPluginExecutionException this stops the execution of plugin and send a message to user. This is only for your information don't use this methods for this case.

Why not make that field read only if you would rather not have the user set the value? So when they change the value of the decision field, add the following:
Xrm.Page.ui.controls.get('new_rejectionreason').setDisabled(true);
So now the user cannot edit the value without changing the decision field again.
Edit: I think understand now based on your comment. I think the simplest is adding an extra check on load.
function OnLoad() {
var decisionValue = Xrm.Page.getAttribute('new_decision').getValue();
if (decisionValue !== null) {
Xrm.Page.getAttribute('new_rejectionreason').setRequiredLevel('required');
}
}
So when your page loads, it checks the Decision field. If it finds a value, it knows that the Reject Reason field is required and marks it as such.
All you need to do then is to modify your OnChange handler for Decision to unset the required value if they remove the value.
if (decisionOptionSetValue === 100000006 && decisionOptionSetText === 'Reject') {
Xrm.Page.getAttribute('new_rejectionreason').setRequiredLevel('required');
}
else {
Xrm.Page.getAttribute("new_rejectionreason").setRequiredLevel('none');
}

I would simply prevent saving of the entity under condition that the status is set to rejected but the reason is empty. Somehow, I feel uneasy setting a field as business required or not depending on the value in another field.

Related

D365 CustomJS - Update Field with AutoNumber Field OnSave

I have a Autonumber field called 'ID' that generates an ID for a record. I want to set the Primary Name field called 'ID_Name' to this. I am currently using the following JS:
function setName(executionContext) {
formContext = executionContext.getFormContext();
var name = formContext.getAttribute("id").getValue();
formContext.getAttribute("id_name").setValue(name);
}
Pretty simple. I get the value of 'ID', assign it to a var called name, then set the value of 'ID_Name' to that var. This triggers OnSave.
This works fine when editing a record. The problem is, this does not work when creating a new record. I assume because at the time the OnSave triggers, Autonumber field 'ID' hasn't generated a value which can be used yet, so ID_Name is set to blank. Of course while editing, ID has a value because the record has already been submitted, so no problems. Is there a way around this issue?
Just set the OOB autonumber option on the primary name field of your entity. No code required and it saves you from duplicating data, which should be avoided when possible.
You can do some workaround using the OnLoad event and trigger an update when there is a mismatch between the two fields (meaning the value has not been saved) but I strongly suggest to don't use this kind of approach.
Ideally this can be solved using a synchronous plugin inside a post operation, at this moment in the pipeline the id field should be filled (you didn't mention if you are using the OOB autonumber or something different to generate the content of this field) and you can trigger the update inside a plugin.

Linking mvc razor checkbox to razor textbox

tl;dr I want to save the value of a textbox to the model ONLY IF the checkbox is checked.
First off, I know my code is very messy. I've been trying to improvise my code off of another stack overflow question so it is first and foremost wrong. What I am trying to do is I have these restrictions to an event, some are bool and some are numbers. For example, no smoking is a bool, but minimum age is a number. These are optional though, the user doesn't have to set any. So I want to have a checkbox saying that they want the restriction but to also save the value to the model. Here is what I have so far:
<p>
<input type="checkbox" id="ageLowCapCB"
#(((Model.currentRestrictions.AgeLowCap != null) &&
(Model.currentRestrictions.AgeLowCap != 0)) ? "checked = 'checked'" : "")
/>
Low Age Limit
#Html.TextBoxFor(e => e.currentRestrictions.AgeLowCap, new {id = "ageLowCap"})
</p>
and the script/jquery for this I have is:
$("#ageLowCapCB").click(function () {
var isChecked = $(this).is(":checked");
$("#ageLowCap").val(isChecked ? /*I don't know what to put here*/);
});
The question I pulled this from was using values of "T" or "F" for true and false so it was easy for them to fill in the comment section putting "T" : "F" and that was it. But I need to pull the value of the text box and set it to the value of Model.currentRestrictions.AgeLowCap. Does anyone have any good ideas on what to do in a weird situation like this?
Unfortunately, there is on way of passing your javascript values to c# view model. However there is some workarounds. You can create action which will accept whatever you want to pass from javascript to c# and then when you need to pass that value(s), that can be done by making ajax request to that action and in that action you can persist that value(s). From there you have many options like in database, session and etc.
Question is not very clear to my understanding. What I understand is if Checkbox is checked display textbox which accepts integer value. All these are model fields.
Approach 1: Write a JavaScript function to detect if Checkbox checked attr is true, Display textbox to accept input from user; Write function for textbox to accept only integers. Onkeypress you can call that function.
Approach 2: If you do not have to take integer value from user in textbox, then on post validate if checkbox is checked and assign value to integer textbox if it is true.
-Thanks

Can you make an Ember.TextField wait until change to update its value binding?

I extended an Ember.TextField to include a date picker. A function that observes the text field’s value attempts to parse the string in the text field and update a date property. This is all fine and good when you use the date picker, but if you were to try to type a date into the box, it goes crazy because the value gets updated on every keydown (or keyup or whatever Ember’s default event to update the value bindings for a TextField), and it immediately re-updates the value of the text field with the nicely-formatted date string that came from what it just parsed. Example:
Input says 10/26/2014
You insert your cursor after 2014 and hit backspace
The value has changed, so a handler parses 10/26/201 and updates a date property
The date property has changed, so a handler formats the date as MM/d/yyyy and sets the value
The input now says 10/26/0201
Rather than changing the way those handlers work, all my problems would be solved if I could tell Ember to update the value binding when the input’s change event fires, rather than trying to update everything on every keystroke. I know this can be done in AngularJS and Knockout, but I can’t find anything about it for Ember.
EDIT
I know I can change the way my code works to avoid this specific problem. At this point, I’m more interested for purposes of edification, in a yes-or-no answer that specifically addresses the question that is the title of this post. I’m starting to think the answer is no, but wanted to poll the community.
I wrote a blog post that may offer some solutions about Date Pickers And Validation In Ember with examples here is one of the JSBins from the post.
Write your own extension of text field component and add the change callback.
App.DateTextComponent = Em.TextField.extend({
change: function(event){
var value = this.get('value');
// massage data
value += "foo";
this.set('value', value);
}
});
Example: http://emberjs.jsbin.com/suzami/2/edit
If you really want to get a call when the value changes after the fact, don't observe the value, use actions.
App.DateTextComponent = Em.TextField.extend({
change: function(event){
var value = this.get('value');
this.sendAction('changed', value);
}
});
{{date-text value=foo changed='fooChanged'}}
Example: http://emberjs.jsbin.com/suzami/3/edit?html,js,output

AngularJS: How to set one input value from another and have it go through validation as if it was user entered?

I'm using angular 1.3.0rc2, and I'm trying to have an input field, on blur, set another input field as if it was user entered.
If there exists only a synchronous validator on the input I'm trying to set, and no debounce or async validators, things always seem to work as expected when I do something like:
myForm.username.$setViewValue('some value');
myForm.username.$render();
However, things don't seem to work as expected when either an async validator or debounce exists on the input I'm trying to set, and when the input I'm trying to set is in a currently invalid state.
I've created the following plunkr to demonstrate my woes. Try setting the value of "Full Name" and see what happens with the Username field, which I want to also be set on blur of the Full Name field. When the Username field is in an invalid state, changing the value of Full Name and then removing focus from the field does not update Username as I would expect.
http://plnkr.co/edit/h1hvf79W8ovqAlNLpBvS
So, my question is, how can I set one input field from another in such a way that it will work reliably and act as if the user themselves has entered this new input (thus running through validators and updating the model value accordingly)?
Give this a try, it should adjust the username when you blur the full name.
Plunkr
ngModel
HTML
Full Name:
<input name="fullName" ng-model="fullName" test-validator change-field="username" />
User Name:
<input name="username" ng-model="username" required />
JS
angular.module("testApp",[]).controller("testCtrl", function($scope) {
}).directive('testValidator', ['$sce', function ($sce) {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
if(!ngModel) return;
element.on('blur', function () {
scope.$apply(read);
});
function read() {
if(attrs.changeField) {
var field = attrs.changeField;
scope.myForm[field].$setViewValue(element.val());
scope.myForm[field].$render();
}
}
}
}
}])
OK, So the basic problem we want to solve here is that having a user set an input that turns out to be invalid leads to the underlying model value being set to undefined, whereas programatically setting the input to an invalid state does not.
This was inconsistent, and so I was trying to find a way to circumvent that. It turns out that the resolution isn't as straightforward as hoped (see https://github.com/angular/angular.js/issues/9295)
However, the reverse solution was proposed instead, which involves using ngModelOptions on the enclosing form (or per input but thats more hassle) with "allowInvalid" set to true. This means that invalid values will still be set to the model, rather than the model value being cleared in that case.
Given that the model is always set now regardless of validity, I can revert to a simpler means of programatically setting one field form another - simply setting the underlying model value, and it behaves identically to if a user set the value themselves :)
plunkr demonstration with an async validator on the second input again:
http://plnkr.co/edit/lkDN4qLbbkN79EmRrxsY?p=preview
see how the model ends up the same regardless of whether the second input value is set by hand or set form the first input, irrespective of validity and the sue of async validator, as desired :)

Radio button validations

I have a series of various fields on a Dynamics CRM 2011 form. I'm using javascript to carry out various checks. One of these is setting particular fields to "required" to prevent the user saving the form until the field is assigned a value. (Making them mandatory)
Xrm.Page.data.entity.attributes.get("new_FieldA1").setRequiredLevel("required");
However, some of my fields are radio buttons. The above code doesn't seem to work correctly for these. I think a Yes/No selection of "No" is seen as null anyway. Which means if "No" is selected, I still get a message "You must provide a value for FieldA1".
Can anyone suggest a work around so "No" is allowed?
Thanks.
To check mandatory fields, (if particular fields are completed on the form) the user selects a radio button as the last option at the bottom of the form ("Mark this form as complete?") When Yes is selected, the following function carries out some basic checks:
function FormSaveAlert()
{
if (Xrm.Page.getAttribute("new_formcompleted").getValue() == true)
{
if (confirm("Are you sure this form is complete? \n Once saved, this form cannot be modified again.") == false)
{
Xrm.Page.getAttribute("new_formcompleted").setValue(false);
}
else
{
var HF1 = Xrm.Page.getAttribute("new_hf1field");
HF1.setRequiredLevel("required");
if (HF1.getValue()==null) {HF1.setValue(false);}
//Xrm.Page.data.entity.attributes.get("otherfield").setRequiredLevel("required");
}
}
}
If the form is marked as complete, and a certain field is required but contains null, a message appears preventing a save. Default message in Dynamics - "You must provide a value for HF1"
I did a test and I can replicate the issue, if I set a two options to null and after I select No, getValue function returns null instead of false.
(I used only Google Chrome, but because is a supported customization it must works for all browsers)
If inside your requirements is possible (shows No as default value), I suggest to enforce the default value by code as this example:
var fieldA1 = Xrm.Page.getAttribute("new_FieldA1");
fieldA1.setRequiredLevel("required");
if (fieldA1.getValue()==null) { fieldA1.setValue(false); }
A required field must have a value, but a bit field always has a value, so I would actually expect this to be seen as containing a value even when it appears not to.
Can you post the onChange code for x_formcompleted too, since that is what is triggering the error?
You have two fields here, and I can't quite see the logic of how they interact.
Surely you need only one, which if ticked asks them to confirm and if they change their mind it gets reset.
Also consider using an option set with values yes / no / null (there is a built-in global option set for this). Make Null ("unassigned") the default, and make the field required (not by script, just always in the field properties).

Categories