Dynamics CRM forms: jScript for a dummy - javascript

Breaking my head against more compex problems, I try to get back to basics.
I want to have a jScript in a form, that upon user change in control Sub-Fund, will pop up a message showing the new value of that control.
Here is my code -- which returns an error, of course 8-(((
function TestForDummy()
{
var noind = crmForm.all.new_subfundid.DataValue;
alert(noind);
}
Whenever I update Sub-Fund, it gives me an error
Field:new_subfundid, Event:onchange, Error:Object expected
What'wrong ?

Try this :
function TestForDummy()
{
var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();
var noind = lookupValue[0].id;
alert(noind);
}

Related

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

Google Tag Manager DataLayer not allways Pushing

I have a Tag in tag manager that feeds me back the data of fields that have been showing as invalid when a user tries to submit a form but its missing or has invalid fields.
This is done using the following code:
// Get user Agent
var Uagent = navigator.userAgent;
// Validation Errors Check
document.getElementById("btnSubmit").onclick = function() {
errorLoop();
}
function errorLoop() {
var runner = document.getElementsByClassName("invalid"),
formEmail = document.getElementById('email').value,
dataL = [];
dataLayer.push({'formEmail' : formEmail});
if (runner) {
for (var i = 0; i < runner.length; i++) {
var errName = runner[i].getAttribute("name"),
errId = runner[i]
.getAttribute("id");
dataL.push("Field: " + errName + " - ID: " + errId);
} //End for
dataL.toString();
var vadout = dataL + " Device: " + Uagent;
console.log(dataL);
dataLayer.push({
'formEmail' : formEmail,
'validationError': vadout,
'event' : 'errorpush'
});
} //End if
} //End errorLoop
So whats basically happening here is on a submit we are checking the form to see if any of the fields have the class invalid & if it does then it add's the name & Id of the fields to an array then prints then prints the array into a data layer.
The tag itself is triggered using a custom event called errorpush.
The issue is that this works only about 80% of the time we still get alot of people get validation errors but the validation errors don't seem to make it to the datalayer and back to google analytics.
I'm considering adding a settimeout delay to the datalayer push which I will go away and try but wanted to see if anyone knows of anything right off the bat which could be causing this problem.
Your runner is declared as empty array if there are no elements with class name "invalid". But your if statement is only checking for declaration thus:
if(runner){
}
will always be true but there are no "invalid" elements. Consequently dataL.push("Field: " + errName + " - ID: " + errId);will never execute in your for loop but dataLayer.push will, and so you will get errorpush event without any errors.
To solve this, I would suggest to rewrite your if statement:
if(runner.length > 0){
}
I hope this solves your problem.

A potentially dangerous Request.Form value was detected from the client (ctl00$cphMain$txCourseDescription="...ace="'MS Sans Serif&#...")

My screen has a Telrik rad popup which populate on a button click(btnCourseDescription). I have taken a label to show html formated data and a textbox to work with code behind file. when I click on btnCourseDescription; Telrik's popup opens and and after submit it shows data on label and assign value to textbox using Javascript ... Here is my Javascript code...
<script type="text/javascript">
function clientShow(sender, eventArgs)
{
//$find();
var txtInput = document.getElementById("<%=lbCourseDescription.ClientID%>");
sender.argument = txtInput.innerHTML;
}
function clientClose(sender, args)
{
if (args.get_argument() != null)
{
var lbInput = document.getElementById("<%=lbCourseDescription.ClientID%>");
var txtInput = document.getElementById("<%=txCourseDescription.ClientID%>");
lbInput.innerHTML = args.get_argument();
txtInput.value = args.get_argument.htmlEncode();
}
}
</script>
Now when I click on btnCourseDescription and and assign value using popup data submits successfully but when I want to update any other field means I am not updating HTML formatted data, HARDERROR occurs:
A potentially dangerous Request.Form value was detected from the client (ctl00$cphMain$txCourseDescription="...ace="'MS Sans Serif&#...").
Please suggest me what should I do?

Update Salesforce Case information

I have created a button to escalate a case. I am trying to change the record type, the "Owner" and append "Case Escalated" to the "Notes" field.
Code:
{!REQUIRESCRIPT("/soap/ajax/27.0/connection.js")}
var objCase = new sforce.SObject('Case');
objCase.Id = '{!Case.Id}';
objCase.Owner__c = 'Global Salesforce Team';
objCase.RecordTypeId = '012C00000007l5WIAQ';
objCase.Notes__c += 'Case Escalated';
var result = sforce.connection.update([objCase]);
if(result[0].success=='true'){
alert('The Case was Updated Successfully');
location.reload(true);
} else if(result[0].success=='true'){
alert('There was an issue updating the case');
}
However this wipes the "Notes" field and adds in "undefinedCase Escalated" instead of appending the string "Case Escalated" to the end of whatever is in there.
I am new to javascript, please be nice :)
i saw the code and the problem seems to be that you are creating a new instance of the Case to update, so there is nothing on the field Notes, and once you insert the record it overwrites with the only text there, 'Case Escalated', to get this to work you have to do a query to look for the value that was before on the field and then append the value to the notes__c field.
{!REQUIRESCRIPT("/soap/ajax/27.0/connection.js")}
var result = sforce.connection.query("select Id, Owner__c, RecordTypeId, Notes__c from Case WHERE Id='{!Case.Id}' LIMIT 1");
var records = result.getArray('records');
var objCase = records[0];
objCase.Owner__c = 'Global Salesforce Team';
objCase.RecordTypeId = '012C00000007l5WIAQ';
objCase.Notes__c += 'Case Escalated';
var result = sforce.connection.update([objCase]);
if(result[0].success=='true'){
alert('The Case was Updated Successfully');
location.reload(true);
} else if(result[0].success=='true'){
alert('There was an issue updating the case');
}
The link to the developer guide with an example is at http://www.salesforce.com/us/developer/docs/ajax/apex_ajax.pdf
Havent tested it and there is some error handling to be done in my code, but it should work.

Javascript validation display string within webpage rather than alert

Hi I currently have a form on submission the following validation rule is checked:
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("message","req","Please enter a valid message.");
</script>
function Validator(frmname)
{
this.formobj=document.forms[frmname];
if(!this.formobj)
{
alert("Error: couldnot get Form object "+frmname);
return;
}
if(this.formobj.onsubmit)
{
this.formobj.old_onsubmit = this.formobj.onsubmit;
this.formobj.onsubmit=null;
}
else
{
this.formobj.old_onsubmit = null;
}
this.formobj._sfm_form_name=frmname;
this.formobj.onsubmit=form_submit_handler;
this.addValidation = add_validation;
this.setAddnlValidationFunction=set_addnl_vfunction;
this.clearAllValidations = clear_all_validations;
this.disable_validations = false;//new
document.error_disp_handler = new sfm_ErrorDisplayHandler();
this.EnableOnPageErrorDisplay=validator_enable_OPED;
this.EnableOnPageErrorDisplaySingleBox=validator_enable_OPED_SB;
this.show_errors_together=true;
this.EnableMsgsTogether=sfm_enable_show_msgs_together;
document.set_focus_onerror=true;
this.EnableFocusOnError=sfm_validator_enable_focus;
}
However I would like the error message to be displayed on the webpage rather than an alert, could someone please achieve this.
The tutorial you are using cites the form validator as http://www.javascript-coder.com/html-form/javascript-form-validation.phtml If you read that, specifically at the top of the second page you will see:
Showing all the form validation errors together in a message box
If you want to show all the error messages together, then just call
the EnableMsgsTogether() function as shown below.
frmvalidator.EnableMsgsTogether();
The text which follows this provides further options for handling of error messages.
You could perhaps try that.

Categories

Resources