How update data by Javascript - javascript

How can I, on the OnChange event, update data in my database ?
I have a WebMethod, that returns a HTML, so I can't see those elements, so I think he solution will be a javascript function.
A textarea catch the text from the database, if the user alter this, the database field has to be updated.
[WebMethod]
public static object ListAdvertise(string transaction)
{
StringBuilder retorno = new StringBuilder(160000);
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
string Credenciada = tk2.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value);
string select3 = "SELECT * FROM San_Imovel WHERE Status_Id = 1 AND Credenciada_Id = " + Credenciada + " AND Transacao_Id IN (" + transacao + ") ORDER BY NomeCidade, NomeBairro, Imovel_Id ASC";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
Imovel_Id = r3["Imovel_Id"].ToString();
Endereco = r3["Descricao"].ToString() + " " + r3["Logradouro"].ToString() + " " + r3["Numero"].ToString() + "/" + r3["DscComplemento"].ToString() + " " + r3["Complemento"].ToString() + " - " + r3["NomeBairro"].ToString();
TextoAnuncio = r3["TextoAnuncio"].ToString();
if (count % 2 == 0)
{
classe = "EstiloDalinhaGrid";
}
else
{
classe = "EstiloDalinhaAlternativaGrid";
}
retorno.Append("<tr class='" + classe + "'>");
retorno.Append("<td>");
retorno.Append(Imovel_Id);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append(Endereco);
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<textarea id='txtArea'>");
retorno.Append(TextoAnuncio);
retorno.Append("</textarea>");
retorno.Append("</td>");
retorno.Append("<td>");
retorno.Append("<input type='checkbox' class='imoveisMarcados' id='" + Imovel_Id + "' />");
retorno.Append("</td>");
retorno.Append("</tr>");
count++;
}
retorno.Append("</table>");
con3.Close();
return new
{
retorno = string.Format(retorno.ToString())
};

