Changing ''pricelevelid'' field based on another field - javascript

im so new to javascript, my situation is beginner of the beginner :)
But i have to write a code on mscrm 2011 order entity.
i have two field, pricelevelid and new_taxincl(radio button). I want to change value in pricelevelid field based on selection of new_taxincl field.
If user select ''yes'' i want to fill pricelevelid field with ''USD -Tax Included-'', ''no'' ''USD -without tax-''. This have to run onChange event.
I could not write the correct code so far.
Any help will be fine for me.
Thanks.
PS: new_vrg is a field in the pricelevel entity and has same value with new_taxincl field in the order entity.
here is my code:
function callRetrievePList() {
var field = Xrm.Page.data.entity.attributes.get("new_taxincl");
if ((field == null) || (field.getValue() == null) || (field.getValue()[0] == null) || (field.getValue()[0].id == null))
return;
var plistfield = Xrm.Page.data.entity.attributes.get("pricelevelid");
if (plistfield != null && plistfield.getValue() != null)
return;
var options = "$select=PriceLevelId,Name&$filter=new_vrg/Id eq (guid'" + (field.getValue()[0]).id + "')";
SDK.REST.retrieveMultipleRecords("PriceLevel", options, retrievePListCallBack, errorCallBack, completeCallBack);
}
function retrievePListCallBack(retrievedStock) {
var plistfield = Xrm.Page.data.entity.attributes.get("pricelevelid");
if (plistfield != null && plistfield.getValue() != null)
return;
for (var i = 0; i < retrievedStock.length; i++) {
var stock = retrievedStock[i];
var lookupReference = [];
lookupReference[0] = {};
lookupReference[0].id = stock.PriceLevelId;
lookupReference[0].entityType = "pricelevel";
lookupReference[0].name = stock.Name;
plistfield.setValue(lookupReference);
return;
}
}
function errorCallBack(errorObject) {
}
function completeCallBack() {
}

Below code may help you:
To get a radio button in CRM JavaScript:
function TaxIncludedRadioButton_OnChange()
{
var taxInclBtn= Xrm.Page.ui.controls.get("new_taxincl").getAttribute().getValue();
var lookup = new Array();
lookup[0] = new Object();
if(taxIncludeRdBtn==true)
{
lookup[0].id = yourrecorid1;
lookup[0].name = 'USD -Tax Included-';
lookup[0].entityType = entityname;
Xrm.Page.getAttribute("pricelevelid").setValue(lookup);
}
else if(taxIncludeRdBtn==false)
{
lookup[0].id = yourrecorid2;
lookup[0].name = 'USD -Without-tax';
lookup[0].entityType = entityname;
Xrm.Page.getAttribute("pricelevelid").setValue(lookup);
}
}
Register the above function OnChange event of you new_taxincl radio button

Related

google tag manager template only reading first elements of array for events with more than 1 item

