Wednesday, July 31, 2013

Cascade DropDownList in SharePoint 2010 using SPServices SPCascadeDropdowns

When you select a value from protocol dropdownlist branches will be automatically populated.




add below code underneath placeholder or add content editor webpart to your page
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
 

<script language="javascript" type="text/javascript" src="/shared documents/jquery-1.8.2.min.js"></script>
<script language="javascript" type="text/javascript" src="/shared documents/jquery.SPServices-0.7.2.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $().SPServices.SPCascadeDropdowns({
            relationshipList: "ListBranches",
            relationshipListParentColumn: "Protocols",
            relationshipListChildColumn: "Title",
            parentColumn: "Protocols",
            childColumn: "Branches",
            debug: true
        });

    });
</script>


I have 2 lists called Protocols and ListBranches.
ProtocolsList Columns
Title
LilstBranches columns
 Title
Protocols (lookup  field)
Cascade List Columns
Title
Branches
Protocols





add below code underneath placeholder or add content editor webpart to your page
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
 

<script language="javascript" type="text/javascript" src="/shared documents/jquery-1.8.2.min.js"></script>
<script language="javascript" type="text/javascript" src="/shared documents/jquery.SPServices-0.7.2.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $().SPServices.SPCascadeDropdowns({
            relationshipList: "ListBranches",
            relationshipListParentColumn: "Protocols",
            relationshipListChildColumn: "Title",
            parentColumn: "Protocols",
            childColumn: "Branches",
            debug: true
        });

    });

</script>

Read SharePoint 2010 List Items using Client Object Model when DropDownList changed

As per my requirement I have to populate ‘Branch’ text box value automatically when ‘protocol’ dropdownlist  select index changed in a SharePoint 2010 List.

 For this we have a workaround like this.
1)      Attach onchange event to the dropdownlist dynamically
2)      Read SharePoint  control (here dropdownlist)
3)     Read SharePoint list item (Branch value) based on dropdownlist ‘Protocol’  value by using Clinet Object Model

auto population branch field

reading  Branches from this list


<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
 
 add below code here or add content editor webpart to newform and editform page

<script type="text/javascript">

           _spBodyOnLoadFunctionNames.push("SetDropDownEvent");

           var ddlProtocol;

           function SetDropDownEvent() {
               getField('select', 'Protocol').onchange = function () { GetProtocol() };
               //alert('SetDropDownEvent');
           }

           function getField(fieldType, fieldTitle) {

               var docTags = document.getElementsByTagName(fieldType);
               //alert(docTags.length);
               for (var i = 0; i < docTags.length; i++) {
                   if (docTags[i].title == fieldTitle) {
                       return docTags[i]
                   }
               }
           }

           function GetProtocol() {
               //alert('syncDropDowns');
               lookupField = getField('select', 'Protocol');
               lookupSelectedItem = lookupField.options[lookupField.selectedIndex];
               // alert('lookupSelectedItem' + lookupSelectedItem.text);
               ddlProtocol = lookupSelectedItem.text;
               alert('ddlProtocol' + ddlProtocol);
               GetBranchByProtocol(lookupSelectedItem.text);
           }


           //  ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
           function GetBranchByProtocol(protocolid) {
               // alert('protocolid' + protocolid);


               var clientContext = new SP.ClientContext.get_current();
               var oList = clientContext.get_web().get_lists().getByTitle('TestList');

               var camlQuery = new SP.CamlQuery();

               camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ProtocolNew\' /><Value Type=\'Text\'>' + protocolid + '</Value></Eq></Where></Query></View>');
               this.collListItem = oList.getItems(camlQuery);

               clientContext.load(collListItem);

               clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

           }

           function onQuerySucceeded(sender, args) {

               var listItemInfo = '';
               var listItemEnumerator = collListItem.getEnumerator();
               while (listItemEnumerator.moveNext()) {
                   var oListItem = listItemEnumerator.get_current();

                   if (ddlProtocol) {
                       branchField = getField('input', 'Branch');
                       // alert('branchField' + branchField.id);
                       document.getElementById(branchField.id).value = oListItem.get_item('Title')
                       // alert('branchvalue' + document.getElementById(branchField.id).value);
                   } else {
                       alert('else');
                       branchField = getField('input', 'Branch');
                       // alert('branchField' + branchField.id);
                       document.getElementById(branchField.id).value = '';
                   }
                   //break
               }


           }

           function onQueryFailed(sender, args) {

               alert('fail');
               alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
           }
    
     </script>






Get List Items where 'Name' field contains 'x'

This script gets results from list items where name field contains ‘Agenda’.  Also it will create a .csv file where you are running this script. You can see as report when you open this file in the excel.


$URL = "http://spdev5:8002/sites/library"
$site = New-Object Microsoft.SharePoint.SPSite($URL)
$web = $site.openweb("")

Try
{
#logging (it will create a .csv file where u r running this script)
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "Agenda_Title"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)
$header = "DocumentID;Protocol;Name;ContentType;DocType;URL;Agenda Y/N?"
$header | out-file -FilePath $logfile

$list = $web.Lists["DSMB-SMC Documents"]
$items= $list.items
$time = Get-Date -Format g

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$camlQuery ="<Where><Contains><FieldRef Name='FileLeafRef' /><Value Type='File'>Agenda</Value></Contains></Where>"
$spQuery.Query = $camlQuery
$spQuery.ViewAttributes = "Scope=Recursive";
$spListItems = $list.GetItems($spQuery)