i think you have to use Ajax for you to be able to update your data base .
check this link to learn more about ajax with Php (you chose whatever server side langage you'd like)
Ajax with PHP

Related

Continue with the attribute to the next requested page

Initially a table full of values are posted, and a column with the drop button is available using javascript coding. When I click the drop button, a dialog pops up with yes or no, if I click yes, I want that specific order to be transferred to another servlet (/drop). This is the order page (/order) with all the orders. How do I move the order from this page (/order) to the drop page (/drop) and delete that specific order from the /order page?
This is what I did, and I get errors.
(/order)
HttpSession session = request.getSession();
if (session.getAttribute("user_name") != null) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Payroll", "root", " ");
String userName = (String) session.getAttribute("user_name");
PreparedStatement ps = con.prepareStatement("SELECT * from Payroll.Order order by delDate asc");
ResultSet rs = ps.executeQuery();
out.println("<script type=\"text/javascript\">"
+ "function getConfirmation(){"
+ "var retVal = confirm(\"Add to Drop List?\");"
+ "if( retVal == true ){"
+ "document.location=\"DvDrop\";"
+ "return true;"
+ "}"
+ "else{"
+ "document.location=\"DvOrders\";"
+ "return false;"
+ "}"
+ "}"
+ "</script>" );
out.println(<strong>Welcome " + session.getAttribute("user_name") + "</strong>");
out.println("<br><h2><center><b>Order List</b></center></h2><br><table border=\"1\" style=\"width:100%;border-spacing: 0.5em;text-align: center;\">");
out.println("<tr><td><b>Order ID</b></td><td><b>Ordered Date</b></td><td><b>Ordered Time</b></td><td><b>Total Amount</b></td><td><b>Delivery Date</b></td><td><b>Add to Drop List</b></td></tr></b>");
while (rs.next()) {
out.println("<tr><td>"+ rs.getString(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getTime(3) + "</td><td>" + rs.getDouble(4) + "</td><td>" + rs.getDate(5) + "</td>");
out.println("<td>" + "<input type=\"button\" value=\"Add to Drop\" name=\"AddDrop\" onClick=\"getConfirmation()\">" + "</td></tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
} else {
response.sendRedirect("login.jsp?id=Your session may be expired. You have to login first");
}
} catch (Exception e) {
out.println(e);
}
}
(/drop)
PrintWriter out = response.getWriter();
try {
// PrintWriter out = response.getWriter() ;
HttpSession session = request.getSession();
if (session.getAttribute("user_name") != null) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Payroll", "root", " ");
String userName = (String) session.getAttribute("user_name");
String order = (String)session.getAttribute("Orderid");
PreparedStatement ps = con.prepareStatement("delete * from Payroll.Order where Orderid = '" + order + "'");
ResultSet rs = ps.executeQuery();
}
} catch (Exception e) {
out.println(e);
}
I'm assuming that you're getting Java compilation errors in your code. If your code for /order servlet is the same as you've posted here, then, in your code's
out.println(<strong>Welcome " + session.getAttribute("user_name") + "</strong>");
there's an error. You have not defined the string correctly for HTML to be sent to the browser. You need to use a double quotes before the <strong> tag, which seems to be causing the Illegal start of expression error
Try this.
HttpSession session = request.getSession();
if (session.getAttribute("user_name") != null) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Payroll", "root", " ");
String userName = (String) session.getAttribute("user_name");
PreparedStatement ps = con.prepareStatement("SELECT * from Payroll.Order order by delDate asc");
ResultSet rs = ps.executeQuery();
out.println("<script type=\"text/javascript\">"
+ "function getConfirmation(id){"
+ "var retVal = confirm(\"Add to Drop List?\");"
+ "if( retVal == true ){"
+ "document.location=\"DvDrop?Orderid=" + id + "\";"
+ "return true;"
+ "}"
+ "else{"
+ "document.location=\"DvOrders\";"
+ "return false;"
+ "}"
+ "}"
+ "</script>" );
out.println("<strong>Welcome " + session.getAttribute("user_name") + "</strong>");
out.println("<br><h2><center><b>Order List</b></center></h2><br><table border=\"1\" style=\"width:100%;border-spacing: 0.5em;text-align: center;\">");
out.println("<tr><td><b>Order ID</b></td><td><b>Ordered Date</b></td><td><b>Ordered Time</b></td><td><b>Total Amount</b></td><td><b>Delivery Date</b></td><td><b>Add to Drop List</b></td></tr></b>");
while (rs.next()) {
out.println("<tr><td>"+ rs.getString(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getTime(3) + "</td><td>" + rs.getDouble(4) + "</td><td>" + rs.getDate(5) + "</td>");
out.println("<td>" + "<input type=\"button\" value=\"Add to Drop\" name=\"AddDrop\" onClick=\"getConfirmation(\'" + rs.getString(1) + "\')\" />" + "</td></tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
} else {
response.sendRedirect("login.jsp?id=Your session may be expired. You have to login first");
}
} catch (Exception e) {
out.println(e);
}
Here, since you need to add a specific item to the drop list, I would suggest creating the button in such a way that when you click it, it sends the ID of the order to be dropped. The proposed change has been made in the above code. What I'm doing there is sending the current order's ID as an argument to the function getConfirmation(). If you want, you can see the final HTML content that is generated using your browser's inspect tool. You'll see that each button calls the same function, but with the corresponding order ID
Also, in your /drop servlet, you're trying to perform data manipulation (insert/update/delete), but you're using the executeQuery() method for it. Instead, try using the executeUpdate(), something like this
PrintWriter out = response.getWriter();
try {
// PrintWriter out = response.getWriter() ;
HttpSession session = request.getSession();
if (session.getAttribute("user_name") != null) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Payroll", "root", " ");
String userName = (String) session.getAttribute("user_name");
//String order = (String)session.getAttribute("Orderid");
String order = Integer.parseInt(request.getParameter("Orderid"));
PreparedStatement ps = con.prepareStatement("delete * from Payroll.Order where Orderid = '" + order + "'");
int rs = ps.executeUpdate();
}
} catch (Exception e) {
out.println(e);
}
Apart from this, in your JavaScript code, you're assigning a new location to the window, and immediately after that, you're trying to return something. The moment you assign a new location to the document, the current script ends there, and the new web page's script starts executing.
I've proposed some changes to your JavaScript code as well. They're in the first code snippet. Hope this helps!
Cheers!

getting undefined value:app script

Here, i am trying to send a mail to replyEmail specified below. But it is giving as undefined value. Why its happening even though i am giving correct email id in google form? Some times its coming correct. But for another time its giving as undefined value.
function sendEmail(e) {
/**
var email = e.values[1];
var item = e.values[2];
var cost = e.values[3];
*/
var serviceInformation = e.values[1],
language = e.values[2],
meetingType = e.values[3],
eventDate = e.values[4],
clientName = e.values[5],
detailedDirections = e.values[6],
onSitePOCName = e.values[7],
onSitePOCNumber = e.values[8],
department = e.values[9],
contactPhoneNumber = e.values[10],
approval = e.values[11]; //the one we need to modif,
requestorEmail = e.values[12],
managerEmail = e.values[13],
Language2 = e.values[14],
interpreterName = e.values[15],
interpreterAgency = e.values[16],
dateConformationSent = e.values[17],
specialNotes = e.values[18];
var url = 'https://script.google.com/a/macros/richmond.k12.va.us/s/AKfycbwuRr1boKTH0v1mprWmc7PE66_mQ_dmPE0lyWb7vkfiyW3pn31b/exec';
// might be that the & needs to be a ?
var approve = url + '?approval=true' + '?reply=' + requestorEmail;
var reject = url + '?approval=false' + '?reply=' + requestorEmail;
var html = "<HTML><body>"+
"<h2>please review</h2><br />"
+"<P>" + language +" " + serviceInformation
+"<p>" + meetingType+ " on "+ eventDate + " for " +clientName
+"<p>" + "Location: "+ department
+"<p>" + "requester: "+ requestorEmail+ " "+
"<p>"+
"Approve<br />"+
"<p>"+
"Reject<br />"+
"</HTML></body>";
var html = [
"<html>",
"<body>",
"<h2>please review</h2> <br/>",
"<p>" + language +" " + serviceInformation,
"<p>" + meetingType + " on " + eventDate + " for " + clientName,
"<p>Location: " + department,
"<p>Requester: " + requestorEmail,
"<p>Approve<br/>",
"<p>Reject<br />",
"</body>",
"</html>";
].join('');
MailApp.sendEmail(managerEmail, "Approval Request", "what no html?", {
htmlBody: html
});
}
function doGet(e) {
var app = UiApp.createApplication(),
aprovalResponce = (e.parameter.approval == 'true') ? 'Approved.' : 'Sorry, you need to reschedule',
msg = "Your manager said :" + aprovalResponce;
var replyEmail = e.parameter.reply; // !!!
Logger.log(replyEmail);
MailApp.sendEmail(replyEmail, "Approval Request", msg);
var helloWorldLabel = app.createLabel(msg);
app.add(helloWorldLabel);
return app;
}
Its because space is not accepted while parsing the data in google script.It should be encoded and then the data is to be send.It can be encoded using encodeURIcomponent().

How to return a value in the only non-blank column in a range for sendEmail function in Google App Scripts

The issue is: I can't find a way to return the value for 'Course' because each form submission generates a new row where the name of the course is spread over columns E to M (column 4 through 12).
In each row, there is only one 'Course' name in one of the columns from E to M (e.g only in F) and all other columns are blank. (Users can only select one course and all the other columns will be blank. I have to categorize the courses into the 9 columns because of the page breaks in order to split the sheer number of options that users select the course from.) How do I return the value of the only non blank cell from E to M which will be entered in the email ?
I was advised to insert the entire findCourse function inside of the sendEmail function before any of the other code. I did so but I have still been receiving failure notifications of the Google App Scripts: TypeError: Cannot read property "values" from undefined. (line 14, file "Code") (referring to var value = e.values[i])
The full code below:
function sendEmail(e) {
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
}
var Name = e.namedValues["Full name as appear in NRIC"];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
After rearranging findCourse as its own function: sorry if I made any mistakes here but i'll try my best to follow all suggestions. If i've added in Logger.log(e) correctly, both functions seem to be undefined
function sendEmail(e) {
Logger.log(e);
var Name = e.values[2];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
var courseToTake = findCourse(e);
Logger.log(e);
}
I will really deeply appreciate any help or alternative solutions here.
Thank you!
What I changed in your code to address your question:
I assigned the onFormSubmit trigger to your sendEmail function so the event object would no longer be undefined
I added a call to findCourse() so your course variable would no longer be undefined
I fixed the undefined check by changing if(value != undefined) to if(typeof value !== 'undefined')
I added a check for a blank value (This was the important bit in the logic after the faulty undefined check) if(value != '')
Explanation:
To trigger the event, an installable trigger needs to be setup for the On Form Submit event that points to your sendEmail function. This can be found in Resources -> Current Project Triggers
To retrieve the course, you need to call your function findCourse() and pass in the e event object. Example: var course = findCourse(e);. This will assign the return value from findCourse(e); to the course variable. You can then use this variable like normal within the rest of your statements.
When checking for undefined, you need to use typeof and then check for the string of 'undefined', or your check will ironically throw an undefined exception.
The values of the form submit should not be undefined, blank values should just be blank strings. so checking for non-blank strings was necessary to get the course name from the values array.
Fixed Code:
function sendEmail(e) {
Logger.log(e)
var course = findCourse(e);
var Name = e.values[19];
var Start = e.values[12];
var End = e.values[14];
var StartTime = e.values[13];
var EndTime = e.values[15];
var Details = e.values[11];
var Cost = e.values[17];
var Email = e.values[20];
var ROname = e.values[21];
var ROemail = e.values[22];
var Location = e.values[16];
var subject = "Training Approval Request for " + course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email+";" + "redactedEmail", subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 2; i <=10; i ++){
//pull value into variable
var value = e.values[i];
if (typeof value !== 'undefined'){ //If value is defined
if(value != ''){ //If value is not blank
//if we find an actual non-blank string value, set the course to take variable
courseToTake = value;
}
}
}
return courseToTake;
}

How to "postMessage" to host from within pdf when viewed in IE9 object element

I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}

