Reading SharePoint Taxonomy Term Store and getDefaultLabel(lcid) - javascript

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

Related

How to get Dynamics CRM Web Resource name using JavaScript

I'm working on a project. I want to get the name of web resource e.g if I want to get entity name I use this query
var entityName = parent.Xrm.Page.data.entity.getEntityName();
var id = parent.Xrm.Page.data.entity.getId();
so in the same way how I can get the web resource name at this time, I am passing the web resource as a string.
getImages(entityName, id, "WebResource_webTest");
So can you tell me how i can get the web resoucre name.
Here is the code snippet I just tried on one of my Entity and it gave me webresource name
You can add this function on load on change and pass execution context as parameter to function
Note: If you have 5 webresources on your form you will get one by one all the webresource names. you can tweak/modify code as per your need.
function onChangeOfField(executionContext) {
debugger
var formContext = executionContext.getFormContext();
formContext.ui.controls.forEach(function(control, index) {
var controlType = control.getControlType();
if (controlType === "webresource" ) {
alert(control.getName());
}
});
}

How to show the number of user stories/test cases by total, pending, complete, in progress, accepted?

So I saw this app for rally on Github:
https://github.com/RallyApps/DefectSummaryMatrix
And I am trying to make the same thing, except for test cases and user stories, instead of defects. How would I go about doing this? I am pretty new into the rally SDK and kind of lost to be honest, so anything you guys can say would help.
I've been looking at the App.html for this, and I think this part is the part I need to pay attention to cause this is where it gets the information about the defects:
var defectQuery = function() {
var selected = releaseDropdown.getSelectedName();
var releaseQuery = '(Release.Name = "' + selected + '")';
var queryObject = [];
queryObject[0] = { key: 'defectStates', type: 'Defect', attribute: 'State' };
queryObject[1] = { key: 'defectPriorities', type: 'Defect', attribute: 'Priority' };
queryObject[2] = {
key: 'defects',
type: 'Defect',
query: releaseQuery,
fetch: 'FormattedID,Name,State,Priority,ScheduleState,ObjectID,Description,owner,DisplayName,LoginName'
};
rallyDataSource.findAll(queryObject, populateTable);
};
How do I modify this to get information about user stories? I think the type field would be called userStory or something like that, but then what would the key and attributes be? I can't find any documentation on this.
See Rally object model in Web Services API documentation.
User stories are called "HierarchicalRequirement" in the WS API. Click on HierarchicalRequirement object in the object model to go over the attributes.
I suggest that you do not use the DefectSummaryMatrix as a starting point. It is a legacy app that is using legacy AppSDK1. Use AppSDK2 instead. There is an example of multi-type object grid here.

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?

Adding a record and retrieving the key generated [duplicate]

I have this code in IndexedDB:
var request = objectStore.add({ entryType: entryType, entryDate: t});
Now I want to know the key of this record that was just added in. How do I do that?
I found this article, and this
code:
var data = {"bookName" : "Name", "price" : 100, "rating":"good"};
var request = objectStore.add(data);
request.onsuccess = function(event){
document.write("Saved with id ", event.result)
var key = event.result;
};
This does not work for me - key shows up as undefined. I think I am missing something basic here!
Go through this code
var data = {"bookName" : "Name", "price" : 100, "rating":"good"};
var request = objectStore.add(data);
request.onsuccess = function(event){
document.write("Saved with id ", event.result)
var key = event.target.result;
};
Hope this code will work to retrieve key of last inserted Record
The spec is written for user agent, not for developer. So it is confusing. Key generator is provided by the user agent.
Any event object that is received by onsuccess handler always have event.target.result. It is the key you are looking for. The key is auto generated if you don't provide it, assuming you set autoIncrement to true.
It is documented in Step 8: as follow:
The result of this algorithm is key.
The trick here is knowing how to search using phrases iteratively, until you land on what you need. I've never heard of IndexedDB before, but seem to have found what you want.
I put "IndexedDB" into a search engine and found this. That yielded the phrase "key generator", so I searched for that as well which led me to this and this.
The StackOverflow link discusses using UUIDs, which of course can be generated in JavaScript, and the last link appears to have examples to do what you want out of the box.
If you're using the idb Promise wrapper for IndexedDB then the new key is just the return value from the add() call:
import { openDB } from 'idb';
const db = await openDB(...);
const tx = db.transaction('mystore', 'readwrite');
const newId = await tx.store.add({ hello: 'world' });
await tx.done;
console.log(`Autogenerated unique key for new object is ${newId}`);
Remember of course, this will only work if you include autoIncrement: true in the options passed to createObjectStore().

