Xrm.Utility.openEntityForm setting Look Up field - javascript

I am attempting to use the Xrm.Utility.openEntityForm() method to open a new custom entity form and programatically set an entity look up field. I am following an example on http://msdn.microsoft.com/en-us/library/gg334375.aspx very closely but getting nondescript error. Any help with actually setting the field or possibly finding the logs for the error would be appreciated.
The code example I am following.
function OpenNewContact() {
var parameters = {};
//Set the Parent Customer field value to “Contoso”.
parameters["parentcustomerid"] = "2878282E-94D6-E111-9B1D-00155D9D700B";
parameters["parentcustomeridname"] = "Contoso";
parameters["parentcustomeridtype"] = "account";
//Set the Address Type to “Primary”.
parameters["address1_addresstypecode"] = "3";
//Set text in the Description field.
parameters["description"] = "Default values for this record were set programmatically.";
//Set Do not allow E-mails to "Do Not Allow".
parameters["donotemail"] = "1";
// Open the window.
Xrm.Utility.openEntityForm("contact", null, parameters);
}
The function I have created to do the same with my custom entity is as follows :
function createNewService() {
var locationId = trimBrackets(Xrm.Page.data.entity.getId());
var primaryField = Xrm.Page.data.entity.getPrimaryAttributeValue();
var entityLogicalName = Xrm.Page.data.entity.getEntityName();
var parameters = {
cw_location: locationId,
cw_locationname: primaryField,
cw_locationtype: entityLogicalName
};
Xrm.Utility.openEntityForm("cw_service", null, parameters);
}
the name of the entity I am opening a form work = cw_service (this isn't the problem as I can open a blank form with Xrm.Utility.openEntityForm("cw_service");)
the name of the field I am trying to set is cw_location.
I'd post a picture of the error message but I don't have the reputation yet to do that.

For simple lookups you must set the value and the text to display in the lookup. Use the suffix “name” with the name of the attribute to set the value for the text.
Don’t use any other arguments for simple lookups.
For customer and owner lookups you must set the value and the name in the same way you set them for simple lookups. In addition you must use the suffix “type” to specify the type of entity. Allowable values are account, contact, systemuser, and team.
For your example, it is a simple lookup, I suppose. So, Please try using the code below:
var parameters = {
cw_location: locationId,
cw_locationname: primaryField
};
For more information, Please visit Set the value for lookup fields.

Related

Troubleshooting SuiteScript 1.0 Line Level Field Sourcing Code (List/Record)

I am an inexperience technical developer working on my first SuiteScript using SuiteScript 1.0. I am getting an SSS_MISSING_REQD_ARGUMENT error, but I am sure there are many more in my code. The purpose of the script is to populate the department field on the expense record line item from a joined record. The end user will select a Project on the expense line, and the script should look up the department on the project record (a custom field) and add the value to the native department field. Code is copied below.
function ProjectSegment ()
{
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var recordID = nlapiGetRecordId(record);
//internal ID of project record
var project = nlapiGetField ('custcol_nra_expense_project');
//load project record
var precord = nlapiLoadRecord('job', project);
//get department on project record (internal ID)
var pdepartment = precord.GetFieldValue('custentity_nra_dept_project');
//get project name from project record
var projectName = precord.GetFieldText('entityid');
//load existing search
var search = nlapiLoadSearch('job','customsearch161');
//add filter to include project name
search.addFilter(new nlobjSearchFilter('entityid',null,'is',projectName));
//run search
var resultSet = search.runSearch();
//get department line
var departmentResult = new nlobjSearchColumn('custentity_nra_dept_project');
//set value
nlapiSetFieldTexts('job','department',1,departmentResult)
//record.commitLineItem('department');
nlapiSubmitRecord(record, true);
}
//internal ID of project record
var project = nlapiGetFieldValue ('custcol_nra_expense_project');
Praveen Kumar's response is correct regarding the missing required argument, but there are many other issues with the script as you've surmised.
Side notes:
The getFieldValue and getFieldText methods of nlobjRecord are not capitalized.
For performance reasons, you could/should use a search to get the values you need from the job record. Loading a record just to get field values is wasteful unless you mean to change the record.
Your search filter should probably be based on the value (not text) of the entityid in the job record.
Your desired search column probably is invalid (I don't think a custentity field could be on a job record).
Getting the search result is incorrect.
You want something like this instead:
var result = resultSet.getResults(0, 1);
if (result) {
var department = result.getValue('custentity_nra_dept_project');
// etc.
}
All that said, though, from your description, I don't think you need the search anyway. Once you have pdepartment (again, using precord.getFieldValue), I think all you need is:
record.setFieldValue('department', pdepartment);
Or if you're setting the line-level department, it would be different.
What kind of script is this? I'd like to make more recommendations, but it depends on what's going on.

Accessing Other Entities Attributes in Dynamics CRM/365 Forms with javaScript

This function buttonBuzz() works inside the Forms of the Entities Account, Contacts and Leads. But not in the Opportunity form.
Mainly because there is no telephone1 attribute. There is however a Contact entity added with "Quick View" in a section with a telephonenumber inside.
I think it can be accessed with the telephone1 as well just not with Xrm.page
Any ideas how i can grab the attribute from inside the "quick view"?
I dont know if the "Quick view" window is a form of an iFrame. And if it is i have no clue how to access it with the Xrm.Page.getAttribute("telephone1").getValue();
function buttonBuzz(exObj) {
var phoneNumber;
// Here i store the "telephone1" Attribute from the current .page
phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();
if (phoneNumber != null) { **Sends phonenumber** } ...
Quick Views display data from a record selected in a lookup field, in this case a Contact. You can query data from related records using the OData endpoint.
You first need to get the Guid of the record selected:
var contactId = Xrm.Page.getAttribute("parentcontactid")[0].id || null;
You would then need to send a SDK.REST request, passing parameters for the Id of the record (contactId), entityName and the columns:
var entityName = "Contact";
var columns = "Address1_Telephone1, FirstName, LastName";
SDK.REST.retrieveRecord(contactId, entityName, columns, null, function(result) {
// Success, logic goes here.
var address1_Telephone1 = result.Address1_Telephone1;
}, function(e) {
console.error(e.message);
});
As well as your JavaScript file, you would need to include the SDK.REST.js file that is included in the MS CRM SDK download within your Opportunity form libraries.
You can pull that field up from the Contact into the Opportunity by creating a Calculated Field, setting it equal to parentcontactid.telephone1
Put the field on the form, and you'll be able to .getAttribute() it like any other Opportunity field (being Calculated, it updates itself whenever the source changes).

Reading SharePoint Taxonomy Term Store and getDefaultLabel(lcid)

My App reads the SharePoint Term Store and need to get the label associated with the user's language. I get the user's language and lcid, and then I read all the terms under a certain node in the taxonomy using this code:
... some code to get the Term Store, then Term Group, then Term Set, and finally startTerm
var tsTerms = startTerm.get_terms();
context.load(tsTerms);
context.executeQueryAsync(
function () {
var termsEnum = tsTerms.getEnumerator();
while (termsEnum.moveNext()) {
var currentTerm = termsEnum.get_current();
var termName = currentTerm.get_name();
var userLabel = currentTerm.getDefaultLabel(lcid);
var userLabelValue = userLabel.get_value();
console.log ("Label=", userLabel, userLabelValue)
... more code ...
In the while loop, I can get all the attributes of the term I need, except for the label. In other samples I found on the web, to get the default label, my userLabel object would be loaded in the context, then another context.executeQueryAsync is called. All that makes sense, but this would induce a lot of calls to the SharePoint server.
But, when I write to the console the userLabel object, is shows as type SP.Result, and when I open it, I see the label I want under the m_value. So there should be no need to go to the server again. However, the userLabelValue is returned as a 0 - obviously, the get_value() does not work. In MSDN documentation, a SP.Result object type is for internal use only. Is there any way to extract the data that it stores?
I have attached a picture of the console with the object expanded, where we clearly see the m_value = "Contrat", which is the label I need to get to.
Use SP.Taxonomy.Term.getDefaultLabel Method to get the default Label for this Term based on the LCID:
function getTermDefaultValue(termId,lcid,success,failure)
{
var context = SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
var termDefaultValue = taxSession.getTerm(termId).getDefaultLabel(lcid);
context.executeQueryAsync(function() {
success(termDefaultValue);
},
failure);
}
Note: SP.Taxonomy.Term.getDefaultLabel method expects locale identifier
(LCID) for the label.
Usage
var layoutsRoot = _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/';
$.getScript(layoutsRoot + 'sp.taxonomy.js',
function () {
var termId = 'dff82ab5-6b7a-4406-9d20-40a8973967dd';
getTermDefaultValue(termId,1033,printLabelInfo,printError);
});
function printLabelInfo(label)
{
console.log(String.format('Default Label: {0}',label.get_value()));
}
function printError(sender,args){
console.log(args.get_message());
}
I was facing the same problem and found a solution. Instead of using getDefaultLabel(lcid), use this:
termSet.getTerm(Termid).getAllLabels(lcid).itemAt(0).get_value();
This, in my opinion, does the same as 'getDefaultLabel' but it works. It may cause a little bit more load than the other function but this one works for me

Looking for general feedback on a URL-parsing script of mine (Javascript)

I'm fairly new to Javascript, and assembled the following (part is from an example online, rest is by me):
This works reliably, I'm just wondering how many best-practices I'm violating. If someone is nice enough to provide general feedback about the latter part of this script, that would be appreciated.
The two included functions are to (1) capture the incoming website visitor's referral data on a page, including URL query strings for analytics, and store it to a cookie. (2) When the visitor completes a form, the script will read the cookie's URL value, parse this URL into segments, and write the segment data to pre-existing hidden inputs on a form.
Example URL this would capture and parse: http://example.com/page?utm_source=google&utm_medium=abc&utm_campaign=name1&utm_adgroup=name2&utm_kw=example1&kw=example2&mt=a&mkwid=xyz&pcrid=1234
function storeRef() { //this function stores document.referrer to a cookie if the cookie is not already present
var isnew = readCookie('cookiename'); //set var via read-cookie function's output
if (isnew == null) {
var loc=document.referrer;
createCookie('cookiename',loc,0,'example.com'); //create cookie via function with name, value, days, domain
}
}
function printQuery() { //function to parse cookie value into segments
var ref=readCookie('cookiename'); //write cookie value to variable
var refElement = ref.split(/[?&]/); //create array with variable data, separated by & or ?. This is for domain info primarily.
var queryString = {}; //From http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
ref.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
//write segments to form field names below.
document.getElementsByName('example1')[0].value = refElement[0]; //exampleX is a form hidden input's name. I can not use getElementById here.
//need to be able to manually define these, which is why they aren't in a loop, though I'm not sure how to loop an array referenced in this way
document.getElementsByName('example2')[0].value = queryString['utm_source'];
document.getElementsByName('example3')[0].value = queryString['utm_medium'];
document.getElementsByName('example4')[0].value = queryString['utm_term'];
document.getElementsByName('example5')[0].value = queryString['utm_content'];
document.getElementsByName('example6')[0].value = queryString['utm_campaign'];
document.getElementsByName('example7')[0].value = queryString['utm_adgroup'];
document.getElementsByName('example8')[0].value = queryString['utm_kw'];
document.getElementsByName('example9')[0].value = queryString['kw'];
document.getElementsByName('example10')[0].value = queryString['mt'];
document.getElementsByName('example11')[0].value = queryString['mkwid'];
document.getElementsByName('example12')[0].value = queryString['pcrid'];
}
Thank you!
why would you need to use a cookie to store the data for that, if unless you wanna keep track of the visitors visiting to your site?

Thunderbird Addon - Filter by Sender

I have a list of email ids.i want to filter inbox messages and display only emails from those users in thunderbird. Please help me doing this.
This is what i tried so far and it's not working.But im getting completely irrelevant error message "We are unable to print or preview this page".
var gLocalIncomingServer = MailServices.accounts.localFoldersServer;
var gLocalMsgAccount = MailServices.accounts.FindAccountForServer(
gLocalIncomingServer);
var gLocalRootFolder = gLocalIncomingServer.rootMsgFolder
.QueryInterface(Ci.nsIMsgLocalMailFolder);
const kInboxFlag = Components.interfaces.nsMsgFolderFlags.Inbox;
var gLocalInboxFolder = gLocalRootFolder.getFolderWithFlags(kInboxFlag);
gLocalRootFolder.findSubFolder(gLocalInboxFolder.URI);
gLocalInboxFolder.setFlag(Ci.nsMsgFolderFlags.Mail);
// Force an initialization of the Inbox folder database.
var folderName = gLocalInboxFolder.prettiestName;
var aValue = "example#domain.com";
var aAttrib = Ci.nsMsgSearchAttrib.Sender;
var aop = nsMsgSearchOp.Contains;;
var hitCount = 1;
var searchListener =
{
onSearchHit: function(dbHdr, folder) { hitCount++; },
onSearchDone: function(status)
{
print("Finished search does " + aHitCount + " equal " + hitCount + "?");
searchSession = null;
do_check_eq(aHitCount, hitCount);
if (onDone)
onDone();
},
onNewSearch: function() {hitCount = 0;}
};
// define and initiate the search session
var hitCount;
var searchSession = Cc["#mozilla.org/messenger/searchSession;1"]
.createInstance(Ci.nsIMsgSearchSession);
searchSession.addScopeTerm(Ci.nsMsgSearchScope.offlineMail, gLocalInboxFolder);
var searchTerm = searchSession.createTerm();
searchTerm.attrib = aAttrib;
var value = searchTerm.value;
// This is tricky - value.attrib must be set before actual values
value.attrib = aAttrib;
value.str = aValue;
searchTerm.value = value;
if (aAttrib > nsMsgSearchAttrib.OtherHeader)
searchTerm.arbitraryHeader = gArrayHdrs[aAttrib - 1 - nsMsgSearchAttrib.OtherHeader];
searchTerm.op = aOp;
searchTerm.booleanAnd = false;
searchSession.appendTerm(searchTerm);
searchSession.registerListener(searchListener);
searchSession.search(null);
alert("search is done:");
Have you seen this Mozilla page? How do I search for a particular contact property (name, email)?
You don't really need to write any JS code to accomplish this. Thunderbird's search mechanism can be used in two UI-accessible ways:
Define a "saved search" folder. This filters one or more folders with a set of criteria and presents the results in a single folder. See and be aware you probably want an offline search since it will be faster than asking the IMAP server: http://kb.mozillazine.org/Saved_Search
Define a "mail view" that can be applied to any folder. Customize the mail toolbar by right clicking on it, choosing "customize..." and dragging the combo-box labeled "Mail Views" to the toolbar. Close the customize dialog by hitting "Done". Click on the combo-box on the toolbar, choose "customize...", hit "new..." to define and name your filter criteria. You can then apply the mail view by clicking on the combo box and locating it under the "Custom Views" header.
For your filter criteria, you can either type in all the names as separate predicates where "any" rule matches, or you might want to use the "is in my address book" predicate and just put all of those people in a special address book. For example, such a rule would look like: "From" "is in my address book" "cool people". You can create a new address book via "File... New... Address Book" from the Address Book window.
If you prefer to do things programatically and you want to be able to have the list of people vary at runtime, you will want to check out my blog post on creating quick filter bar extensions, as that's the easiest way to hook custom filtering logic into the Thunderbird UI that won't break:
http://www.visophyte.org/blog/2010/05/02/thunderbird-quick-filter-bar-extensions-theyre-a-thing/
Code for that example currently lives here on github:
github.com/asutherland/qfb-pivot
If your list of e-mails isn't going to change a lot, you can also create the "saved search folders" (virtual folders, internally), you should check out mxr.mozilla.org/comm-central/source/mailnews/base/src/virtualFolderWrapper.js and its createNewVirtualFolder method.
Apologies for de-hyperlinking two of the URLs, but the anti-spam mechanism won't let me have more than 2 links in the post...

Categories

Resources