I have been working on an application in SharePoint Office 365, and one of the requirements was to get the list details using Custom form and store it in the announcement list which includes adding Enterprise keyword value to the list column and in default term store.

 

First step is to Add reference to Taxonomy.js file:

jQuery(document).ready(function(){

var scriptbase = _spPageContextInfo.siteAbsoluteUrl + “/_layouts/15/”;

$.getScript(scriptbase + “SP.js”, function(){

$.getScript(scriptbase + “SP.Taxonomy.js”, onPageload);

});

});

function onPageload(){

 

//Write the code for tasks on page load

 

}

 

After Adding the announcement list new Item form to the web part page using DataViewWebPart, write the below code in Content Editor web part to collect the data from form and update in the list.

 

 

Below are the few highlights carried out by the OnClickOfSubmitButton() function:

 

  1. Adding Title, description and Expires textbox values to list column is pretty straight forward. You simply need to set the value to list Item.
  2. For handling Enterprise keywords below steps are followed.
  3. Enterprise Keyword text box terms are separated by a semicolon (;).
  4. If the Term already exists in the term store then the Guid of the term is extracted from term store and added to the list column.
  5. If the user has entered a new term, then a new Guid is created and assigned to the term and then added to the term store as well as list column.

 

 

var siteUrl;

var clientContext;

var oList;

var itemCreateInfo;

var oListItem;

var keyword1;

var ic=0;

//Executes on click of submit button

function OnClickOfSubmitButton()

{

var termValueString = null;

//Get Enterprise Keyword Data from text box

var keyword = jQuery(“div[id*=’editableRegion’]”)[0].innerHTML;

keyword1 = jQuery(keyword).text();

if( keyword1 != ”){

var newarr = encodeURIComponent(keyword1);

keyword2 = newarr.replace(/%3B%C2%A0%E2%80%8B/,””);

keyword2 = keyword2.replace(/%3B%E2%80%8B/,””);

var newarr1= decodeURIComponent(keyword2);
Karray = newarr1.split(‘;’);

var trimmed = Karray.map(Function.prototype.call,String.prototype.trim);

var limit=trimmed.length;

var termsArray = new Array();

EnsureKeywordMethod(trimmed[ic]);

function funcComplete(termId) {

if (termId!= null) {

// The term exists or was created

termsArray.push(“-1;#” + trimmed[ic] + “|” + termId);

termValueString  = termsArray.join(“;#”);

if(ic==trimmed.length-1)

CreateListItem(termValueString);

}

else{

alert(“Term does not exist or could not create a new term”);

}

} // funcComplete Call ends

} //if ends

else{

CreateListItem(termValueString);

}
function CreateListItem(termString)

{

siteUrl =”Site_URL”;

clientContext = new SP.ClientContext(siteUrl);

oList = clientContext.get_web().get_lists().getByTitle(‘List Title’);

itemCreateInfo = new SP.ListItemCreationInformation();

this.oListItem = oList.addItem(itemCreateInfo);

//Extracts the title entered by user

var titleValue = jQuery(“input[title=’Title Required Field’]”);

title1= jQuery(titleValue).val();

this.oListItem.set_item(‘Title’, title1);

//Extracts the description multiline rich text entered by user

var description = jQuery(“div[id*=’TextField_inplacerte’]”)[1].innerHTML;

this.oListItem.set_item(‘Body’, description);

//Extracts Expires date entered by user

var EDate = jQuery(“input[title=’Expires’]”);

ExpiresDate = jQuery(EDate).val();

if( ExpiresDate != ”){

this.oListItem.set_item(‘Expires’, ExpiresDate);

}

// Load list column- keywords

if(termString != null){

var field = oList.get_fields().getByInternalNameOrTitle(“Enterprise Keywords”);

var txField = clientContext.castTo(field, SP.Taxonomy.TaxonomyField);

clientContext.load(txField);

// update the taxonomy field value for column

var termValues = new SP.Taxonomy.TaxonomyFieldValueCollection(clientContext, termString, txField);

txField.setFieldValueByValueCollection(this.oListItem, termValues);

}

// create item finally

this.oListItem.update();

clientContext.load(this.oListItem);

clientContext.executeQueryAsync(Function.createDelegate(this,onCreateListItemSuccess),Function.createDelegate(this,onCreateListItemFailed));

function onCreateListItemSuccess()

{

alert(“Whats New Item added successfully”);

}

function onCreateListItemFailed(sender, args)

{

alert(“Whats New item could not be created because: ” + args.get_message());

}

} // CreateListItem ends

// check term and return Id else create term and return Id

function EnsureKeywordMethod(termInput) {

var termSetName = “Keywords”;

var locale = 1033;

// To be used while create term if it does not exist

localTerm = termInput;

clientContext = new SP.ClientContext(“Add Site URL”);

var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);

var termStore = taxonomySession.getDefaultKeywordsTermStore();

var termSets = termStore.getTermSetsByName(termSetName, locale);

var termSet = termSets.getByName(termSetName);
var terms = termSet.getAllTerms();

term = terms.getByName(termInput);

clientContext.load(term);

clientContext.executeQueryAsync(Function.createDelegate(this, GetTermExecuteOnSuccess), Function.createDelegate(this, GetTermExecuteOnFailure));

// Found term – SUCCESS

function GetTermExecuteOnSuccess(sender, args) {

//Run the delegate function with the term id found;

funcComplete(term.get_id().toString());

ic++;

EnsureKeywordMethod(trimmed[ic]);

}

// Found term – FAILURE

function GetTermExecuteOnFailure(sender, args) {

// Create term in term set

var termSetName = “Keywords”;

var locale = 1033;

clientContext = new SP.ClientContext(“Add Site URL”);

var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);

var termStore = taxonomySession.getDefaultKeywordsTermStore();

var termSets = termStore.getTermSetsByName(termSetName, locale);

var termSet = termSets.getByName(termSetName);

var newGuid = new SP.Guid.newGuid();

newTerm = termSet.createTerm(localTerm, 1033, newGuid.toString());

clientContext.load(termSet);

clientContext.load(newTerm);

clientContext.executeQueryAsync(Function.createDelegate(this, CreateTermExecuteOnSuccess), Function.createDelegate(this, CreateTermExecuteOnFailure));

}

// Create term – SUCCESS

function CreateTermExecuteOnSuccess(sender, args) {

//Run the delegate function with the term id found;

funcComplete(newTerm.get_id().toString());

ic++;

EnsureKeywordMethod(trimmed[ic]);

}

// Create term- FAILURE

function CreateTermExecuteOnFailure(sender, args) {

//Run the delegate function and return null because there was no match.

funcComplete(null);

}

}    // EnsureKeywordMethod ends

} // submit button event handler ends

</script>

<div id=”ButtonOK”>

<input type=”button” onclick=”OnClickOfSubmitButton()” value=”Submit”/></div>

 

Hope you find it useful!!

 

Heena
Heena
Software Engineer