CRM 2011 Retrieving lookup - dynamics-crm-2011

I'm new in CRM development. I know a basic thing like "best practice for crm 2011"
I wanna understand now how to work with lookup fields. And I think I chose the easiest way for my self.
I have an costum entity "contract" it has 5 more field, 2 of these are lookups.
First lookup (agl_contractId) - it is a link by it self
Second lookup (agl_ClientId) - link to Client.
What do I need?
When I choose fill First lookup (agl_contractId), script should find in this contract a Client and copy-past it to current form.
I've done script but it isn't work... (((
function GetAccountFromContract()
{
XrmServiceToolkit.Rest.Retrieve(Xrm.Page.getAttribute("agl_osnovnoy_dogovorid").getValue(),
'agl_osnovnoy_dogovoridSet',
null,null,
function (result) {
var Id = Xrm.Page.getAttribute("agl_osnovnoy_dogovorid").getValue();
if (result.Id != null) {
var LookupData = new Array();
var LookupItem = new Object();
var lookuptextvalue = lookupvalue[0].name;
var lookupid = lookupvalue[0].id;
var lokupType = lookupvalue[0].entityType;
alert(lookupvalue);
alert(lookupData);
Xrm.Page.getAttribute("agl_accountid").setValue(lookupData);
}
},
function (error) {
equal(true, false, error.message);
},
false
);
}

If I understand you well: When you select Contract in agl_osnovnoy_dogovorid field, you want to pull Client property from that Contract and put it in agl_accountid field?
If that is right:
First, get Id of selected Contract (from agl_osnovnoy_dogovorid field)
var selectedContract = new Array();
selectedContract = Xrm.Page.getAttribute("agl_osnovnoy_dogovorid").getValue();
{
var guidSelectedContract = selectedContract[0].id;
//var name = selectedContract[0].name;
//var entType = selectedContract[0].entityType;
}
Second, retrieve Client from agl_osnovnoy_dogovorid. Your oData query will be like:
http://crmserver/org/XRMServices/2011/OrganizationData.svc/ContractSet(guid'" + guidSelectedContract + "')/CustomerId
(In example I'm using CustomerId field. For your case enter Schema Name of Client field).
Now, execute query and put result into agl_accountid field:
$.getJSON(
Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContractSet(guid'" + guidSelectedContract + "')/CustomerId",
function(data){
if(data.d.CustomerId != null && data.d.CustomerId.Id != null && data.d.CustomerId.Id != "undefined")
{
//set agl_accountid field
Xrm.Page.getAttribute("agl_accountid").setValue([{id:data.d.CustomerId.Id, name:data.d.CustomerId.Name, typename:data.d.CustomerId.LogicalName}]);
}
});

Your using REST to retrieve data but also using FetchXml example to setup the agl_accoutid lookup.
Also some of the conditions are not clear … anyway … I’ve incorporated the change to your original post.
function GetAccountFromContract()
{
var aodLookupValue = Xrm.Page.getAttribute("agl_osnovnoy_dogovorid").getValue();
if (!aodLookupValue) return;
XrmServiceToolkit.Rest.Retrieve( aodLookupValue[0].id ,
'agl_osnovnoy_dogovoridSet', null,null,
function (result) {
var customer = result.d["your attribute name"];
if (customer) {
var LookupData = new Array();
var LookupItem = new Object();
var lookuptextvalue = customer.Name;
var lookupid = customer.Id;
var lokupType = customer.LogicalName;
alert(lookupvalue);
alert(lookupData);
Xrm.Page.getAttribute("agl_accountid").setValue(lookupData);
}
},
function (error) {
equal(true, false, error.message);
}, false );
}

Related

NetSuite:I want to edit a savedSearch and saved it.But the filters of the savedSearch is null

The suitescript 1.0 code as follow:
function clientFieldChanged(type, name, linenum) {
if (name == 'class') {
var brand_id = nlapiGetFieldValue('class');
if (brand_id) {
console.log(brand_id);
var itemSearch = nlapiLoadSearch(null,'customsearch_item_brand_search');
var itemSearchFilter = new nlobjSearchFilter('custitem30', null, 'anyof',brand_id);
var filters = [itemSearchFilter];
itemSearch.setFilters(filters);
itemSearch.saveSearch();
}
}
}
But after this script is executed,the filters of the saved search is null.SuiteScript 1.0 saved Search
The suitescript 2.0 code as follow:
function fieldChanged(scriptContext) {
if(scriptContext.fieldId == 'class'){
var currentRecord = scriptContext.currentRecord;
var brand_id = currentRecord.getValue({fieldId:'class'});
if(brand_id){
var itemSearch = search.load({
id: 'customsearch_item_brand_search'
});
var itemSearchFilter = search.createFilter({
name:'custitem30',
operator:search.Operator.ANYOF,
values:brand_id
});
var filtersArray = [itemSearchFilter];
itemSearch.filters = filtersArray;
itemSearch.save();
}
}
}
After this script is executed,the filters of the saved search is right.SuiteScript 2.0 saved Search
What can I do to make the SuiteScript 1.0 saved Search same as the SuiteScript 2.0 saved Search?
By the way,nlapiRefreshLineItems is the api of suitescript 1.0,but there is no equivalent in version 2.0.If I want refresh item only in suitescript 2.0,how to do it?
In the 1.0 code change setFilters() to addFilters() so your code should be:
function clientFieldChanged(type, name, linenum) {
if (name == 'class') {
var brand_id = nlapiGetFieldValue('class');
if (brand_id) {
console.log(brand_id);
var itemSearch = nlapiLoadSearch(null,'customsearch_item_brand_search');
var itemSearchFilter = new nlobjSearchFilter('custitem30', null, 'anyof',brand_id);
var filters = [itemSearchFilter];
itemSearch.addFilters(filters);
itemSearch.saveSearch();
}
}
}
This works for me, while the setFilters threw an error.
Why not?
Load the search
Get the type/columns/filters
Modify the filters
Create another search
Use the previous config
That should work.

Display of "is not a valid internal id" in Netsuite Suitescript 1.0 when creating a Search on a particular record

I have created a search in Netsuite using Suitescript 1.0 for searching a particular "Account" using its account number. When I save the following script file, an error is being displayed in "filters[0]" line in the code below, where it says "acctnumber is not a valid internal id.". I am new to Netsuite and would want to know why the error is being displayed, and the solution for the same. Below is the following piece of code written in which the error is being occured.
function COGSAcnt() {
var cOGSAcntNumber = '50001';
var acntNo;
var filters = new Array();
filters[0] = new nlobjSearchFilter('acctnumber', null, 'startswith', cOGSAcntNumber);
var columns = new Array();
columns[0] = new nlobjSearchColumn('internalid');
var acntSearch = nlapiSearchRecord('account', null, filters, columns);
if (acntSearch != null) {
for (x=0; x<acntSearch.length; x++) {
acntNo = ITMSearch[x].getValue('internalid');
}
}
nlapiLogExecution('debug', 'acntNo', acntNo);
return acntNo;
}
NOTE: I want the filter to be acctnumber (Account Number), and using that would want to retrieve the internalid of the account in Netsuite.
This is where NS can be a little confusing. If you look at the NS Record browser (http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_2/script/record/account.html) look under the Filters section. Account Number (acctnumber) isn't there. However Number (number) is the filter.
Try rewriting the code to use number instead
function COGSAcnt() {
var cOGSAcntNumber = '50001';
var acntNo = [];
var filters = new nlobjSearchFilter('number', null, 'startswith', cOGSAcntNumber);
var acntSearch = nlapiSearchRecord('account', null, filters, columns);
if (acntSearch != null) {
for (x=0; x<acntSearch.length; x++) {
acntNo.push(ITMSearch[x].getId();
}
}
return acntNo;
}

Wants to search the fileld value from Contract record in Purchase order record

I was searching for a value from contract record in Purchase record but i am unable to get the field where the value is. Below is the code for that. I am applying this code for the contract record and the function is for before submit.
I think I am applying the search in wrong way.
function srchfield()
{
var recordid = nlapiGetRecordId() //retunrs the contract id
nlapiLogExecution('DEBUG', 'recordid ', recordid );
var recordtype = nlapiGetRecordType(); //retunrs the contract recordtype = jobs
nlapiLogExecution('DEBUG', 'RecordType', recordtype);
var loadrecord = nlapiLoadRecord(recordtype, recordid); //loads the record
nlapiLogExecution('DEBUG', 'Load Record', loadrecord );
var contractname = nlapiGetFieldValue('entityid'); //returs the value of the field contractname whose fieldid is = entityid
nlapiLogExecution('DEBUG', 'ContractName ', contractname );
var filters = new Array();
new nlobjSearchFilter('entityid', null, 'anyof', contractname ); // entityid is field id in contract Record and contractname is defined above for contract record
// nlapiLogExecution('DEBUG', 'SearchFilter', filters );
var columns = new Array();
new nlobjSearchColumn('custbodycontract'); // custbodycontractis field id in PO Record
var searchresults = nlapiSearchRecord('purchaseorder', null, filters, columns);
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
var record = searchresult.getId( );
var rectype = searchresult.getRecordType( );
var cntrct_name= searchresult.getValue( 'custbodycontract' );
}
}
Thanks in advance
****Update: I have completed my answer based on the comments provided. Please see at the last section. I hope it helps. Thanks!***
**I might provide you the snippet if you will explain this further. Please advise
If I understand correctly your code, these are what you are doing and you want to do:
Your contract record is the native entity record - project/job. It had just been renamed to contract by your functional consultant.
You have an user event script (SuiteScript 1.0) before submit and deployed to the contract (project/job) record.
Using the information from the contract record (in this case using the contract name (entityid), you wanted to search for POs to get 'custbodycontract' at the header.
Then you are filtering the search on POs using "entityid" but PO doesnt have that native field on the header. It only has it on the expense line and item line but the id is 'customer'.
Can you explain how is the contract record related to PO. Which field (native/custom) is available on PO that can be used as a join on contract record?
Then, please take note this best practice as freebie.
To optimize your script. You don't need to use nlapiLoadRecord on beforesubmit. Please see below the best practice.:
- With beforesubmit and if you are only getting or setting values on the script deployed record, use nlapiGet** and nlapiSet** API.
- On beforesubmit, only use nlapiLoadRecord if you are getting and setting the value on the sublist of a different record. But utilize first nlapiSearchRecord if you are only getting value at the line level (different record). If it will not give what you need, use nlapiLoadRecord.
- On aftersubmit, only use nlapiLoadRecord if you are setting and getting value at the line level of the deployed record and different record. If you are only getting value at the level, same practice with beforesubmit.
- On aftersubmit, use nlapiLookUp for getting value from the header, and nlapiSubmitField if you are setting. Only use nlapiLoadRecord if it doesnt give you what you need.
****This might what you need...
function srchfield()
{
var stRecordid = nlapiGetRecordId(); /*retunrs the contract id*/
nlapiLogExecution('DEBUG', 'recordid ', stRecordid);
var stRecordtype = nlapiGetRecordType(); /*retunrs the contract recordtype = jobs*/
nlapiLogExecution('DEBUG', 'RecordType', stRecordtype);
var stContractname = nlapiGetFieldValue('entityid'); /*returs the value of the field contractname whose fieldid is = entityid*/
nlapiLogExecution('DEBUG', 'ContractName ', stContractname);
var arrFilters = new Array();
arrFilters.push(new nlobjSearchFilter('type', null, 'anyof',
[
'PurchOrd'
])); /*As best practice, instead of directly searching on POs, add filter for transaction type since you might use this later in other transaction.*/
arrFilters.push(new nlobjSearchFilter('mainline', null, 'is', 'T')); /*This is to exclude line level results*/
arrFilters.push(new nlobjSearchFilter('custbodycontract', null, 'is', stContractname));
var arrColumns = new Array();
arrColumns.push(new nlobjSearchColumn('trandate')); /*I just wanted to include this column on the result. :)*/
arrColumns.push(new nlobjSearchColumn('type')); /*I just wanted to include this column on the result. :)*/
arrColumns.push(new nlobjSearchColumn('tranid')); /*I just wanted to include this column on the result. :)*/
arrColumns.push(new nlobjSearchColumn('custbodycontract')); /*This is what you need.*/
var arrSearchresults = nlapiSearchRecord('transaction', null, arrFilters, arrColumns);
for (var i = 0; arrSearchresults != null && i < arrSearchresults.length; i++)
{
var objResult = arrSearchresults[i];
var stRecId = objResult.getId();
var stRecType = objResult.getRecordType();
var stCntrctName = objResult.getValue('custbodycontract');
}
The problem I notice on your code is the creation of the filter.
You instantiated nlobjSearchFilter but you didn't push it in an array. So basically, you are searching without filter.
And I believe your search criteria were complete.
Try below codes. By the way make sure that the field type of custbodycontract is a freeform text to properly compare it with the entityid of the contract record.
function srchfield()
{
var stRecordid = nlapiGetRecordId(); /*retunrs the contract id*/
nlapiLogExecution('DEBUG', 'recordid ', stRecordid);
var stRecordtype = nlapiGetRecordType(); /*retunrs the contract recordtype = jobs*/
nlapiLogExecution('DEBUG', 'RecordType', stRecordtype);
var stContractname = nlapiGetFieldValue('entityid'); /*returs the value of the field contractname whose fieldid is = entityid*/
nlapiLogExecution('DEBUG', 'ContractName ', stContractname);
var arrFilters = new Array();
arrFilters.push(new nlobjSearchFilter('type', null, 'anyof',
[
'PurchOrd'
])); /*As best practice, instead of directly searching on POs, add filter for transaction type since you might use this later in other transaction.*/
arrFilters.push(new nlobjSearchFilter('mainline', null, 'is', 'T')); /*This is to exclude line level results*/
arrFilters.push(new nlobjSearchFilter('custbodycontract', null, 'is', stContractname));
var arrColumns = new Array();
arrColumns.push(new nlobjSearchColumn('trandate')); /*I just wanted to include this column on the result. :)*/
arrColumns.push(new nlobjSearchColumn('type')); /*I just wanted to include this column on the result. :)*/
arrColumns.push(new nlobjSearchColumn('tranid')); /*I just wanted to include this column on the result. :)*/
arrColumns.push(new nlobjSearchColumn('custbodycontract')); /*This is what you need.*/
var arrSearchresults = nlapiSearchRecord('transaction', null, arrFilters, arrColumns);
for (var i = 0; arrSearchresults != null && i < arrSearchresults.length; i++)
{
var objResult = arrSearchresults[i];
var stRecId = objResult.getId();
var stRecType = objResult.getRecordType();
var stCntrctName = objResult.getValue('custbodycontract');
}
}

Creating dynamic customer group using suite script

I am trying to create dynamic customer group using suite script in Net suite, I am trying below code but always getting
system INVALID_KEY_OR_REF
Invalid savedsearch reference key 21.
I have checked it is valid save search, Please help I am doing something wrong.
function createDynamicGroup(savedSearchId, groupName) {
var saveSearchObj = nlapiLoadSearch('customer', savedSearchId);
var initValues = new Array();
initValues.grouptype = 'Customer';
initValues.dynamic = 'T';
var goupRecObj = nlapiCreateRecord('entitygroup', initValues);
goupRecObj.setFieldValue('groupname', groupName);
goupRecObj.setFieldValue('savedsearch',saveSearchObj.getId());
nlapiSubmitRecord(goupRecObj);
}
You need group type = 'CustJob' as well as using a public search id:
function createDynamicGroup(savedSearchId, groupName) {
var saveSearchObj = nlapiLoadSearch('customer', savedSearchId);
var initValues = {
grouptype: 'CustJob', // <-- use this
dynamic: 'T'
};
var goupRecObj = nlapiCreateRecord('entitygroup', initValues);
goupRecObj.setFieldValue('groupname', groupName);
goupRecObj.setFieldValue('savedsearch', savedSearchId);
return nlapiSubmitRecord(goupRecObj);
}

Sharepoint 2010 list creation using ecmascript

i am new to ECMAScript and share point development, i have small requirement i need to create one list using ECMAScript and while creation it has to check whether the list already exists in the site ,if list doesn't exist new list has to create.
You can use SPServices with "GetListCollection" to find all the lists in a Sharepoint, and then use "AddList" to create it.
Something like:
var myList="My List Test"; // the name of your list
var listExists=false;
$().SPServices({
operation: "GetListCollection",
async: true,
webURL:"http://my.share.point/my/dir/",
completefunc: function (xData, Status) {
// go through the result
$(xData.responseXML).find('List').each(function() {
if ($(this).attr("Title") == myList) { listExists=true; return false }
})
// if the list doesn't exist
if (!listExists) {
// see the MSDN documentation available from the SPService website
$().SPServices({
operation: "AddList",
async: true,
webURL:"http://my.share.point/my/dir/",
listName:myList,
description:"My description",
templateID:100
})
}
}
});
Make sure to read the website correctly, and especially the FAQ. You'll need to include jQuery and then SPServices in your code.
You could utilize JSOM or SOAP Services for that purpose, below is demonstrated JSOM solution.
How to create a List using JSOM in SharePoint 2010
function createList(siteUrl,listTitle,listTemplateType,success,error) {
var context = new SP.ClientContext(siteUrl);
var web = context.get_web();
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(listTitle);
listCreationInfo.set_templateType(listTemplateType);
var list = web.get_lists().add(listCreationInfo);
context.load(list);
context.executeQueryAsync(
function(){
success(list);
},
error
);
}
How to determine whether list exists in Web
Unfortunately JSOM API does not contains any "built-in" methods to determine whether list exists or not, but you could use the following approach.
One solution would be to load Web object with lists collection and then iterate through list collection to find a specific list:
context.load(web, 'Lists');
Solution
The following example demonstrates how to determine whether List exist via JSOM:
function listExists(siteUrl,listTitle,success,error) {
var context = new SP.ClientContext(siteUrl);
var web = context.get_web();
context.load(web,'Lists');
context.load(web);
context.executeQueryAsync(
function(){
var lists = web.get_lists();
var listExists = false;
var e = lists.getEnumerator();
while (e.moveNext()) {
var list = e.get_current();
if(list.get_title() == listTitle) {
listExists = true;
break;
}
}
success(listExists);
},
error
);
}
Usage
var webUrl = 'http://contoso.intarnet.com';
var listTitle = 'Toolbox Links';
listExists(webUrl,listTitle,
function(listFound) {
if(!listFound){
createList(webUrl,listTitle,SP.ListTemplateType.links,
function(list){
console.log('List ' + list.get_title() + ' has been created succesfully');
},
function(sender, args) {
console.log('Error:' + args.get_message());
}
);
}
else {
console.log('List with title ' + listTitle + ' already exists');
}
}
);
References
How to: Complete basic operations using JavaScript library code in SharePoint 2013

Resources