Set Unit as Default When I Select a Product in Opportunity Product.

Proposed Answer Set Unit as Default When I Select a Product in Opportunity Product.

  • Wednesday, March 23, 2011 5:58 AM
     
     

    Hello Everyone,

            I am using CRM 2011 RC and i am stuck in a issue in Opportunity Product Form.Here when we select the product I want to auto fetch and set the unit by default. Can anyone help me in this.!!!

    One more issue is in Opportunity Product,we have wuantity,I have set the precision for it to be zero,but when the unit field is selected it automatically takes the precision of quantity from the Unit which is 5 decimals.

    Please help me out to resolve this two issues.

    Thanks,

    Bilal Sayed.


    Bilal Sayed.

All Replies

  • Wednesday, March 23, 2011 7:18 AM
     
      Has Code

    Hello Bilal,

    You can use this library to retrieve a certain record on the OnLoad() event of the form.

    For the unit, try the following code:

    // Sets the lookup value for a certain field
    function SetLookupValue(fieldName, id, name, entityType) 
    {
    	if(fieldName != null) 
    	{
    		var lookupValue = new Array();
    		lookupValue[0] = new Object();
    		lookupValue[0].id = id;
    		lookupValue[0].name = name;
    		lookupValue[0].entityType = entityType;
     
    		Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    	}
    }
    
    function SetDefaultUnit()
    {
    	var outputColumns = [new CRMField("uomid"), new CRMField("name")];
    	var defaultUnitId = <your_id_here>;
    	var unit = RetrieveRecord("uom", outputColumns, defaultUnitId);
    
    	if(unit != null)
    	{
    		var unitName = unit.GetValue("name");
    
    		SetLookupValue("the_unit_field_schema_name_on_form", defaultUnitId, unitName, "uom");
    	}
    }
    
    SetDefaultUnit();
    


    Cornel Croitoriu - Senior Software Developer & Entrepreneur

    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    Biz-Forward.comCroitoriu.NET

  • Thursday, March 24, 2011 5:53 AM
     
     

    Hello Cornel,

                     I tried the above script but the thing is that ,When the product is selected the unit is set and again the unit goes.I think there is some other system occuring after our script is executed,hich results in removing the lookup value.

    Can you help me out in this!!!

     


    Bilal Sayed.
  • Thursday, March 24, 2011 7:32 AM
    Moderator
     
     

    I face the same issue too!

     1、the product is selected。

     2、the onChange event of product attribute is fired。

     3、In the onChange event we set the default value to the unit ,and pop a alert message.

     4、the unit is set a default value,when close the alert window,the unit  goes.

    so i think after the onChange event  other system will remove the lookup value. but in mscrm 4.0 the same way work fine!


    刀客 | MSN:caims@techsun.com | BLOG:http://caims.cnblogs.com | 提供微软CRM高级开发顾问外包
  • Thursday, March 24, 2011 7:37 AM
     
     Proposed Answer Has Code

    I was struggling with this lately. During the onChange Event, the uom lookup remains readonly in CRM2011. You will have to do this with a slight delay:

     

    // this is the event handler
    function ProductOnChange_SetUOM() {
            // add delay of since lookup is readonly
       window.setTimeout("SetDefaultUnit()", 100);
    	}
    • Proposed As Answer by WimCo Thursday, March 24, 2011 10:56 AM
    •  
  • Thursday, March 24, 2011 10:56 AM
     
     

    Although I do not like the solution too much, Frank's script should defintely work. (I don't like it because it uses delay and to what should we set the delay to make sure it is enough?)

    The delay is needed mainly because CRM 2011 executes its own script during the OnChange event of the Product lookup. This builtin script enables/disables the control again, but also clears the value which is set in the Unit lookup. Unfortunately this script always runs AFTER your script methods that you link to the OnChange event in the editor. Thanks to the delay you can make sure(/hope) that the execution of your method is only started after the execution of the CRM 2011 default OnChange script.

    Not sure if there are any other unsopported Javascript events we could attach to in order to make sure that you refill the default unit when it gets cleared.

  • Thursday, March 24, 2011 11:03 AM
     
     

    Although I do not like the solution too much, Frank's script should defintely work. (I don't like it because it uses delay and to what should we set the delay to make sure it is enough?)

    Yeah that's right. Until now 100ms seems to be a good value, since it is enough so that the field is no longer disabled and not too much, so that the user will actually notice a delay or is able to start typing/editing the lookup.
  • Friday, April 15, 2011 6:27 PM
     
     

    Hi Cornel,

    I'm looking for some help.  (FYI I'm still learning Jscript) 

    I'm using your code on the QuoteProduct form to populate the Unit field.  When I run the SetDefaultUnit() function on the Existing Product OnChange, I get an error that 'CRMField' is not defined.

    Is there a function for CRMField()?

    Any ideas on what I may be missing?

    Thanks,
    Valerie

     


    Valerie Lingen
  • Thursday, May 19, 2011 2:29 PM
     
     

    I implemented a different solution and it works fine until I save and close the Opportunity Product window, then I receive "An error has occurred" with no descriptive explanation...anyone have any idea why?

    First I set the quantity to 1 and set a delay as recommended above.  Then I set the unit to "Hours"...as you can see I also set to "Default Unit" just to see if the "Hours" had anything to do with the error, but I still received the error upon save and close.  any help would be welcomed.

    function SetQuantity() {
        var Name = Xrm.Page.data.entity.attributes.get("quantity");
        Name.setValue(1.00000);
        window.setTimeout("nowupdateunit()", 250);

    }

    function nowupdateunit() {
    if(crmForm.all.quantity.DataValue != null)
    {
              //alert("you are here");
                    //Create an array to set as the DataValue for the lookup control.
                    var lookupDataB = new Array();
              //Create an Object add to the array.
                    var lookupItemB= new Object();
              //Set the id, typename, and name properties to the object.
                   lookupItemB.id = 'b1C369482-9C0E-E011-8BDB-78E7D162EE7D';
                   lookupItemB.typename = 'uom';
                  lookupItemB.name = 'Hours';

                  //lookupItemB.id ='b2DDF2545-E898-420F-BFED-8802E1E9D2A9';
                  //lookupItemB.typename = 'uom';
                  //lookupItemB.name = 'Default Unit';


             // Add the object to the array.
                   lookupDataB[0] = lookupItemB;
             // Set the value of the lookup field to the value of the array.
            //alert("lookupDataB=" & lookupDataB);
                   crmForm.all.uomid.DataValue = lookupDataB;
    }
    }

  • Thursday, May 19, 2011 3:25 PM
     
     

    I resolved my problem by moving the code out of the Existing Product OnChange Event.  Apparently as you pick a product form the list, the OnChange Event launchs in the middle of the CRM code. So based on what I saw in the debugger, the OnChange event would run but some other code ran after which cleared out the DataValue I put in.

    Once I moved my code to a different field OnChange event it worked great!

    if (crmForm.all.uomid.DataValue == null)
    {
    var lookupData = new Array();
      var lookupItem= new Object();
      lookupItem.id = '{640e595a-bf19-42f2-95ed-2e47a514c4b2}';
       lookupItem.typename = 'uom';
       lookupItem.name = 'Primary Unit';
    // Add the object to the array.
       lookupData[0] = lookupItem;
    // Set the value of the lookup field to the value of the array.
       crmForm.all.uomid.DataValue =lookupData;
       crmForm.all.uomid.ForceSubmit = true;
    }


    Valerie Lingen
  • Wednesday, June 15, 2011 11:23 AM
     
     

    I have used the code the Valerie posted and I am almost there.  I have triggered the code when the quantity field is changed and it works, but when I try to save the record I get "Record is Unavailable - the requested record was not found...".  I am sure this is something to do with the GUID but I can not work out how to get the GUID so that I can put in the lookupItem.id variable.

    If someone could show me how to do this it would be appreciated as I feel I am very close to making this work.

    Thanks
    Ian

  • Saturday, January 07, 2012 11:11 AM
     
     

    I face the same issue too!

     1、the product is selected。

     2、the onChange event of product attribute is fired。

     3、In the onChange event we set the default value to the unit ,and pop a alert message.

     4、the unit is set a default value,when close the alert window,the unit  goes.

    so i think after the onChange event  other system will remove the lookup value. but in mscrm 4.0 the same way work fine!


    刀客 | MSN:caims@techsun.com | BLOG:http://caims.cnblogs.com | 提供微软CRM高级开发顾问外包

    Hi am having the same issue with the opportunity product, did someone find a response to this problem?

    IVe even post my code

    see it at 

    http://social.microsoft.com/Forums/en-US/crm/thread/8ceccb29-5139-4850-8113-5f867ad83c52


    Be wise
  • Saturday, January 07, 2012 11:16 AM
     
     

    I resolved my problem by moving the code out of the Existing Product OnChange Event.  Apparently as you pick a product form the list, the OnChange Event launchs in the middle of the CRM code. So based on what I saw in the debugger, the OnChange event would run but some other code ran after which cleared out the DataValue I put in.

    Once I moved my code to a different field OnChange event it worked great!

    if (crmForm.all.uomid.DataValue == null)
    {
    var lookupData = new Array();
      var lookupItem= new Object();
      lookupItem.id = '{640e595a-bf19-42f2-95ed-2e47a514c4b2}';
       lookupItem.typename = 'uom';
       lookupItem.name = 'Primary Unit';
    // Add the object to the array.
       lookupData[0] = lookupItem;
    // Set the value of the lookup field to the value of the array.
       crmForm.all.uomid.DataValue =lookupData;
       crmForm.all.uomid.ForceSubmit = true;
    }


    Valerie Lingen

    Thanks for your participation

    im curious to know which Debbuger you used and how you use it, can you give a links or more Details about it?

    Thanks


    Be wise
    • Edited by TheeNerd01 Saturday, January 07, 2012 11:17 AM
    •  
  • Saturday, January 07, 2012 11:18 AM
     
     

    I resolved my problem by moving the code out of the Existing Product OnChange Event.  Apparently as you pick a product form the list, the OnChange Event launchs in the middle of the CRM code. So based on what I saw in the debugger, the OnChange event would run but some other code ran after which cleared out the DataValue I put in.

    Once I moved my code to a different field OnChange event it worked great!

    if (crmForm.all.uomid.DataValue == null)
    {
    var lookupData = new Array();
      var lookupItem= new Object();
      lookupItem.id = '{640e595a-bf19-42f2-95ed-2e47a514c4b2}';
       lookupItem.typename = 'uom';
       lookupItem.name = 'Primary Unit';
    // Add the object to the array.
       lookupData[0] = lookupItem;
    // Set the value of the lookup field to the value of the array.
       crmForm.all.uomid.DataValue =lookupData;
       crmForm.all.uomid.ForceSubmit = true;
    }


    Valerie Lingen

    Thanks for your participation

    im curious to know which Debbuger you used and how you use it, can you give a links or more Details about it?

    Thanks


    Be wise
    One more thing where do you move your code to? to which Field?
    Be wise
  • Sunday, January 08, 2012 5:22 AM
     
     

    You can use the Developer Tools option available in IE browser. This will display the script in debugger IDE. Set the breakpoints and you should be able to debug your scripts. Make sure to select the correct script file to debug.

    You can have a look at the following link for help http://inogic.blogspot.com/2010/11/debug-script-in-microsoft-dynamics-crm.html

    The code can be written on OnChange of the Product or if it is going to be the same irrespective of the Product, you can have it on OnSave or OnLoad...

    HTH

    Sam


    Dynamics CRM MVP | Inogic | http://inogic.blogspot.com| news at inogic dot com

    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

  • Monday, April 09, 2012 7:15 PM
     
     

    My requirement is that both the UOM and the quantity be defaulted. So moving my onChange to another field isn't really an option.

    Did anyone get the delay to work? Something like this:

          window.setTimeout(“doUnitEach()”, 100);

    Edit:

    CRM 2011 accepted the code without error when I changed the quotes to single quotes. I think it was a character set issue with the slanted quotes I had grabbed from a webpage.

  • Monday, April 09, 2012 8:00 PM
     
     Proposed Answer Has Code

    Here is the code that I am using for the order product with success to set the default unit after the user selects a product from the lookup (this should be about the same for the Opportunity Product). We were using this in CRM 4.0, but have found after the upgrade to 2011 that this still works just fine.

    function productid_onchange() { GetAttributeValueFromID= function(sEntityName, sGUID, sAttributeName,sOrganizationName) { var xml = "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + Xrm.Page.context.getAuthenticationHeader() + " <soap:Body>" + " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" + " <q1:EntityName>" + sEntityName +"</q1:EntityName>" + " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" + " <q1:Attributes>" + " <q1:Attribute>" + sAttributeName + "</q1:Attribute>" + " </q1:Attributes>" + " </q1:ColumnSet>" + " <q1:Criteria>" + " <q1:FilterOperator>And</q1:FilterOperator>" + " <q1:Conditions>" + " <q1:Condition>" + " <q1:AttributeName>"+ sEntityName + "id</q1:AttributeName>" + " <q1:Operator>Equal</q1:Operator>" + " <q1:Values>"+ "<q1:Value xsi:type=\"xsd:string\">" + sGUID + "</q1:Value>" + "</q1:Values>" + " </q1:Condition>" + " </q1:Conditions>" + " </q1:Criteria>" + " </query>" + " </RetrieveMultiple>" + " </soap:Body>" + "</soap:Envelope>" + ""; var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false); xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple"); xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); xmlHttpRequest.setRequestHeader("Content-Length", xml.length); xmlHttpRequest.send(xml); var resultXml = xmlHttpRequest.responseXML; if (resultXml != null) { var names = resultXml.selectNodes("//BusinessEntity/q1:" + sAttributeName); if (names != null) { if (names.length > 0) { return names[0].text; } } //return "*Error*"; } }

    //Set unit with default unit of product using CRM webservice
    if(Xrm.Page.getAttribute("productid").getValue() != null)
    {
        var ProductSelected = new Array;
        ProductSelected = Xrm.Page.getAttribute("productid").getValue();

        var UnitId = "";
        var UnitDescription = "";
        UnitId = GetAttributeValueFromID("product",ProductSelected[0].id,"defaultuomid");
        UnitDescription = GetAttributeValueFromID("uom",UnitId,"name");

        var InputUnitId = new Array();
        InputUnitId[0] = new LookupControlItem (UnitId, 1055, UnitDescription);
        Xrm.Page.getAttribute("uomid").setValue(InputUnitId);
    }
    else
    {
        Xrm.Page.getAttribute("uomid").setValue(null);
    }

    As far as the precision issue, I struggled with this myself. I ended up creating a separate amount field to display to the user and used background code to update the quantity as I could not find a way to reduce the precision.

    Thanks,


    • Edited by ccortright Monday, April 09, 2012 8:01 PM
    • Proposed As Answer by ccortright Tuesday, May 08, 2012 7:08 PM
    •  
  • Saturday, June 02, 2012 7:09 AM
     
     

    I need Unit lookup value in the Quote product Entity to be set automatically as "Gram" once the Existing product is given.When I used Theenerd01's code and made the lookup value to be displayed in alert, its displaying "[object object]". Can you guide me with that coding?

    Here is my code:

    if (Xrm.Page.getAttribute("uomid").getValue() == null)
    {
    var lookupData = new Array();
      var lookupItem= new Object();
      lookupItem.id = '{DEFF1939-94B4-4F3C-AB78-21AB1A08C0FB}';
       lookupItem.entityType = 'uom';
       lookupItem.name = 'Primary Unit';
    // Add the object to the array.
       lookupData[0] = lookupItem;
    // Set the value of the lookup field to the value of the array.
       //Xrm.Page.getAttribute("uomid").getValue() =lookupData;
       //Xrm.Page.getAttribute("uomid").setSubmitMode("always");
       alert(lookupData);
    }

    I have set this alert in Existing Product onchange Event.


    Naren

  • Saturday, June 02, 2012 7:35 AM
     
     

    lookupdata is an array and so it will display object in the alert.

    The guid provided in lookupitem.id should be the guid of Gram uom that you have created in your system.

    In lookupitem.name you need to set Gram which is the name of the uom you need to set.

    To set the value to the uomid field use setValue instead of getValue in the commented lines above.

    HTH

    Sam


    Dynamics CRM MVP | Inogic | http://inogic.blogspot.com| news at inogic dot com

    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"