Showing posts with label Editor. Show all posts
Showing posts with label Editor. Show all posts

Sunday, 17 April 2016

JQuery Get all SharePoint sites and subsites and show in dropdown dynamically New / Edit form of List

Sometimes SharePoint CSOM/SPO, get all site and sub-sites Url / Name recursively in new or edit forms that needs to add or update a field value by doing little customization, but that little thing leads to research and some coding more then expected as SharePoint OOB features always needs little customization after client demos. well here I am sharing a code snippet that will fetch all sites and subsites Url or Name and add in a dropdown 

<script type="text/javascript" src="/SiteAssets/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/SiteAssets/jquery.SPServices-2013.01.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    var sitePathColumn="Site Path";
    var url="http://myserver";
    var v="";
      $().SPServices({
                operation: "GetWebCollection",
                webURL: url,
                completefunc: function(xData, status) {
                    $(xData.responseXML).find("Web").each(function() {
                        var weburlvar = $(this).attr("Url").replace(url,"");
                        var titlevar = $(this).attr("Title");
                        v+="<option value='"+weburlvar +"'>"+titlevar +"</option>";
                        $().SPServices({
                            operation: "GetWebCollection",
                            webURL: weburlvar ,
                            completefunc: function(xData, status) {
                            var subsite=1;
                                $(xData.responseXML).find("Web").each(function() {
                                    v+="<option value='"+$(this).attr("Url").replace(url,"")+"'>&nbsp;&nbsp;"+subsite+". " + $(this).attr("Title")+" </option>";
                                    subsite++;
                                });
                            }
                        });
                    });
                }
            });   
var DropDown="<TR><TD width='190' class='ms-formlabel' noWrap vAlign='top'><H3 class='ms-standardheader'><NOBR>"+sitePathColumn;
DropDown+=" <SPAN title='This is a required field.' class=ms-formvalidation> *</SPAN></NOBR></H3></TD><TD class='ms-formbody' vAlign='top'><SPAN><select id='configDropDown' onchange='UpdateField();'>"+v+"</select><BR></SPAN></TD></TR>";
        $("td.ms-formlabel h3 nobr").each(function(index){
            if($(this).text().indexOf('*')>0 && $(this).text().indexOf(sitePathColumn)>-1)
                {   
                    $(this).closest('tr').css('display','none');   
                    $(this).closest('tr').parent().prepend(DropDown);   
                }
            if($(this).text()==sitePathColumn)
                {    $(this).closest('tr').css('display','none');    }
        });           
});
function UpdateField(){
$('input[title="Site Path"]').val($("#configDropDown").val());
GetLists($("#configDropDown").val());
}
function  GetLists(siteUrl){

    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    var collList = oWebsite.get_lists();

    this.listInfoCollection = clientContext.loadQuery(collList, 'Include(Title, Id)');
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    var listInfo = '';
    for (var i = 0; i < this.listInfoCollection.length; i++) {
        var oList = this.listInfoCollection[i];
        listInfo += '\nTitle: ' + oList.get_title() + ' ID: ' + oList.get_id().toString();
        alert(oList.get_type());
    }
   // alert(listInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>



if you have any doubt just use comment section or contact form, I'll reply you soon,

Saturday, 12 March 2016

Use of SharePoint ClientPeoplePicker, people picker, people editor, set initial value, js, jQuery, and C# boh ways

SharePoint newly introduced ClientPeoplePicker PeopleEditor, PeoplePicker control, that is really good control in terms of customer experience.

We will see today that how we should use SharePoints People Picker.

instead of using below tradition people picker that introduced before SharePoint 2010 / MOSS

<SharePoint:PeopleEditor ID=”spPeoplePicker” runat=”server” SelectionSet=”User” />


and setting javascript to fetch uses while typing on control Microsoft have done this or we can say Microsoft baought it and fit it in sharepoint 2013 release.
we can use ClientPeoplePicker

Assuming audience have basic knowledge of SharePoint coding.

<SharePoint:ClientPeoplePicker ValidationEnabled="true" ID="pplDemoPraveen" runat="server" VisibleSuggestions="5" AutoFillEnabled="True" AllowEmailAddresses="true" Rows="1" AllowMultipleEntities="false" CssClass="ms-long ms-spellcheck-true" Height="85px"  />



C# Code to get SPUser:


if( pplDemo.ResolvedEntities.Count > 0)
{
SPUser oUser = oWeb.SiteUsers[((PickerEntity)pplDemo.ResolvedEntities[0]).Key];

             if (oUser != null)
             {
               // do your stuff.
             }
}


Now see How can we get selected value from JavaScript / jQuery / client side
I am putting sample to get json details which you can get and its format, you can pick what ever details you want.


// value from first input field in client people picker div
var data = $("Div[title='YourPPLPicker'] > input" ).val(); 
var json = JSON.parse(data);

// and now you can see the properties
alert(json[0].DisplayText);

/*
    [
    {
    "Key":"i:0#.w|Domain\\userLogin",
    "Description":"Domain\\userLogin",
    "DisplayText":"Praveen, P",
    "EntityType":"User",
    "ProviderDisplayName":"Active Directory",
    "ProviderName":"AD",
    "IsResolved":true,
    "EntityData":
        {"Title":"Arch",
        "MobilePhone":"+91-88",
        "SIPAddress":"",
        "Department":"",
        "Email":"Praveen@domain.com"
        },
    "MultipleMatches":[],
    "AutoFillKey":"i:0#.w|Domain\\userLogin",
    "AutoFillDisplayText":"Praveen P",
    "AutoFillSubDisplayText":"",
    "AutoFillTitleText":"xyz@xyz\nActive Directory\xyz\\xyz",
    "DomainText":"userLogin.local",
    "Resolved":true,
    "LocalSearchTerm":"xcv"
    }
    ]
*/
For more details please refer 

https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.clientpeoplepicker_members.aspx



--
Comments & Feedback are welcome, and yeah don't forget to share make short link wherever needed.
.

Thursday, 30 July 2015

Update Modified by and Created by in SharePoint list

Some of you have face the situation to update list with large number of items or some time we have to change, so that lead to change Modified By to your name; Modified or created by names of all items, yeah we are aware about System.Update() method but if data has populated and no code action will take place and requirement says to update because we don't wants to confuse client/Business users and his customers so in very rare and after approval we execute it to update modified and created by names.

We can use below script to update thousands of list items in single shot. but take care once changes are done by PowerShell can not be roll back. 

so to update SharePoint list items simply can save below PowerShell script in a .PS1 file and run it with Elevated privileges in SharePoint server where you has permission to modify items. 

PowerShell:


<# Created by: MakrShortWork
   Purpose:   To update Modified and created by Names.
   Created Date: June, 2011
#>

  $web = Get-SPWeb "http://YourWebUrl"
  $spList =  $web.Lists["ListName"]  
  $ListItemID = 23;
  $UserName =$ web.EnsureUser("domain\useridLoginId");  
     
  $caml = '<Where><Eq><FieldRef Name="ID" /><Value Type="Text">{0}</Value></Eq> </Where>' -f $ListItemID
  $query = new-object Microsoft.SharePoint.SPQuery
  $query.Query=$caml
  $oItem = $spList.GetItems($query)[0]

# in List Created by -Author and Modifed by -Editor
     $oItem["Author"] = $UserName           
     $oItem["Editor"] = $UserName  

     # You can add other fields here any field value data time etc....
     $oItem.Update()
    # You can use SystemUpdate(true/false);

Please run script on SharePoint server with Admin privileges,
Share or refer the link, that may help some one

-