Write-Host "count" $spListItems.count

$count=1
$listurl =$list.ParentWeb.Url
Write-Host "listurl "  $list.ParentWeb.Url
#Write-Host "rrot"  $list.RootFolder.Url
$protocol =$null

    foreach ($item in $spListItems)
            {
           
                   $doctype = $item["DOC TYPE"]
                  if ($item["PROTOCOL"] -ne $null)
                  {
                      $lookup  = [Microsoft.SharePoint.SPFieldLookupValue]$item["PROTOCOL"];  
                      $protocol = $lookup.LookupValue;
                  }
                  else
                  {
                   $protocol = $null
                  }
                 
                $itemurl =    $listurl + "/" + $item.url
                 
                  Write-Host $count  $item.ID $protocol
                  $msg = ("{0};{1};{2};{3};{4};{5};{6}" -f $item.ID,$protocol ,$item.Name,$item.ContentType.Name, $doctype ,$itemurl,"")
                  $msg | out-file -FilePath $logfile  -append
                  $count++
     
                  if($count -eq 6)
                  {
                        #break;
                  }
            }
      }
Catch
      {
            Write-Host "Error occurred while Updating:"  $_  -ForegroundColor Red
          $msg = ( "{0}" -f "Error occurred while Updating:" + $_)
            $msg | out-file -FilePath $logfile  -append
      }


$web.Dispose()
$site.Dispose()






Tuesday, July 30, 2013

Create and Consume custom asp.net Web Service in SharePoint 2010 using Jquery

follow below steps to create a asp.net web service



you can download the webservice code from here. 


you just need to change the site url. for this select project and press F4 then it will show properties window. right click deploy it.


I am consuming this webservice using jquery. 

Please this code below this tag
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

Update web service url and soap message as well.


<script src="/shared%20documents/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script language="javascript">

        $(document).ready(function () {

            alert();

            var soapMessage = '<?xml version="1.0" encoding="utf-8"?> \
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">\
  <soap12:Body>\
    <GetSiteListCount xmlns="http://tempuri.org/" />\
  </soap12:Body>\
</soap12:Envelope>'


            $.ajax({
                url: "http://spdev5:8004/_layouts/webservicedemo/mycustomws.asmx?op=GetSiteListCount",
                type: "POST",
                dataType: "xml",
                data: soapMessage,
                processData: false,
                contentType: "text/xml; charset=\"utf-8\"",
                success: OnSuccess,
                error: OnError
            });
        });


        function OnSuccess(data, status) {
            alert(data.text);
        }

        function OnError(request, status, error) {
            alert('error' + request + status + error);
        }</script>

Friday, July 26, 2013

Attach OnChange Event To SharePoint Lookup Field By Using JavaScript

as per my requirement I have to populate Branches dropdownlist based on Protocols dropdownlist value. for this we added javascript onchange function to the protocols dropdownlist dynamically. 

reading Branches values by using ECMA script client object model  as they are in the different list. you can see the images below.

you can add this script content editor webpart or designer.


   <script type="text/javascript">

        _spBodyOnLoadFunctionNames.push("SetDropDownEvent");

        var ddlProtocol;

        function SetDropDownEvent() {
            getField('select', 'Protocol').onchange = function () { GetProtocol() };
            //alert('SetDropDownEvent');
        }

        function getField(fieldType, fieldTitle) {

            var docTags = document.getElementsByTagName(fieldType);
            //alert(docTags.length);
            for (var i = 0; i < docTags.length; i++) {
                if (docTags[i].title == fieldTitle) {
                    return docTags[i]
                }
            }
        }

        function GetProtocol() {
            //alert('syncDropDowns');
            lookupField = getField('select', 'Protocol');
            lookupSelectedItem = lookupField.options[lookupField.selectedIndex];
            // alert('lookupSelectedItem' + lookupSelectedItem.text);
            ddlProtocol = lookupSelectedItem.text;
            alert('ddlProtocol' + ddlProtocol);
            GetBranchByProtocol(lookupSelectedItem.text);
        }


        //  ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
        function GetBranchByProtocol(protocolid) {
            // alert('protocolid' + protocolid);


            var clientContext = new SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('TestList');

            var camlQuery = new SP.CamlQuery();

            camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ProtocolNew\' /><Value Type=\'Text\'>' + protocolid + '</Value></Eq></Where></Query></View>');
            this.collListItem = oList.getItems(camlQuery);

            clientContext.load(collListItem);

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

        }

        function onQuerySucceeded(sender, args) {

            var listItemInfo = '';
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();

                if (ddlProtocol) {
                    branchField = getField('input', 'Branch');
                    // alert('branchField' + branchField.id);
                    document.getElementById(branchField.id).value = oListItem.get_item('Title')
                    // alert('branchvalue' + document.getElementById(branchField.id).value);
                } else {
                    alert('else');
                    branchField = getField('input', 'Branch');
                    // alert('branchField' + branchField.id);
                    document.getElementById(branchField.id).value = '';
                }
                //break
            }

            //alert(listItemInfo.toString());
        }

        function onQueryFailed(sender, args) {

            alert('fail');
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    
     </script>



Followers