In this blog, we will see how to get and set manager property of currently logged in user. We have a one-person editor field and we need to set the name of the manager based on the logged-in user.
I have one visual web part and in that, I have the following control.
- <SharePoint:PeopleEditor MultiSelect="false" ValidationEnabled="true" ID="cppFirstApprover" Width="500px" runat="server" VisibleSuggestions="3" Rows="1" CssClass="ms-long ms-spellcheck-true marginleft0" />
The below-given script is used to get the manager name from SharePoint user profiles.
- <script>
- LoadPeoplePickerDetails();
-
- function LoadPeoplePickerDetails() {
- var url = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties"
- getReqData(url, function(data) {
- try {
- var ManagerName = data.d.UserProfileProperties.results[15].Value;
- $("div[id*='cppFirstApprover']").html(ManagerName);
- $("a[id*='cppFirstApprover_checkNames']").click();
- } catch (err) {}
- }, function(data) {
- alert("some error occured in getting current User info");
- });
- }
-
- function getReqData(reqUrl, success, failure) {
- $.ajax({
- url: reqUrl,
- method: "GET",
- headers: {
- "Accept": "application/json; odata=verbose"
- },
- success: function(data) {
- success(data);
- },
- error: function(data) {
- failure(data);
- }
- });
- }
- </script>
We can also add the above script to document.ready function. Also, we need to save this approver information into Person or Group column SharePoint list.
Suppose, we have a button and on click of this button, we need to save the manager's information into SharePoint list.
- <asp:Button ID="btnSave" runat="server" CssClass="btn btn-primary" Text="Submit" OnClick="btnSave_Click1" />
After creation of the click event, open ascx.cs file and add the below code on button click.
- protected void btnSave_Click1(object sender, EventArgs e) {
- SPSite site = new SPSite(SPContext.Current.Web.Url);
- using(SPWeb web = site.OpenWeb()) {
- try {
- SPList lst = web.Lists.TryGetList("Add your cutom list Name");
- site.AllowUnsafeUpdates = true;
- web.AllowUnsafeUpdates = true;
- SPListItem item = lst.Items.Add();
- SPFieldUserValueCollection spfcppFirstApprover1 = GetPeopleFromPickerControl(cppFirstApprover, web);
- item["ApproverName"] = spfcppFirstApprover1;
- item.Update();
- site.AllowUnsafeUpdates = false;
- web.AllowUnsafeUpdates = false;
- }
- Catch(Exception ex) {}
- }
- }
That's it. We are done here.