CRM 4.0 - Create Method Cloning Quote Record - javascript

Can anyone help me please?
I'm trying to create a record using the create method through javascript.
I need to copy all the fields' value and create a new entity. Like cloning a record in CRM 4.0
I'm using quote entity. I'm trying to pass the Opportunity. It was successful but when i look into the grid view, the opportunity field is blank. but in the form, it has a value.
Then i try to look into the opportunity form and see related Quotation, but it doesn't appear there.
Thank you for your reply. here's my code
>
var authenticationHeader = GenerateAuthenticationHeader();
var OpportunityID = crmForm.all.opportunityid.DataValue[0].id;
var varFields = "<opportunityid>"+ OpportunityID +"</opportunityid>"
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'>"+
authenticationHeader+
"<soap:Body>"+
"<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<entity xsi:type='quote'>"+
varFields +
"</entity>"+
"</Create>"+
"</soap:Body>"+
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Create");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result
var resultXml = xHReq.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
// Open new contact record if no errors.
else
{
var quoteid = resultXml.selectSingleNode("//CreateResult");
window.open("/sfa/quotes/edit.aspx?id={"+quoteid.nodeTypedValue+"}");
}
}
Kindly help me please.
I really need it badly.
Thank you very much.

Related

i cant read this xml file to my page. the function works, but xml is not read

This is my javascript code.
function getXmlData(){
var icode=document.getElementById("itemcodee").value;
alert(icode);
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "assets/itemdetail.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var items = TheDocument.childNodes[0];
// Retrieve each item in turn.
for (var i = 0; i < items.children.length; i++)
{
var item = items.children[i];
if(item==icode)
{
// Access each of the data values.
var code = item.getElementsByTagName("code");
var name = item.getElementsByTagName("name");
var stock = item.getElementsByTagName("stock");
// print these values to corresponding field
document.getElementById("itemnamee").value=name;
document.getElementById("itemstock").value=stock;
alert(code+'|'+name+'|'+stock)
}
else
{
alert('Sorry, Item Not Found. Please check the inventory');
}
}
}
and here is my xml
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<item><code>1</code><name>Sample Item</name><stock>0</stock></item>
<item><code>3</code><name>ITEM</name><stock>205000</stock></item>
<item><code>4</code><name>ABHI UPDATED</name><stock>2201</stock></item>
<item><code>5</code><name>Item 5</name><stock>10</stock></item>
<item><code>6</code><name>item 6</name><stock>2130</stock></item>
<item><code>7</code><name>Soap</name><stock>100</stock></item>
<item><code>8</code><name>New Item</name><stock>1201</stock></item>
</xml>
when i enter a data(icode here) i want the script to read related data from this xml file and display it on corresponding texbox.
i'm stuck with this for a pretty long time. i have tried various solutions,but still no luck.
Try this
var item = items.children[i];
var theCode = item.getElementsByTagName("code").html;
if(theCode==icode)
{
...
} else {
...
}

How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});

Retrieving JSON data from API

I am trying to get a very simple Stock API to work on JSFiddle.net using Quandl API: https://www.quandl.com/blog/api-for-stock-data
If I use the current ".csv" format as below, I am returned a CSV file. If I change the format to ".json" in my API, how do I recover the data so that I can use it on a website for example?
I believe I need to use a getJSON command, but I am confused as to how it works. Can someone help me out?
HTML:
<input type="text" id="symbol">
<button id="getPrice">Get Price!</button>
<div id="result">Stock Market Ticker</div>
JavaScript:
function getPrice() {
var symbol = $("#symbol").val();
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var stock = symbol+".csv";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var url = baseurl+ stock + "?" + endurl;
$("#result ").html("<a href = '" + url + "' >Hyperlink</a>");
}
$("#getPrice ").click(getPrice);
My OUTPUT using stock ticker KORS (.CSV file) is: Data Close
1/5/2016 40.72
I've recently answered to "How do I use a Quandl API?" with the following snippet, which you should adapt for your JSON:
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var quandlcode = "KORS"; // if is it's your choice?
var url = baseurl + quandlcode + ".json?" + endurl; // dont forget the "?"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
var data = JSON.parse(this.responseText).dataset.data;
// {}.dataset.data is the data matrix in Quandl
// for most datasets as far as I know ...
// then process your own way
}
xhr.send();

Load a JavaScript event the last in CRM form

I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.

Store textarea.value via settimer-function to MySQL database without losing newlines

In the website EasyNote I have got a problem with newlines.
On body onload I set a timer for auto-uploading a note every 3 seconds like this:
<body onload="setInterval(uploadNote,3000);current = 1;">
And the code for uploadNote is:
function uploadNote() {
var note = current+document.getElementById(\'note\').value; //current is the number of the note selected\' because echoed
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){}
}
xmlhttp.open("GET","uploadnote.php?q="+note,true);
xmlhttp.send();
}
And then there is this php-code:
$note = $_GET["q"]; //contains both notenumber as first digit and note
echo($note."\n"); //for debugging reasons
$notenumber = substr($note, 0, 1);
$notecontent = substr($note, 1, strlen($note));
$notecontent = str_replace("'","''",$notecontent);
$notecontent = nl2br($notecontent);
echo($notecontent); //for debugging reasons
$request = 'UPDATE notes SET note'.$notenumber.' = "'.$notecontent.'" WHERE mail LIKE "'.$email.'"';
$result = mysql_query($request);
Now, the problem is, that the newline characters in the textarea are erased completely, so the result of the php-snippet is twice the text without newlines and in the database also.
However, there is no problem showing newlines in the textarea when I insert them directly in the database.
Help would be greatly appreciated.
EDIT:
updated uploadNote() function:
function uploadNote() {
var note = current+document.getElementById(\'note\').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){}
}
xmlhttp.open("POST","uploadnote.php",true);
xmlhttp.send("note="+note);
}
and php:
$note = $_POST["note"];
echo($note."\n");
$notenumber = substr($note, 0, 1);
$notecontent = substr($note, 1, strlen($note));
$notecontent = mysql_real_escape_string($notecontent);
echo($notecontent);
$request = 'UPDATE notes SET note'.$notenumber.' = "'.$notecontent.'" WHERE mail LIKE "'.$email.'"';
$result = mysql_query($request);
Problem now is that nothing works. The note won't update in the MySQL db.
The problems with your code:
Don't use a GET request for something that changes things on the server, use POST.
Database queries need the variable parts escaped. Use mysql_real_escape_string() on the value that is written to SQL.
Do not use any html-centric formatting when saving data to the database. You can use it when outputting the code back to the browser.
Inside a textarea, you are not allowed to use any HTML markup, so using <br> for a newline is wrong.

Categories