Saturday, April 7, 2012

Startup script Onload AND Onsave! Basic's for every Jscript!

Tired of having XX web-resurces on a form? Well.. Now you can controll everything within one JS with only 1. trigger:
- OnChange
- Onload
- OnSave

as well as:
- For all form types: OnCreate, OnNewForm, onReadonly ++

Read more about this in my previous post: Best javascript startup script ever
/* Script Entry Point */
function OnCrmPageLoad() {
 var FormTypes =
 {
Undefined: 0,
Create: 1,
Update: 2,
ReadOnly: 3,
Disabled: 4,
QuickCreate: 5,
BulkEdit: 6
 }
 runAlways();
 switch (crmForm.FormType) {
 case FormTypes.Create: OnNewFormLoad(); break;
 case FormTypes.Update: OnUpdateFormLoad(); break;
 case FormTypes.ReadOnly: OnReadOnlyFormLoad(); break;
 case FormTypes.Disabled: OnDisabledFormLoad(); break;
 case FormTypes.QuickCreate: OnQuickCreateFormLoad(); break;
 case FormTypes.BulkEdit: OnBulkEditFormLoad(); break;
 case FormTypes.Undefined: alert("Error"); break;
 }
}
/* Implement each Form Type you wish to address */
function runAlways() {
 onchange();
 Xrm.Page.data.entity.addOnSave(addToOnSave);
}
function OnNewFormLoad() {
}
function OnUpdateFormLoad() {}
function OnReadOnlyFormLoad() { }
function OnDisabledFormLoad() { }
function OnQuickCreateFormLoad() { }
function OnBulkEditFormLoad() { }
/******************** OnChange and OnSave functions ***************************/
function onchange(){
 //Skriv inn alle felter som skal ha OnChange
 Xrm.Page.data.entity.attributes.get("prefix_field").addOnChange(Summering);
}
function addToOnSave() {
 var SAVE_MODE_SAVE = 1;
 var SAVE_MODE_SAVEANDCLOSE = 2;
 // Validate only if the user clicked "Save".
 switch (event.Mode){
 case SAVE_MODE_SAVE:
  //Do something for "save"
  if(/*write you check*/) {
   // Cancel the save operation.
   event.returnValue = false;
   return false;
  }
  break;
 case SAVE_MODE_SAVEANDCLOSE:
  //Do something for "Save and close"
  if(/*write you check*/) {
   // Because this is a "Save and Close",
   // just save the form.
   return true;
  }
  break;
 }
}
/*************** End OnChange and OnSave functions ***************************/
/* --------------- Private functions ---------------------*/
function Summering(){
alert("You are inside a function triggerd from a onChange");
}
/* ------------ End Private functions------------------*/