Friday, September 28, 2018

Item Creation Using Sitecore Services Client API -Item Serive (Data from CSV/JSON)

Sitecore.Services.Client provides a service layer on both the server and the client side of Sitecore applications that you use to develop data-driven applications.

It Provides Two Services

ItemService: this service gives you access to regular Sitecore items.
EntityService: this service gives you access to business objects that you define.

In this Post, we will See about Sitecore Item Creation Using Item Service.

What is ItemService ?

 It Provides an Single HTTP End Point and API that you used to interact with sitecore items over HTTP.

Lets Start,

Step 1:  Create a View for uploading a file in the format either JSON or CSV(JSON more Preferable)
If you use Json ,Skip the Step2

Step 2:  Reading CSV File From View.

        var files = $('#fileID').prop('files');
        var file = files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var texto = e.target.result;
            CreateCommentItem(csvJSON(texto), "Path");            
        };
        reader.readAsText(file);


The Above code is for Getting File from User end and File Reading.


function csvJSON(csv) {  
    var lines = csv.split('\r');
    for (let i = 0; i < lines.length; i++) {
        lines[i] = lines[i].replace(/\s/, '')//delete all blanks
    }
    var result = [];
    var headers = lines[0].split(",");
    for (var i = 0; i < lines.length; i++) {
        var obj = {};
        var currentline = lines[i].split(",");
        for (var j = 0; j < headers.length; j++) {
             obj[headers[j].toString()] = currentline[j];           
        }
        result.push(obj);
    }
     return result; //JavaScript object
   // return JSON.stringify(result); //JSON
}

The above function will convert your CSV File Into JSON Formatted file.


Step 3:  You need to Initialize the Item Service for Item Creation.


function CreateCommentItem(arr, path) {

//Item Service Initialization
var Service = new ItemService({ url: '/sitecore/api/ssc/item' });

    $.each(arr, function (key, val) {
        if (arr[key].ItemName) {
            arr[key].TemplateID = "Templated ID Goes Here...";
        }
    });
    $.each(arr, function (i, val) {
        if (arr[i].ItemName) {
            Service.create(arr[i]).path(path).execute().then(function (item) {
                window.alert("works");
            })
                .fail(function (err) {
                    window.alert(err);
                });
        }
    });

    event.preventDefault();
    return false;
}


Note: If do not type the correct case for properties when invoking the services, the service returns 500 Error.


Step 4: Don’t forget to add this line to your View

<script src="/sitecore/shell/client/Services/Assets/lib/itemservice.js">
</script>


Step 5: All Now Set, Run Your View Create Items Using ItemService. Happy Coding :)

1 comment:

  1. Hello, with sitecore 9.3 I cannot add reference from step 4.
    When I check logs in Chrome developer tool I can see call to /sitecore/shell/client/Services/Assets/lib/itemservice.js returns with status 302 and I am
    redirect to login page.
    I tried to patch Sitecore.Services.Client.config file in order to allow Anonymous access but I am still redirected to http://events.tac.local/login.aspx?ReturnUrl=%2Fsitecore%2Fshell%2Fclient%2FServices%2FAssets%2Flib%2Fitemservice.js which then redirects to http://events.tac.local/sitecore/service/notfound.aspx?item=%2flogin&user=extranet%5cAnonymous&site=events and this request is with status 404.
    Any thought on this?
    Thanks,
    Srdjan

    ReplyDelete

Check the users Logged into the sitecore backend

Hi, Today I'm going to discuss about " how to check the concurrent users logged into the sitecore backend ? ". For this ...