I'm implementing this google tag manager template(GA3/UA) but the issue is that when there is more than 1 product, it only catches or reads the first element of the arrays, this happens for all the events that can have more than 1 product, I'm kinda new to this, can anyone guide me in why is this happening? here is the code for the sandbox javascript, I just need to get all the elements of the arrays, not the first one, everything else works fine. Thank you very much in advance.
___SANDBOXED_JS_FOR_WEB_TEMPLATE___
const log = require('logToConsole');
const makeTableMap = require('makeTableMap');
// Call APIs to set dataLayer and copy values from dataLayer
const copyFromDataLayer = require('copyFromDataLayer');
// Set the function where we want to push the dataLayer
const createQueue = require('createQueue');
const dataLayerPush = createQueue('dataLayer');
//Validate structure
var ecommerce_data = copyFromDataLayer('ecommerce.'+data.activity);
if(ecommerce_data == undefined){
//dataLayerPush({'event': "error", "info": "enhanced ecommerce base structure not found for "+ data.activity});
// return;
ecommerce_data = {};
}
var ecommerce_actionField = copyFromDataLayer('ecommerce.'+data.activity+".actionField");
if(ecommerce_actionField == undefined){ ecommerce_actionField = {};}
var ecommerce_products = copyFromDataLayer('ecommerce.'+data.activity+".products");
if(ecommerce_products == undefined){ecommerce_products = []; ecommerce_products.push({});}
var ecommerce_impressions = copyFromDataLayer('ecommerce.'+data.activity);
if(ecommerce_impressions == undefined){ecommerce_impressions = []; ecommerce_impressions.push({});}
var ecommerce_promotions = copyFromDataLayer('ecommerce.'+data.activity+".promotions");
if(ecommerce_promotions == undefined){ecommerce_promotions = []; ecommerce_promotions.push({});}
//this fucntion works only for one element edition.
//Usable for: actionFiel, product click, detail, add, remove, promotionClick
//Params: aField, ecommerce_origin
function merge_element() {
log("entro 1");
let key;
for (key in arguments[0]) {
arguments[1][key] = arguments[0][key];
}
return arguments[1];
}
//this fucntion works for a list of elements edition.
//Usable for: products, impressions and promotions
//Params: prods, ecommerce_origin, type_index
function merge_elements(){
if(arguments[2] == "all"){
let key, elem;
for(elem in arguments[1]){
for (key in arguments[0]) {
arguments[1][elem][key] = arguments[0][key];
}
}
}else{
var indexes = data.index.split(",");
log("indexes", indexes);
let elem, key;
for(elem in indexes){
if(!arguments[1].hasOwnProperty(indexes[elem]-1)){
log(indexes[elem] + " is not a number or not beyong your array size");
continue;
}
for (key in arguments[0]) {
arguments[1][indexes[elem]-1][key] =arguments[0][key];
}
}
}
return arguments[1];
}
var aField = {}, prods = {}, impr = {},prom ={};
if(data.actionField != undefined){aField = makeTableMap(data.actionField, 'key', 'value');}
if(data.products != undefined){prods = makeTableMap(data.products, 'key', 'value');}
if(data.impressions != undefined){impr = makeTableMap(data.impressions, 'key', 'value');}
if(data.promotions != undefined){prom = makeTableMap(data.promotions, 'key', 'value');}
var type_index = "all";
if(data.type_index != undefined){type_index = data.type_index;}
const datalayer = {};
datalayer[data.activity] ={};
datalayer.currencyCode = copyFromDataLayer('ecommerce.currencyCode') != undefined? copyFromDataLayer('ecommerce.currencyCode'): data.currencyCode;
if(data.activity == "checkout"||data.activity =="click"||data.activity =="detail"|| data.activity == "purchase"){
log("entro click");
datalayer[data.activity].actionField = merge_element(aField, ecommerce_actionField);
datalayer[data.activity].products = merge_elements(prods, ecommerce_products, type_index);
}
if(data.activity == "add"||data.activity == "remove"){
datalayer[data.activity].products = merge_elements(prods, ecommerce_products, type_index);
}
if(data.activity == "promoView"|| data.activity == "promoClick"){
datalayer[data.activity].promotions = merge_elements(prom, ecommerce_promotions, type_index);
}
if(data.activity == "impressions"){
datalayer[data.activity].impressions = merge_elements(impr, ecommerce_impressions, type_index);
}
//basic data recompilation
var event = "", eventCategory = "",eventAction = "",eventLabel = "",eventValue = 0;
if(data.basic_data){
event = data.event_name +"";
eventCategory = data.event_category+"";
eventAction = data.event_action+"";
eventLabel = data.event_label+"";
eventValue = data.event_value+"";
}
if(event == ""){
event = copyFromDataLayer('event')+ "_changed";
}if(eventCategory == ""){
eventCategory = copyFromDataLayer('eventCategory') != null? copyFromDataLayer('eventCategory'): "Enhanced ecommerce";
}if(eventAction == ""){
eventAction = copyFromDataLayer('eventAction') != null? copyFromDataLayer('eventAction'): data.activity;
}if(eventLabel == ""){
if(copyFromDataLayer('eventLabel') != null){
eventLabel= copyFromDataLayer('eventLabel');
}else{
if(data.activity == "impressions"){
eventLabel = datalayer[data.activity].impressions[0].name;
}
if(data.activity == "promoView"|| data.activity == "promoClick"){
eventLabel = datalayer[data.activity].promotions[0].name;
}else{
eventLabel=datalayer[data.activity].products[0].name;
}
}
}if(eventValue == 0){
if(copyFromDataLayer('eventValue') != null){
eventValue = copyFromDataLayer('eventValue');
}
}
dataLayerPush({'event': event,'eventCategory': eventCategory, 'eventAction': eventAction, 'eventLabel': eventLabel, 'eventValue': eventValue,'ecommerce':datalayer});
data.gtmOnSuccess();
You can Mock the DL values in the template unit tests.
Mock it properly, run the tests, debug the values. If that is not enough to make the issue obvious, post a mcve of your attempt.
Don't just dump the whole template in a question. Show your debugging attempts.