Creating JavaScript API for first time

I am creating a commercial API for the first time for responsive webpages/web applications (mobile devices).
I am new and, sadly, working alone as well as new to Javascript (long complicated story).
I was just wondering if someone from the industry could offer their professional opinion on the following format of a "get" call:
var getSample = function(params) {
//Returns Object
return $.ajax({
url: URL + 'downloadQuadrat.php',
type: 'GET',
data: { 'projectID': params.pid, 'quadratID': params.qid },
dataType: dataType
});
}
Function call:
var printList = function(lid,options,get) {
var list = $("ul#"+lid);
var promise = get(options);
promise.promise().then(
function(response) {
var items = response;
list.empty();
$.each(items, function(item,details) {
var ul = $('<ul/>');
ul.attr('id', lid+'_'+details.ID);
var li = $('<li/>')
.text(details.ID)
.appendTo(list);
ul.appendTo(list);
$.each(details,function(key,value) {
var li = $('<li/>')
.text(key+': '+value)
.appendTo(ul);
});
});
}
);
}
Any input or guidance will be hugely appreciated.
I'm not a professional from the industry, per se, but there's a few things that I think would improve your code:
Format it according to common conventions. It's hard to see what your code is doing without proper indentation.
Just use $("#"+lid) instead of $("ul#"+lid). The ul at the beginning does not add any disambiguation because id attributes must be unique, and it just make it take longer to parse.
Ditch localstorage in this case. It's not supported on all browsers, and as far as I can tell, you don't need it here. Just directly use the data returned from the response.
Here is how I would change your code:
var printList = function(lid, options, get) {
var promise = get(options);
var list = $("#" + lid);
promise.success(function(response) {
var data = response;
list.empty();
$.each(data, function(item, details) {
var ul = $('<ul/>').attr('id', lid + '_' + details.ID);
var li = $('<li/>').text(details.ID).appendTo(list);
ul.appendTo(list);
$.each(details, function(key, value) {
var li = $('<li/>').text(key + ': ' + value).appendTo(ul);
});
});
});
}
EDIT: The edited version of your code looks fine to me, except for the minor ul# thing.
Some more suggestions to make your API a tad more professional looking:
1 - Namespacing
Use a namespace to keep your code packaged neatly in it's own space where it won't conflict with other function definitions on the page. Something like this to start with:
window.MyNamespace = {};
MyNamespace.get = function(qid, pid) {
//things
};
MyNamespace.anotherFunction = function() {
//other stuff
}
If your code starts getting bigger you can wrap the whole lot in a closure. Also you could define it all as class and then instantiate it once to make your code neater and allow you to store instance variables and call this.anotherFunction(). I can provide examples of those too if you like.
2 - API method signatures
Another thing I prefer to see is explicit arguments to functions rather than function get(params) style code. Making parameters explicit makes your code easier to read and understand and discourages ad-hoc hacks which is especially important when writing an API. It's a case of just because you can doesn't mean you should.
3 - Config
Try to move things like IDs and URLs into variables to start with to make your code a bit easier to reuse and work with.
Generally, Javascript developers are famous for looking at your code before they look at your API docs so anything you can do to make the API function names and argument names more expressive and self-documenting will help them.

Categories

Resources