How Do I get a page's URL using JSOM - sharepoint

I am using SharePoint 2013 workflow.
I am in the Initiation form when my my users clock the Start button to start the workflow.
I am using JSOM to start the workflow but since I am on the Initiation form, I don't know the URL of the page. I do know the list (pages) and the the list id (2).
Can someone help me retrieve the list id's url using JSOM?
Thanks
Tom

How to get Page Url in Initiation Form page:
var listId = getParameterByName('List');
var itemId = getParameterByName('ID');
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getById(listId);
var listItem = list.getItemById(itemId);
ctx.load(listItem);
ctx.executeQueryAsync(
function () {
var itemUrl = listItem.get_item('FileRef');
console.log(itemUrl);
},
function (sender, args) {
console.log(args.get_message());
}
);
,where
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
is intended for retrieving parameter from query string
Source

Related

Getting users job title in Sharepoint List

So I have a SP Online list, that every user can submit his entries. I have a default column of "created by", where the user, that submited the entry is listed. I'd like to have 2 other columns, to get users Department and Job Title copied automatically from users account. How can I do this?
Method 1:
You can use the JSOM to set the Department/JobTitle. Because we don't sure where your user from(AD or some else )
First of all you need to load the “SP.UserProfiles.js, SP.Runtime.js and SP.js” js files on your SharePoint page, use following code snippet to load these files,
$(document).ready(function () {
var scriptbase = _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase + "SP.UserProfiles.js", GetUserInformation);
});
});
});
var userProfileProperties;
function GetUserInformation() {
// Get the current client context.
var clientContext = SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
var targetUser = "domain\\userId";
userProfileProperties = peopleManager.getPropertiesFor(targetUser);
//Execute the Query.
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(onSuccess, onFail); }
function onSuccess () {
// get user information from userProfileProperties and set to your target column.
userProfileProperties.get_userProfileProperties()['Department'];
userProfileProperties.get_userProfileProperties()['SPS-JobTitle'];
// To do: list item replace operation
}
function onFail (sender, args) {
alert("Error: " + args.get_message());
}
Reference:https://msdn.microsoft.com/en-us/library/office/jj679700.aspx
Method 2: Workflow
When user add/edit a item,we trigger the workflow to copy the user's department/JobTitle to target column
Reference for get the Department/Jobtitle.
https://sharepoint.stackexchange.com/questions/97971/get-current-user-information-and-add-to-email-action-in-workflow

SharePoint JSOM Parsing values in a hyperlink field

I have a value that looks like "mailto:a#b.com, mailto:a#b.com'. This is basically a hyperlink field and I want to parse this properly using SharePoint JSOM. I tried SP.FieldUrlValue, but it does not seem to have a method that lets you parse.
You can use the .get_url() function on the actual item value to get the hyperlink URL, or the .get_description() function to get the hyperlink's display text.
var linkField = "internalColumnName";
var listName = "List Title";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var camlQuery = new SP.CamlQuery();
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
var itemEnumerator = items.getEnumerator();
while(itemEnumerator.moveNext()){
var item = itemEnumerator.get_current();
var url = item.get_item(linkField).get_url(); // <-- Get URL
var text = item.get_item(linkField).get_description(); // <-- Get Text
alert(url + ", " + text);
}
}),Function.createDelegate(this,function(sender, args){alert(args.get_message());}));

activation of customer by sending link to his email using Suitelet Scripts

