title: CRM 2011: Change Value OnCreate on Form with JS
body: <p>I want to change the value of a field with javascript on the OnSave Event of a Form in CRM 2011. This should only occur if the entity is created. </p>
  
  <p>This means I check the FormMode for OnCreate and then try to change a field value with:</p>
  
  <pre><code>Xrm.Page.data.entity.attributes.get("field").setValue("asd"); 
  Xrm.Page.data.entity.save();    
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Xrm.Page.getAttribute("field").setValue("asd");
  Xrm.Page.data.entity.save();
  </code></pre>
  
  <p>neither of them is working. How do I save/change the value OnCreate with JavaScript in a CRM 2011 Form?</p>
  
  <hr>
  
  <p>Code:</p>
  
  <pre><code>function doSomeThingOnSave(ExecutionObj) {
      var formType = Xrm.Page.ui.getFormType();
      if (formType != 1) return;
      var odataSelect = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc";
      odataSelect += "/blablabla";
  
      $.ajax({
      type: "GET",
      contentType: "application/json; charset=utf-8",
      datatype: "json",
      url: odataSelect,
      beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
      success: function (data, textStatus, XmlHttpRequest) {
          if (data.d.results != null &amp;&amp; data.d.results[0] != null) {
              var value= data.d.results[0].asdsda;
  
          var field = Xrm.Page.getAttribute('sad');
          if (field != null) {
              field.setSubmitMode("always");
              field.setValue(field.getValue() +value);
              }
  }
  
      },
      error: function (XmlHttpRequest, textStatus, errorThrown) {
          if (errorThrown != "Forbidden")
              alert('OData Select Failed: ' + odataSelect);
      }
  });
  </code></pre>
  
  <p>}</p>
  
  <p>seems that my call was asynchronous. The correct code would be making the call synchron with <code>async:false</code></p>