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).
Related
Ok, so I have a user event script attached to a custom record. One of the fields on this custom record is a select field for item records. In the user event script, it's getting the value of this field, checking the item options on the selected item. As it runs through the values, it checks to see if it's missing certain values and adds them if necessary. The problem I'm having is that it's ultimately setting the item options field to blank. I've tried both with loading the record, setting the values, then saving, and also by trying to just set a single value with nlapiSubmitField(). The outcome is the same both ways. Here's a quick rundown of the code:
var itemId = customRec.getFieldValue("custrec_item_field");
var itemRec = nlapiLoadRecord("noninventoryitem", itemId, { recordmode : "dynamic" });
var optArray = [ "CUSTCOL_OPT1" , "CUSTCOL_OPT2" , "CUSTCOL_OPT3" , "CUSTCOL_OPT4" ];
itemRec.setFieldValues("itemoptions", optArray);
nlapiSubmitRecord(itemRec, true, true);
Now, a few months back I was certain this was working correctly, and if I apply similar login to a user event BeforeSubmit function when the item record saves, everything works as intended. I'm sure I could get this to work by triggering an edit on the item record within a Suitelet called from the original user event, but that seems ridiculous. There are no errors encountered unless I pass in the item option values through in lower case. Am I missing something? Or am I just going to have to find a way to trigger this outside of this user event function?
There was a flaw somewhere else that was clearing the options out because it mistakenly thought the selected value had changed.
When using the .each function with JQuery like below is there anyway to automatically group the results by type to save some time;
$(selector).each(function () {
//do stuff here for each found
});
The above will obviously go through each found element one by one but with the logic within my code I'm just detecting what field type the field is and I would action each field type to do the same thing. I'm just trying to save doing all the logic for the same field type over and over again.
To detail a little more, I have a value and it needs to go into may different fields types. Simple text fields are fine as they're just insert in using .val() but for other default and custom fields that I have such as picklists and multi-select boxes I need to do some logic around the value for these fields so the appropriate values are set, but not all these type fields don't exist so don't want to do the necessary logic beforehand if those fields don't actually exist. So if I had 50 picklist fields I would obviously only want to do that logic once and set the values for all picklist fields to this value(s) that the logic had set. I just thought they're might be a simple method of JQuery that I'm missing here?!
You can do some manual testing and run your code a different way
var all = $(selector),
text = all.filter('[type="text"]'),
select = all.filter('select');
text.val(someValue);
if (select.length){ // select elements exist
// do logic and apply to all
select.val(selectSpecificValue);
}
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
Ok, so I have a kind of weird problem that I need ideas on how to solve.
I have a vb.net web application that points to a sql database. There's a table with a primary key that is an auto-incremented integer.
When a user adds an object to this table, it doesn't currently check to see if the "First Name" and "Last Name" already exist in one of the datarows. The desired addition to the functionality is as follows:
1)When the user submits the form, check the table to see if such a record already exists.
1.1)If the record doesn't exist proceed with the insert.
2)If that record does exist, display a warning to the user that such a record exists
2.1)The warning should have two buttons, "Continue" and "Cancel"
2.1.1)If the user clicks "Continue" go ahead and add the duplicate record
2.1.2)If the user clicks "Cancel" stop the insert.
I'm still relatively new to web development (a little over a year of experience). I am looking for the "correct" way to do this. The aspect of this task that is making it hard for me is that I have to run the query, and then possibly display and alert (javascript probably). I'm not sure how to display an alert in the middle of the server side validation.
Any ideas or comments are appreciated!
Thanks!
If you wouldn't allow insertion of duplicates, you could just create unique index in your database. However, what you can do now is to get the count of records in the database, where firstname and lastname equals to inserted.
In case of normal SQL it would look like
SELECT COUNT(recordID) WHERE firstName = #firstName AND lastName = #lastName;
Or it could look even easier with Entity Framework. Anyway, your question was about "displaying alert in the middle of server side validation". Think about it differently. Think about it as about two checks.
Add another control to your input form, an invisible checkbox near the Submit button. It should contain the expression about user's agreement to insert duplicate record.
Once you detect, that record is duplicate, interrupt the validation, and make checkbox visible, but Submit button - disabled. When user checks the checkbox, Submit button should become visible again.
Now, since you are going through the same validation again, you have to take your checkbox into equation - if it is visible and checked, you don't have to check for record duplication anymore, and just submit the record. If you need to re-use that input form, don't forget to uncheck the checkbox and make it invisible once again.
What you want to do here is add a confirm parameter or something like that to your method, like this:
' This is just pseudocode; I'm guessing you can translate it to
' whatever web framework you're using
Sub InsertRecord(ByVal name() As String, Optional ByVal confirm As Boolean = False)
If DuplicateRecord(name) And Not confirm
' Here's where you would render the page with a confirmation dialog
RenderViewToRequestConfirmation()
Return
End
DoInsertRecord(name)
RenderViewAfterRecordInserted()
End
Then under normal circumstances, from your front end you would submit a request that would call this method without the confirm parameter. In the case of duplicate records, the server would render a response with a dialog requesting confirmation. If the user clicked 'Yes' (or whatever), then the front end would send the same request but this time with the necessary request params to set confirm to True.
In terms of web requests, this process might look like:
| Request Data | Response |
|------------------------------------------|------------------------|
| { "name": "M Webster" } | Page w/ confirm dialog |
| { "name": "M Webster", "confirm": true } | Success page |
The route that I went is a little confusing... even now that I have it working, but i'll explain it here in case it makes sense to someone else who can better explain it later.
I wrote a function in the code behind that calls the function that checks the database for a duplicate record, but I added these two lines of code above the function declaration:
<System.Web.Services.WebMethod()>
<System.Web.Script.Services.ScriptMethod()>
Then, I wrote a JavaScript function that grabs the value from the Textbox and passes the value to that function in the code behind. This is made possible by those two lines above the function declaration in the code behind and by using the PageMethods object. The actual call from the JavaScript would look like this:
PageMethods.FunctionName(parameter, function(returnValueFromOtherFunction){
....function stuff
});
Then I assigned the JavaScript function to the onBlur event in the Textbox.
Thanks for the help guys, but I think this is the best way to solve my problem.
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.