1

I am trying to create SharePoint app. Basic idea is to create document in hostweb document library from AppWeb (document template stored in AppWeb doc lib).

In Details :

  1. I have created ribbon custom action in HostWeb (ribbon button). Once we click on that button in ribbon then user redirect to App default page.

  2. In App I have created one document library and some document templates uploaded in it.

  3. I have retrieved all document present in AppWeb document library in default page where I have given link once we click on that document link new form will open and that ask us document name (To create document using that template ). Once we enter document name and click on “Create” button that will create document to HostWeb document library.

Completed Part :

  1. Creation of ribbon custom action.

  2. Creation of document library in HostWeb and retrieve all documents in default.apsx page.

  3. Open new form on click of document link.

Looking for:

  1. Once I will enter document name using that name document create to HostWebb. (By using CrossDomainRequest I have got context of hostWebb but looking for how to create new doc using that name which entered in form in AppWebb )

HostWebb Ribbon button :

enter image description here

AppWebb default page :

enter image description here

New form open once we click on document link :

enter image description here

Please find below code

App.js

'use strict';
var context;
var hostweburl;
var appweburl;
var appContextSite;
var list;
var web;
var DocLib;
var folderDir;
var listId;
var sourceUrl;
var hostWebapp;
var sourceUrl1;
var sourceurl2;

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getUrl);

    var scriptbase = hostweburl + "/_layouts/15/";

    $.getScript(scriptbase + "SP.Runtime.js",
          function () {
          $.getScript(scriptbase + "SP.js",
          function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
                  );
          }
          );
});

function getUrl() {

    hostweburl = getQueryStringParameter("SPHostUrl");
    //console.log("HostWeb Url without decode :" + hostweburl);
    appweburl = getQueryStringParameter("SPAppWebUrl");
    //console.log("App Url without decode :" + appweburl);
    hostweburl = decodeURIComponent(hostweburl);
    console.log("Host Web Url :" + hostweburl);
    appweburl = decodeURIComponent(appweburl);
    console.log("App Web Url  :" + appweburl);
    hostWebapp = extractHostname(hostweburl);
    console.log(" HostWebApp url :" + hostWebapp);
    var url = document.URL;
    listId = decodeURIComponent(getQueryStringParameter("SPListId"));

    console.log("ListID :" + decodeURIComponent(listId));

    sourceUrl1 = getQueryStringParameter("SPSource");

    sourceurl2 = decodeURIComponent(sourceUrl1);
    console.log("SourceUrl :" + decodeURIComponent(sourceurl2));

    folderDir = getQueryStringParameter2("RootFolder", sourceurl2);
    folderDir = decodeURIComponent(folderDir);

    console.log(" Folder Url:  " + folderDir)

    var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js",
            function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execOperation); }
            );
        }
    );
}
    function execOperation() {
    context = new SP.ClientContext(appweburl);
    var factory =
        new SP.ProxyWebRequestExecutorFactory(
            appweburl
        );
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, appweburl);
    web = appContextSite.get_web();
    context.load(web);
    list = web.get_lists().getByTitle("TempLib");
    context.load(list);
    var query = new SP.CamlQuery.createAllItemsQuery();
    DocLib = list.getItems(query);
    context.load(DocLib);

    context.executeQueryAsync(
        successHandler, errorHandler
    );
}

function successHandler(data, req) {

   // alert("List loaded Successfully");

    var announcementsHTML = "";
    var enumerator = DocLib.getEnumerator();
    var items = [];
    while (enumerator.moveNext()) {
        var announcement = enumerator.get_current();
        var fName = announcement.get_item("Title");
        var fUrl = announcement.get_item("FileRef");
        fName = fUrl.substring(fUrl.lastIndexOf("/") + 1, fUrl.length);
        announcementsHTML = announcementsHTML +
            "<p><h1>" + fName +
            "</h1>" + fUrl +
            "</p><hr>";

        items.push('<li><a class="lfTmpLink" href="' + fUrl + '"><h1>' + fName + '</h1></a></li>');
    }

    $('#ShowData').append(items.join(''));
}

