How to Create Relationship Between Contact and Account SugarCRM javascript - javascript

Hi can somebody help me? I am new in programing with Javascript and I need to set a Contact to Account Relationship.
function SetRelationContact_Account(){
$.get(CurrentServerAddress + '/service/v2/rest.php', {
method: "set_relationship",
input_type: "JSON",
response_type: "JSON",
rest_data: '{"session":"' + SugarSessionId +
'","module_name":"Contacts","module_id":"' + CurrentContactId +
'","link_field_name":"accounts","related_ids":["session":"' + SugarSessionId +
'"]}'
}, function(data) {
if (data !== undefined) {
var addAccountResult = jQuery.parseJSON(data);
}
});
}
I tried to create new Contact and I want to set a Relationship with an existing Account.
At jmertic's suggestion, I tried the following, but it still didn't work:
function SetRelationContact_Account(){
$.get(CurrentServerAddress + '/service/v2/rest.php', {
method: "set_relationship",
input_type: "JSON",
response_type: "JSON",
rest_data: '{"session":"' + SugarSessionId + '","module_name":"Contacts","module_id":"' + CurrentContactId + '","link_field_name":"accounts","related_ids":["name":"account_id","value":"' + CurrentAccountId + '"]}'
}, function(data) {
if (data !== undefined) {
var addAccountResult = jQuery.parseJSON(data);
}
});
}

"related_ids" should be the Account Id of the record you are relating to, and should be in the form of a javascript array.

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "System Administrator") {
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

jQuery Loader on a Ajax request [duplicate]

This question already has answers here:
Add a loading animation to jquery ajax .load()
(5 answers)
Closed 8 years ago.
I am creating an application in Node, which pulls objects in my Schema (Mongo) and presents them in HTML. Okay, all right so far.
Now I need to create a jQuery loader, which features a picture like this while the objects do not appear in the html -> http://i.imgur.com/hq37Dew.gif while the data does not appear.
$.ajax({
type: 'GET',
url: host + '/datas',
success:function(datas) {
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
How I can do this?
$.ajax({
$(".datas").empty().html('<img src="http://i.imgur.com/hq37Dew.gif" />'); // SHOW THE AJAX LOADER
type: 'GET',
url: host + '/datas',
success:function(datas){
$(".datas").html(datas); // this will hide the loader and replace it with the data
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
I think this is it.
Assuming that you give the image an id of image_id ,
$.ajax({
type: 'GET',
url: host + '/datas',
beforeSend: function(){
// Code to show the image . e.g.
$('#image_id').show();
},
success:function(datas) {
// Code to hide image again / completely make it display-none
$('#image_id').hide // or $('#image_id').css("display","none");
reservas.forEach (function (data) {
// ........
})
}
});
$.ajax({
type: 'GET',
url: host + '/datas',
beforeSend: function() {
// Add loader here
$(placeholder).addClass('loading');
},
complete: function() {
//hide loader here/
$(placeholder).removeClass('loading');
},
success:function(datas){
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
hope this works

Returning Response in jquery ajax function

Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.

How to get the ID of the user who is logged into the current session?

I need to find the user who is logged into the current session. I tried the following but does not work:
Can anyone help me? Thanks in advance!
$.get(CurrentServerAddress + '/service/v4/rest.php', {
method: "get_user_id",
input_type: "JSON",
response_type: "JSON",
rest_data:'"new_get_user_id":["session":"' + SugarSessionId + '"]'
}, function(data) {
if (data !== undefined) {
var userID = jQuery.parseJSON(data);
}
});
I tried the following and it works for me.
var userID = '';
$.get(CurrentServerAddress + '/service/v4/rest.php', {
method: "get_user_id",
input_type: "JSON",
response_type: "JSON",
rest_data: '[{"session":"' + SugarSessionId + '"}]'
}, function(data) {
if (data !== undefined) {
userID = jQuery.parseJSON(data);
}
});
'authenticated_user_id'
As far as I'm aware that is the sugar crm item in session which you should be looking for, are you requesting that?
The REST call that you are making requires that you have a SESSION token. Normally, we will setup a REST user on our CRM's that can be accessed via REST.

Categories

Resources