Auto-Populate Field using Javascript

I created this javascript to auto populate a field, with values from other fields. It is called in the form onSave event.
function OppTopic() {
var products = "";
var parent = Xrm.Page.getAttribute("parentaccountid").getvalue();
var city = Xrm.Page.getAttribute("address1_city").getValue();
var automation = Xrm.Page.getAttribute("new_automationfeatures").getValue();
var service = Xrm.Page.getAttribute("new_service").getValue();
//Determines if a Product/Service is selected
if (automation == true) {//***AUTOMATION***
if (products != ""){
products += ",Automation";
}
else{
products = "Automation";
}
}
if (service == true) {//***SERVICE***
if (products != "")
products += ",Service";
else
products = "Service";
}
if (automation == false && service == false) {
products = "null";
}
var subject = parent + " - " + city + " - " + products;
Xrm.Page.getAttribute("name").setValue(subject);
}
But , when the form is saved this is the error that appears.I'm not really sure what the error means?
I have checked the field names and they are correct.
What could be the problem that is causing this error?
Thanks
var parent will return a javascript object that is a CRM lookup. If you are putting it together in a string with other strings, you will have to retrieve the name or whichever other attribute from the lookup you're trying to add
var parentName = "";
var parent = new Array();
parent = Xrm.Page.getAttribute("parentaccountid").getValue();
if(parent!=null){
parentName = parent[0].name;
}
Source: http://www.mscrmconsultant.com/2012/08/get-and-set-lookup-value-using.html

Filter a child picklist in CRM 2011