function errorHandler(data, error, errorMessage) {
    document.getElementById("renderAnnouncements").innerText =
        "Please re-Check your code " +
        errorMessage;
}

function extractHostname(url) {

    var hostname;
    if (url.indexOf("//") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }
    hostname = hostname.split(':')[0];
    hostname = hostname.split('?')[0];
    hostname = window.location.protocol + "//" + hostname;
    return hostname;
}

function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
function getQueryStringParameter2(paramToRetrieve, url) {
    if (url.indexOf("?") > -1) {
        var params = url.split("?")[1].split("&");
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve)
                return singleParam[1];
        }
    }
    else {
        return "";
    }

}

function execCrossDomainRequest()
{
    var context;
    var factory;
    var appContextSite;

    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);
    this.web = appContextSite.get_web();
    context.load(this.web);

    context.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );

    function successHandler() {
        console.log("Root Web Title= " + this.web.get_title());

        $(document).on('click', '.lfTmpLink', function (event) {

            var hLink = $(this).attr('href');
            var appWebHost = extractHostname(document.URL);
            var tmpUrlComplete = appWebHost + "/" + hLink;
            event.preventDefault();

            var list = web.get_lists().getById('Shared Documents');
            var folder = list.get_rootFolder();
            var templateUrl = tmpUrlComplete;

            $("#myForm").show();

            $('#submit').click(function () {
                var newDocumentName = $("#textarea").val();
                console.log("File Name title=" + newDocumentName);

            });

            $('#cancle').click(function () {
                document.getElementById("myForm").style.display = "none";
            });

            //var libUrl = sourceurl2;
            //console.log("Template Url " + tmpUrlComplete);
            //console.log("Library Url " + libUrl);
            //console.log("Folder Url " + libUrl);
            //var destinationFolder = (folderDir == '' ? libUrl : (hostWebapp + "/" + folderDir));
            //console.log("Destination folderurl :" + destinationFolder);
            //CoreInvoke('createNewDocumentWithProgID', tmpUrlComplete, destinationFolder, 'SharePoint.OpenDocuments', false, 'ms-word');
            //return false;


        });

    }

    function errorHandler(data, errorCode, errorMessage) {
        console.log("Could not complete cross-domain call: " + errorMessage);
    }


}

Default.aspx

<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>

        <ul id="ShowData">

        </ul>

        <p id="queryParams"></p>
    </div>


    <%--<button class="open-button" onclick="openForm()">Open Form</button>--%>

<div class="form-popup" id="myForm">
  <form class="form-container">
    <h1>Template</h1>

    <label for="name"><b>Enter document name</b></label>
    <input type="text" placeholder="Enter document name" id="textarea" required>

    <button type="submit" class="btn" id="submit" >Create</button>

    <button type="button" class="btn cancel" id="cancle">Close</button>

  </form>
</div>


</asp:Content>

Elements.xml (Ribbon Button) :

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="19cdef82-a956-4ba5-9d2c-f5ca469cbef5.LFTEMPLATE"
                RegistrationType="List"
                RegistrationId="101"
                Location="CommandUI.Ribbon"
                Sequence="10001"
                Title="Invoke &apos;LFTEMPLATE&apos; action">
    <CommandUIExtension>
      <!-- 
      Update the UI definitions below with the controls and the command actions
      that you want to enable for the custom action.
      -->
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.New.Controls._children">
          <Button Id="Ribbon.ListItem.Actions.LFTEMPLATEButton"
                  Alt="Request LFTEMPLATE"
                  Sequence="100"
                  Command="Invoke_LFTEMPLATEButtonRequest"
                  LabelText="Templates"
                  TemplateAlias="o1"
                  Image32by32="_layouts/15/images/placeholder32x32.png"
                  Image16by16="_layouts/15/images/placeholder16x16.png" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="Invoke_LFTEMPLATEButtonRequest"                                                                                                                     
                          CommandAction="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={SelectedItemId}&amp;SPListId={SelectedListId}&amp;SPSource={Source}"/>
      </CommandUIHandlers>
    </CommandUIExtension >
  </CustomAction>
</Elements>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.