Sunday, 22 November 2015

CURD operations on list using RESTAPI and AngularJS in SharePoint 2013 - Part2

Hi, in my previous post we have seen how to get SharePoint list data and show in tabular format using REST API with AngularJS.

Now i want to show to create new form and add new list item to list using REST API and AngularJS.


Here i will add one button under list item details and name it as "Create New" and it's look like as below.




Now when we click on the button i will display a new form to insert new item.

It looks like as below.



In this new form, we have single line of text, multiline of text, date picker, hyperlink, true/false(checkbox), dropdown and people picker.

This example, i have covered most of the column types.

For people picker am using Clientpeoplepicker.

In this example, am using dropdown column and dropdown values are loaded while page loading as below script.

// Loading dropdown default values
$scope.items = [
    { id: 1, name: 'Action'},
    { id: 2, name: 'Drama'}];

And dropdown field design is


<div class="form-group">

  <label class="col-sm-2 control-label">Book type: </label>
  <div class="col-sm-10">
   <select ng-model="selectedItem"
          ng-options="item as item.name for item in items">
  </select>
 </div>
</div>

For date picker, am using third party control for better look i.e. KENDO

and date picker field look as below




First we need to include all the required js and css files

<link rel="stylesheet" href="<sitename>/SiteAssets/Kendo/kendo.common-material.min.css" />
<link rel="stylesheet" href="<sitename>/SiteAssets/Kendo/kendo.material.min.css" />
 <script src="<sitename>/SiteAssets/Kendo/jquery.min.js"></script>
 <script src="<sitename>/SiteAssets/Kendo/angular.min.js"></script>
 <script src="<sitename>/SiteAssets/Kendo/kendo.all.min.js"></script>

Now load kendo module as below

var myAngApp = angular.module('bookapp', ["kendo.directives"]);

For, people picker am using SPClientpeoplepicker.

For this, we need to load the below script.

$(document).ready(function () {

    // Specify the unique ID of the DOM element where the

    // picker will render.
     initializePeoplePicker('peoplePickerDiv');

});

function initializePeoplePicker(peoplePickerElementId) {


    // Create a schema to store picker properties, and set the properties.

    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = false;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '280px';

    // Render and initialize the picker.

    // Pass the ID of the DOM element that contains the picker, an array of initial
    // PickerEntity objects to set the picker value, and a schema that defines
    // picker properties.
    SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}

People picker looks like as below and when users start typing can see search results as below.



Now when user enter all the details and click on add button all these details need to add to list and refresh the page with added item.

now we need to update control as below,

###############################################

$scope.Add = function() {
$scope.Booktype=$scope.selectedItem.name;
if($scope.HasPassport) 
{
$scope.isread=true;
}
else
{
$scope.isread=false;
}
    var d = new Date($scope.dateString);
    $scope.Bookreleasedate= d.toISOString();
    var userlanid="'"+$.parseJSON($('#peoplePickerDiv_TopSpan_HiddenInput').val())[0].Key+"'";
    var name=userlanid.replace(':', '%3A').replace('|', '%7C').replace('#', '%23').replace(/'/g, '%27');
var promisedata=bookService.getuserid(name,$scope);
promisedata.then(function(data) {
bookService.addBook('Bookshelf',$scope);
console.log('This ANOTHER success method was assigned AFTER calling to async()', data);
}, function(error) {
console.log('This ANOTHER failure method was assigned AFTER calling to async()', error);
});
    }

update service as below where actual item adding to list.

###############################################################

 //Create a book
this.addBook = function (listTitle,$scope) {
        var dfd = $q.defer();
       $http.defaults.headers.post['X-HTTP-Method'] = "";
       var restUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('" + listTitle + "')/items";
       $http.post(restUrl, {
       __metadata: {
           type: "SP.Data." + listTitle + "ListItem"
       },
       Title: $scope.BookTitle,
Booksummary: $scope.BookSummary,
Bookisread: $scope.isread,
ReleaseDate: $scope.Bookreleasedate,
Bookreleasedate:$scope.Bookreleasedate,
EmpId: $scope.emp,
Booktype:$scope.Booktype,
storeurl: {
                    __metadata: { type: 'SP.FieldUrlValue' },
                    Description: $scope.storedescr,
                    Url: $scope.storeurl
},
   }).success(function (data) {
       //resolve the new data
alert("Book has been added successfully.")
       dfd.resolve(data.d);
   }).error(function (data) {
       dfd.reject("failed to add book");
   });
   return dfd.promise;
}

// Completed add book

this.getuserid = function (username,$scope) {
   var dfd = $q.defer();
       $http.get(_spPageContextInfo.webAbsoluteUrl+"/_api/web/siteusers(@v)?@v="+username).success(function (data) {
       //resolve the new data
       dfd.resolve(data.d);
$scope.emp=data.d.Id;
   }).error(function (data) {
alert(data);
       dfd.reject("failed to get user id");
   });
   return dfd.promise;
}

while adding new item which is having peoplepicker field then we need selected user id so for that we have used getuserid function to get selected user id.




In my next post, will see how to update and delete item using REST API.

Here the complete source code.

Wednesday, 11 November 2015

Error Type: The name ‘InitializeControl’ does not exist in the current context

Hi, 

Today i want to explain how to resolve "The name ‘InitializeControl’ does not exist in the current context" error.

This error ever common when you try to build SharePoint solution from visual studio 2010/2013.

This error mainly comes when you do not have access to connect SharePoint site.

To confirm this, Try to create new SharePoint solution from visual studio, give site URL where you want to debug and click on connect. Then you will get the below error.

The local SharePoint server is not available. Check that the server is running and connected to the SharePoint farm.


It means that you do not have access to connect to SharePoint server from visual studio.

To resolve the above two issues  you should have content database access of config database and the web application.

Now, Go to SharePoint powershell management and execute the below script/queries

Add-SPShellAdmin -UserName <domain\username>

--This will add permissions to the config database in SharePoint 2010

$db = Get-SPContentDatabase -WebApplication <web application URL>

Add-SPShellAdmin -UserName <domain\username> -database $db.Id

Replace "<domain\username>" with the user who is going to work and <web application URL> with the web application.

Now you can happily start working on :).