Getting users job title in Sharepoint List - sharepoint

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

Related

Viewing file properties instead of file in SharePoint document library

I have a document library on SharePoint online with lots of columns for metadata. These columns won't fit in a single view on screen, so I want the users to first view the properties of the file before downloading them.
Is there a way to change the behavior of the SharePoint library ensure that the user views the file properties first when they click on the filename?
PS: I understand I could have used lists, but after loading about 10000 documents, I have decided to use it as a last resort. Thank you.
Custom the LinkFilename field by CSR.
Sample code:
(function () {
'use strict';
var CustomWidthCtx = {};
/**
* Initialization
*/
function init() {
CustomWidthCtx.Templates = {};
CustomWidthCtx.Templates.Fields = {
'LinkFilename': {
'View': customDisplay
}
};
// Register the custom template
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(CustomWidthCtx);
}
/**
* Rendering template
*/
function customDisplay(ctx) {
var currentVal = '';
//from the context get the current item and it's value
if (ctx != null && ctx.CurrentItem != null)
currentVal = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
var el = "<div class='ms-vb itx' id='" + ctx.CurrentItem.ID + "' app='' ctxname='ctx37'><a title='" + ctx.CurrentItem._ShortcutUrl + "' class='ms-listlink ms-draggable' aria-label='Shortcut file' onfocus='OnLink(this)' href='/Doc4/Forms/EditForm.aspx?ID=" + ctx.CurrentItem.ID + "' target='_blank' DragId='17'>" + ctx.CurrentItem.FileLeafRef + "</a></div>";
// Render the HTML5 file input in place of the OOTB
return el;
}
// Run our intiialization
init();
})();

How Do I get a page's URL using JSOM

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

List 'created by' in column

I know there is surveylist.get_description and surveylist.get_itemCount. I would like to know if there is a way to get created by fit in a column?
From syntax i guess you are using Javascriot CSOM.
Try this:
surveylist.get_author
Don't forget that you need to explicitly specify which properties you want to retrieve before you can get their values.
Unfortunately List Author property is not exposed via SharePoint CSOM.
How to retrieve List Author property via CSOM?
The idea is to retrieve SPList.SchemaXml property and extract Author property
function getListAuthor(listTitle,OnSuccess,OnError) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
context.load(web);
context.load(list,'SchemaXml');
context.executeQueryAsync(function(sender,args){
var schemaXml = $.parseXML(list.get_schemaXml());
var authorId = parseInt($(schemaXml).find('List').attr('Author')); //SchemaXml contains Author ID only
var listAuthor = web.getUserById(authorId);
context.load(listAuthor);
context.executeQueryAsync(OnSuccess(listAuthor),OnError);
},OnError);
}
//Usage
getListAuthor('Discussions List',
function(author){
console.log('List created by: ' + author.get_loginName())
},
function(sender,args){
console.log('Error occured:' + args.get_message());
}
);

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

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