Overview:
I create one custom customer form using Suitelet Script with fields like name,email,phone in GET Method and the values entered in this fields obtained in the POST Method by request.getParameter() method. the customer record is created is successfully but when clicking the submit button the customer record is to be "inactive" mode and the url link is to sent to the customer email address ,when he clicks the link his record is to be changed to"active" mode this must be with in same suitelet page.
My Requirement:
I created the customer record successfully with INACTIVE MODE and link this send the customer mail but i need how to make the customer record to ACTIVE MODE when he clicks the link and the result is to be viewed in same suitelet page.
I have Given my code Sample Below:
function getCustomerInfo(request, response){
if(request.getMethod() == 'GET'){
//CREATING THE CUSTOM FORM AND ADDING FIELDS IN THE FORM
var form = nlapiCreateForm('Custom Customer Form');
form.addField('sfg_company', 'text', 'Company Name').setMandatory(true);
form.addField('sfg_address1','text','Address1');
form.addField('sfg_address2','text','Address2');
form.addField('sfg_city','text','City');
form.addField('sfg_state','text','State');
form.addField('sfg_emailaddr','email','Email').setMandatory(true);
form.addField('sfg_phone','phone','Phone');
form.addSubmitButton('Submit');
response.writePage(form);
}else{
nlapiLogExecution('DEBUG','form',form);
// CREATING THE RECORD BY GETTING THE VALUES ENTERED IN THE CUSTOM FORM
var compName = request.getParameter('sfg_company');
var compAdd1 = request.getParameter('sfg_address1');
var compAdd2 = request.getParameter('sfg_address2');
var cities = request.getParameter('sfg_city');
var stateName =request.getParameter('sfg_state');
var email_addr = request.getParameter('sfg_emailaddr');
var phone_num = request.getParameter('sfg_phone');
var newCust = nlapiCreateRecord('customer');
newCust.setFieldValue('companyname', compName);
newCust.setLineItemValue('addressbook', 'addr1', 1, compAdd1);
newCust.setLineItemValue('addressbook', 'addr2', 1, compAdd2);
newCust.setLineItemValue('addressbook', 'city', 1, cities);
newCust.setLineItemValue('addressbook', 'state', 1, stateName);
newCust.setFieldValue('email', email_addr);
newCust.setFieldValue('phone', phone_num);
newCust.setFieldValue('subsidiary', 1);
newCust.setFieldValue('isinactive','T');
//sending activation link to the customer
var sender = nlapiGetUser();
var receiver = email_addr;
var subject = 'Customer Activation Link';
var recordId = nlapiGetRecordId();
var url = "https://system.na1.netsuite.com/app/common/entity/custjob.nl?id="+recordId+"&whence=";
var body = 'Dear Customer,Your Record is Created Successfully and it will activated by click the following link :'+ url;
nlapiSendEmail(sender,receiver,subject,body);
var id = nlapiSubmitRecord(newCust);
nlapiSetRedirectURL('RECORD','customer',id,null,false);
}
}
It sounds like what you basically want is to send out a confirmation link to a customer that they can click and complete some sort of registration.
If you want to re-use your suitele code then you need to pass a custom stage or action parameter that you can trigger different actions from. e.g.:
var stage = request.getParameter('custparam_action') || 'showForm';
switch(stage){
case 'showForm': doShowForm(request, response); break;
case 'validate' : doValidate(request, response); break;
}...
Then the url you need to send out needs to reference the suitelet rather than the customer page in Netsuite:
var ctx = nlapiGetContext();
var url = nlapiResolveURL('SUITELET', ctx.getScriptId(), ctx.getDeploymentId(), true) +"&custparam_action=validate"+ getSecureValidationParams());
the function getSecureValidationParams should create some sort of time sensitive parameters including a hashed key. If the request passes validation then you would show whatever other form you want to show or redirect to or show a thank you page.
function getCustomerInfo(request, response){
if(request.getParameter('custscript_sfg_custmer_param') != null){
var value = request.getParameter('custscript_sfg_custmer_param')
var loadRecord = nlapiLoadRecord('customer',value);
loadRecord.setFieldValue('isinactive','F');
loadRecord.setFieldValue('custentity_sfg_referredby',1);
nlapiSubmitRecord(loadRecord);
nlapiSetRedirectURL('RECORD','customer',value);
}
if(request.getParameter('custscript_sfg_custmer_param') == null){
if(request.getMethod() == 'GET'){
//CREATING THE CUSTOM FORM AND ADDING FIELDS IN THE FORM
var form = nlapiCreateForm('Custom Customer Form');
form.addField('sfg_company', 'text', 'Company Name').setMandatory(true);
form.addField('sfg_address1','text','Address1');
form.addField('sfg_address2','text','Address2');
form.addField('sfg_city','text','City');
form.addField('sfg_state','text','State');
form.addField('sfg_emailaddr','email','Email').setMandatory(true);
form.addField('sfg_phone','phone','Phone');
form.addSubmitButton('Submit');
response.writePage(form);
}
}
if(request.getMethod() == 'POST'){
nlapiLogExecution('DEBUG','form',form);
// CREATING THE RECORD BY GETTING THE VALUES ENTERED IN THE CUSTOM FORM
var compName = request.getParameter('sfg_company');
var compAdd1 = request.getParameter('sfg_address1');
var compAdd2 = request.getParameter('sfg_address2');
var cities = request.getParameter('sfg_city');
var stateName =request.getParameter('sfg_state');
var email_addr = request.getParameter('sfg_emailaddr');
var phone_num = request.getParameter('sfg_phone');
var newCust = nlapiCreateRecord('customer');
newCust.setFieldValue('companyname', compName);
newCust.setLineItemValue('addressbook', 'addr1', 1, compAdd1);
newCust.setLineItemValue('addressbook', 'addr2', 1, compAdd2);
newCust.setLineItemValue('addressbook', 'city', 1, cities);
newCust.setLineItemValue('addressbook', 'state', 1, stateName);
newCust.setFieldValue('email', email_addr);
newCust.setFieldValue('phone', phone_num);
newCust.setFieldValue('subsidiary', 1);
newCust.setFieldValue('isinactive','T');
//sending activation link to the customer
var sender = nlapiGetUser();
var receiver = email_addr;
var subject = 'Customer Activation Link';
var recordId = nlapiGetRecordId();
var webAddress = "https://system.na1.netsuite.com"
var scriptType = nlapiGetContext().getScriptId();
var scriptId = nlapiGetContext().getDeploymentId();
var location = nlapiResolveURL('SUITELET',scriptType,scriptId);
var id = nlapiSubmitRecord(newCust);
var link = webAddress+location+'&custscript_sfg_custmer_param='+id+"&whence=";
var url = 'Click Here ';
var body = 'Dear Customer,Your Record is Created Successfully and it will activated by click the following link :'+ url;
nlapiSendEmail(sender,receiver,subject,body);
nlapiSetRedirectURL('SUITELET',scriptType,scriptId);
}
The above code will Get Customer Information through external Suitelet form and saving the record in the system.

Multiple Querys context.Load SP O365

I need to retrieve a lot of User PersonProperties, and i was wondering if it is possible to load it all together.
For example:
var userList = web.SiteUserInfoList.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(userList);
clientContext.ExecuteQuery();
PeopleManager pm = new PeopleManager(clientContext);
List<PersonProperties> users = new List<PersonProperties>();
foreach (ListItem u in userList)
{
var personProperties = pm.GetPropertiesFor(u.FieldValues["Name"].ToString());
users.Add(personProperties);
}
clientContext.Load(users); //load all users[i].UserProfileProperties and PictureUrl
clientContext.ExecuteQuery();
My app is a ProviderHosted and it is for SharePoint Online 2013
Thanks for your time.
Since SharePoint CSOM supports Request Batching you could take advantage of this feature and consider the following example that demonstrates how to submit two requests to the server in order to:
retrieve site users
retrieve profile properties for site users
Example:
//1.Load site users
var siteUsers = ctx.Web.SiteUsers;
ctx.Load(siteUsers);
ctx.ExecuteQuery();
//2.Load user profile properties for site users
var pm = new PeopleManager(ctx);
var results = new Dictionary<string,PersonProperties>();
foreach (var siteUser in siteUsers)
{
var personProperties = pm.GetPropertiesFor(siteUser.LoginName);
ctx.Load(personProperties);
results.Add(siteUser.LoginName,personProperties);
}
ctx.ExecuteQuery();
Usage
foreach (var result in results)
{
var userLoginName = result.Key;
var userProperties = result.Value;
Console.WriteLine("{0} ({1})",userLoginName, userProperties.Email);
}

CRM 2011 Retrieving lookup

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 );
}

Resources