I'm trying to convert javascript code from CRM 4.0 to CRM 2011.
I'm having problems with a picklist filter.
My function is on the onchange of the parent picklist. It works the first time but the second it erase everything from my child picklist.
This is the part where I suppose to reset the picklist
if(!oSubPicklist.originalPicklistValues)
{
oSubPicklist.originalPicklistValues = oSubPicklist.getOptions();
}
else
{
oSubPicklist.getOptions = oSubPicklist.originalPicklistValues;
oSubPicklist.setOptions = oSubPicklist.originalPicklistValues;
}
And this is the part where i remove all the option not related:
oTempArray is an array with the options that i want to keep. If a check the "oSubPicklist.getOptions.length" the value is the same that my original picklist.
for (var i=oSubPicklist.getOptions.length; i >= 0;i--)
{
if(oTempArray[i] != true)
{
Xrm.Page.getControl("new_product").removeOption(i);
}
}
Ideas?
Edit: I solved declaring a global var with the originalPickList in the onLoad event and:
oSubPicklist.clearOptions();
for (var i=0; i< oSubPicklist.originalPicklistValues.length; i++)
{
for (var j=0; j< oDesiredOptions.length; j++)
{
if (i == oDesiredOptions[j])
{oSubPicklist.addOption(oSubPicklist.originalPicklistValues[i]);}
}
}
Your code is not very clear to me: May be you could paste all your function code for better understanding but:
This is how you get the options from PickList in CRM 2011
var myOptionSet = Xrm.Page.ui.controls.get("new_product") //get Control
var optionsSet = myOptionSet .getAttribute().getOptions(); //get Options
preferredTimeOptionSet.clearOptions(); //Clear all options
//Create a new Option
var opt1 = new Option();
opt1.text = "one";
opt1.value = 1;
//Add Option
myOptionSet.addOption(opt1);
//Remove Option
myOptionSet.removeOption(1);
Good Example here
Here is another way to do Parent/Child picklists:
function dynamicDropdown(parent, child) {
filterPicklist(parent, child);
}
function parentListFilter(parent, id) {
var filter = "";
if (getParentCode(parent) != "") {
filter = getParentCode(parent);
} else {
// No [ ] match
}
return filter;
}
function filterPicklist(parent, child) {
var parentList = Xrm.Page.getAttribute(parent).getValue();
var childListControlAttrib = Xrm.Page.getAttribute(child);
var childListOptions = childListControlAttrib.getOptions();
var childListControl = Xrm.Page.getControl(child);
var codeToFilterListOn = parentListFilter(parent, parentList);
if (codeToFilterListOn != "") {
childListControl.clearOptions();
for (var optionIndex in childListOptions) {
var option = childListOptions[optionIndex];
// Ignore xx and check for Match
if (option.text.substring(0, 2) != "xx" && option.text.indexOf(codeToFilterListOn) > -1) {
childListControl.addOption(option);
}
}
} else {
// Didn't match, show all?
}
}
function getParentCode(parent) {
//Get Parent Code Dynamically from inside [ ]
var filter = "";
var parentValue = Xrm.Page.getAttribute(parent).getText();
if (parentValue && parentValue.indexOf("]") > -1) {
var parentCode = parentValue.substring(parentValue.indexOf("[") + 1, parentValue.indexOf("]"));
if (parentCode) {
filter = parentCode + " | ";
} else {}
}
return filter;
}
See more here: Parent/Child

parameter count mismatch exception thrown when event handler of button called from javascript

I have a few textboxes on a page whose values are getting populated from the return value of
a modal window like this and I have a javascript method that calls the event handler of a button in the following way. The values are being returned properly and the textbox is getting populated properly but i am getting an exception parameter count mismatch.
res = window.showModalDialog('frm_VisitorSearchPopUp.aspx', "", "dialogWidth:1024px;dialogHeight:600px");
getElementById('<%=AddVisitorID.ClientID %>').click();
This problem does not occur when i am using window.open() method can anybody tell me why this problem is occurring.
My Code
function openup() {
var left = screen.width / 2 - 1024 / 2;
var tops = screen.height / 2 - 600 / 2;
var d = new Date();
var res;
res = window.showModalDialog('frm_VisitorSearchPopUp.aspx', "", "dialogWidth:1024px;dialogHeight:600px");
setvalues(res.PersonName, res.Address, res.CompanyName, res.ContactNumber, res.Email);
}
function setvalues(PersonName, Address, CompanyName, ContactNumber, Email) {
var RowId = $("#<%= VisitorDetailsGrid.ClientID%>").getDataIDs();
for (i = 0; i < RowId.length; i++) {
rowData = $("#<%= VisitorDetailsGrid.ClientID%>").getRowData(RowId[i]);
if (rowData.PersonName == PersonName && rowData.ContactNumber == ContactNumber && rowData.CompanyName == CompanyName && rowData.Email == Email && rowData.Address == Address) {
alert("The visitor \"" + PersonName + "\" has already been added to the visitor's list.");
document.getElementById('<%=PersonNameID.ClientID%>').value = "";
document.getElementById('<%=AddressID.ClientID%>').value = "";
document.getElementById('<%=CompanyNameID.ClientID%>').value = "";
document.getElementById('<%=ContactNumberID.ClientID%>').value = "";
document.getElementById('<%=EmailID.ClientID%>').value = "";
return;
}
}
document.getElementById('<%=PersonNameID.ClientID%>').value = PersonName;
document.getElementById('<%=AddressID.ClientID%>').value = Address;
document.getElementById('<%=CompanyNameID.ClientID%>').value = CompanyName;
document.getElementById('<%=ContactNumberID.ClientID%>').value = ContactNumber;
document.getElementById('<%=EmailID.ClientID%>').value = Email;
elem = document.getElementById('<%=AddVisitorID.ClientID %>').click();
}