dynamics crm 4.0 lookup field onload() query

I have an account entity with a lookup field schoolLookupId which refers back to a custom entity new_schools. The lookup field only display the name of the school. What I would like to be able to do using the onload() event handler of the account form is to run some javascript code that will query the new_phonenumber attribute of the new_schools entity to see if it matches a value i provide lets say var x = "1234" and if it does then update schoolLookupId accordingly with the name of the school that corresponds with the found phone number. i.e update the lookup field with a phone number that already exists without creating a completely new lookup value.
I can get the attributes of the lookupfield using
var name = crmForm.all.schoolLookupid.DataValue[0].name
var id = crmForm.all.schoolLookupid.DataValue[0].id
var typename = crmForm.all.schoolLookupid.DataValue[0].typename
but I can't figure out how to retrieve, compare the data that lies behind the lookup field, and update the lookupfield accordingly.
Your help as always is invaluable.
Try put this code in load event:
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\">" +
GenerateAuthenticationHeader() +
" <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>new_schools</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>new_schoolsid</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>new_phonenumber</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">"+crmForm.all.new_phonenumber.DataValue+"</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", "http://"+window.location.hostname+":"+window.location.port+"/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.xml.search('<q1:new_schoolsid')>0)
{
var val = xmlDoc.getElementsByTagName("q1:new_schoolsid")[0].childNodes[0].nodeValue;
var lookupitem = new Array();
lookupitem[0] = new LookupControlItem(val , typecode, name);
crmForm.all.schoolLookupid.DataValue = lookupitem ;
}
}
I don't try this code be careful. Use this code as a guide.
Hope this helps.
If i answered your question, please mark the response as an answer and also vote as helpful.

Categories