Accessing dynamically created Dojo checkbox widgets in javascript

I am trying to create checkboxes using Dojo problematically. The no. of checkboxes are different according to the selection made.
I am able to create the boxes. The problem is when I try to submit the form and try to access the boxed using dijit.byid("ID"), the IE gives undefined message.
below is the code. I am abe to creae the checkboxes but cant access them.
Code to create checkboxes in Javascript :
function displayDefiningC(definingCharacteristicCount,fieldData){
try{
if( (document.getElementById("problemDefChar").style.display == "none") && (definingCharacteristicCount > 0))
{
document.getElementById("problemDefChar").style.display = "block";
**var DefCharSpan = dojo.doc.createElement("span");
for(j = 1; j<=definingCharacteristicCount; j++ )
{
var DefCharCheckbox = new dijit.form.CheckBox();
DefCharCheckbox.id = "PDCDEFCHAR"+j;
DefCharCheckbox.name = "PDCDEFCHAR"+j;
DefCharCheckbox.value = fieldData[j].DefiningCharacter;
DefCharCheckbox.checked = false;
var DefCharLabel = dojo.doc.createElement("span");
DefCharLabel.innerHTML = fieldData[j].DefiningCharacter;
var DefCharBreak = dojo.doc.createElement("br");
DefCharSpan.appendChild(DefCharCheckbox.domNode);
DefCharSpan.appendChild(DefCharLabel);
DefCharSpan.appendChild(DefCharBreak);
dojo.place(DefCharSpan, dojo.byId("DefCharCheckBox"), "last");
}**
}
}catch(e){
alert(e);
}
return;
}
and i am trying to access these checkboxes using :
var defchar= dijit.byId("PDCDEFCHAR1");
alert("defchar " +defchar);
but this given undefined.
I have got it solved....the problem was I was creating it wrongly :)
function displayDefiningC(definingCharacteristicCount,fieldData){
try{
if( (document.getElementById("problemDefChar").style.display == "none") && (definingCharacteristicCount > 0))
{
document.getElementById("problemDefChar").style.display = "block";
var DefCharSpan = dojo.doc.createElement("span");
for(j = 1; j<=definingCharacteristicCount; j++ )
{
var DefCharCheckbox = new dijit.form.CheckBox({
name: "PDCDEFCHAR"+j,
id: "PDCDEFCHAR"+j,
value: fieldData[j].DefiningCharacter,
checked: false,
});
var DefCharLabel = dojo.doc.createElement("span");
DefCharLabel.innerHTML = fieldData[j].DefiningCharacter;
var DefCharBreak = dojo.doc.createElement("br");
DefCharSpan.appendChild(DefCharCheckbox.domNode);
DefCharSpan.appendChild(DefCharLabel);
DefCharSpan.appendChild(DefCharBreak);
dojo.place(DefCharSpan, dojo.byId("DefCharCheckBox"), "last");
}
}
}catch(e){
alert(e);
}
return;
}

Categories