How to: Create a basic app for SharePoint by using "Napa" Office 365 Development Tools

apps for SharePoint

Learn how to create a basic app for SharePoint by using "Napa" Office 365 Development Tools.

Run button Run this sample now!

Last modified: September 09, 2014

Note Note

You can also build an app for SharePoint by using Visual Studio. For more information, see Get started developing apps for SharePoint.

Applies to: apps for SharePoint | Office 365 | SharePoint Foundation 2013 | SharePoint Server 2013

You need the following components to complete this walkthrough:

  • An Office 365 account

  • The "Napa" Office 365 Development Tools app

For more information about how to set up an Office 365 account, see Sign up for an Office 365 Developer Subscription, set up your tools and environment, and start deploying apps. For more information about Office 365 development, see Create apps for Office and SharePoint by using "Napa" Office 365 Development Tools.

By following this walkthrough, you can learn how to create a simple app for SharePoint by using "Napa" Office 365 Development Tools. The app that you’ll create includes controls and code for managing lists and list items, but most apps for SharePoint are far more powerful. For example, you can create an app for SharePoint that helps users track expenses and plan events. By using "Napa" Office 365 Development Tools, you can create your apps for SharePoint inside your browser instead of in Visual Studio. At any time, you can download your project and open it in Visual Studio for more advanced scenarios.

For more information about "Napa" Office 365 Development Tools, see Create apps for Office and SharePoint by using "Napa" Office 365 Development Tools.

In this procedure, you'll create a project for the app for SharePoint.

To create an app for SharePoint project

  1. Open the "Napa" Office 365 Development Tools app on the Office 365 page.

  2. Choose the Add New Project tile, and then choose the App for SharePoint tile.

  3. Name the project Test app for SharePoint, and then choose the Create button.

    The code editor opens and shows the default webpage, which already contains some sample code that you can run without doing anything else.

In the app for SharePoint, add controls to the default home page for creating and deleting a generic SharePoint list and getting the current number of lists in the web of the app for SharePoint. You’ll add code for the controls later.

To add controls to the home page

  1. On the left side of the page under the Pages folder, choose the Default.aspx page if it isn’t already selected, as shown in Figure 1.

    Figure 1. Default.aspx page node

    Figure 1. Default.aspx page node

    The Default.aspx webpage appears in the code editor.

  2. In the PlaceHolderMain section, add this code under the existing HTML

    <br />
    <div>
        <button id="getListCount">Get count of lists in web</button>
    </div>
    <br />
    <div id="starter">
        <input type="text" value="List name here" id="createlistbox"/><button id="createlistbutton">Create List</button>
        <p>
        Lists
        <br />
        <select id="selectlistbox" ></select><button id="deletelistbutton">Delete Selected List</button>
        </p>
    </div>
    

    The HTML creates these controls.

    • A button that gets the number of lists in the web of the app for SharePoint.

    • A button for creating a generic SharePoint list and another button for deleting the list.

    • A list of lists that are available within the app.

In this procedure, you’ll add some JavaScript code so that users can create and delete lists in the app for SharePoint.

To add code for creating and deleting lists

  1. Choose the Scripts folder, and then choose the App.js link, as shown in Figure 2.

    Figure 2. App.js JavaScript file node

    Figure 2. App.js JavaScript file node

    The default JavaScript code file from the project template opens for editing. This file contains the code that's used in your app for SharePoint. You could add another .js file and add code to it instead of to the existing file. But, for this example, add it to the App.js file that's provided.

    In the next step, you’ll define the functions for the controls that you created in the previous procedure.

    Function Name

    Description

    getWebProperties()

    Connected to the getListCount control—retrieves the number of lists in the web.

    createlist()

    Connected to the createListButton control—creates a generic SharePoint list.

    deletelist()

    Connected to the deletelistbutton control—deletes the list that the user chose from the list of available lists.

    You’ll also call the welcome() and displayLists() functions, which this walkthrough will describe later.

  2. In the App.js file, add the web, lists, and listItemcollection variables to the two default variables, and change the code in the $(document).ready() function to the following example.

    Note Note

    Error squiggles will appear in this code. They'll disappear in later steps.

    'use strict';
    
    var context = SP.ClientContext.get_current();
    var user = context.get_web().get_currentUser();
    var web = context.get_web();
    var lists = web.get_lists();
    var listItemCollection;  // This variable is used later when you add list items.
    
    (function () {
    
    // This code runs when the DOM is ready and creates a context object which is 
    // needed to use the SharePoint object model.
    $(document).ready(function () {
        getUserName();
        $("#getListCount").click(function (event) {
            getWebProperties();
            event.preventDefault();
        });
    
        $("#createlistbutton").click(function (event) {
            createlist();
            event.preventDefault();
        });
    
        $("#deletelistbutton").click(function (event) {
            deletelist();
            event.preventDefault();
        });
            displayLists();
        });
    
    

    In the next step, you’ll add JavaScript functions for the definitions. Each function in the code is executed by calling executeQueryAsync(), which executes the current pending request asynchronously on the server by using the client-side object model (CSOM) for SharePoint. When a function executes asynchronously, your script continues to run without waiting for the server to respond. Each executeQueryAsync() call includes two event handlers. One handler responds if the function runs successfully, and the other handler responds if the function fails. This table describes the main functions.

    Function name

    Description

    welcome()

    Gets the current web context reference, and then uses it to set the current user information into the context.

    getWebProperties()

    Gets the collection of lists in the current web and then returns the number of lists.

    displaylists()

    Gets the current collection of lists in this web. If successful, this function adds the name of each list in the collection to the list of available lists.

    createlist()

    Creates a generic SharePoint list (list template type genericList) and gives it the name that the user specifies in the createlistbox control. You can create other types of lists. For more information about list types, see SPListTemplateType Enumeration.

    deletelist()

    Deletes the list that the user chose from the list of available lists.

  3. Add the following code after the onGetUserNameFail() function in App.js.

    function getWebProperties() {
            // Get the number of lists in the current web.
            context.load(lists);
            context.executeQueryAsync(onWebPropsSuccess, onWebPropsFail);
        }
    
        function onWebPropsSuccess(sender, args) {
            alert('Number of lists in web: ' + lists.get_count());
        }
    
        function onWebPropsFail(sender, args) {
            alert('Failed to get list. Error: ' + args.get_message());
        }
    
        function displayLists() {
            // Get the available SharePoint lists, and then set them into 
            // the context.
            lists = web.get_lists();
            context.load(lists);
            context.executeQueryAsync(onGetListsSuccess, onGetListsFail);
        }
    
        function onGetListsSuccess(sender, args) {
            // Success getting the lists. Set references to the list 
            // elements and the list of available lists.
            var listEnumerator = lists.getEnumerator();
            var selectListBox = document.getElementById("selectlistbox");
            if (selectListBox.hasChildNodes()) {
                while (selectListBox.childNodes.length >= 1) {
                    selectListBox.removeChild(selectListBox.firstChild);
                }
            }
            // Traverse the elements of the collection, and load the name of    
            // each list into the dropdown list box.
            while (listEnumerator.moveNext()) {
                var selectOption = document.createElement("option");
                selectOption.value = listEnumerator.get_current().get_title();
                selectOption.innerHTML = listEnumerator.get_current().get_title();
                selectListBox.appendChild(selectOption);
            }
        }
    
        function onGetListsFail(sender, args) {
            // Lists couldn’t be loaded - display error.
            alert('Failed to get list. Error: ' + args.get_message());
        }
    
    function createlist() {
            // Create a generic SharePoint list with the name that the user specifies.
            var listCreationInfo = new SP.ListCreationInformation();
            var listTitle = document.getElementById("createlistbox").value;
            listCreationInfo.set_title(listTitle);
            listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
            lists = web.get_lists();
            var newList = lists.add(listCreationInfo);
            context.load(newList);
            context.executeQueryAsync(onListCreationSuccess, onListCreationFail);
        }
    
        function onListCreationSuccess() {
            displayLists();
        }
    
        function onListCreationFail(sender, args) {
            alert('Failed to create the list. ' + args.get_message());
        }
    
        function deletelist() {
            // Delete the list that the user specifies.
            var selectListBox = document.getElementById("selectlistbox");
            var selectedListTitle = selectListBox.value;
            var selectedList = web.get_lists().getByTitle(selectedListTitle);
            selectedList.deleteObject();
            context.executeQueryAsync(onDeleteListSuccess, onDeleteListFail);
        }
    
        function onDeleteListSuccess() {
            displayLists();
        }
    
        function onDeleteListFail(sender, args) {
            alert('Failed to delete the list. ' + args.get_message());
        }
    

The first part of the UI and code is in place, so go ahead and run the app to verify whether it works.

To run the app

  1. At the bottom of the page, choose the run (Run button) button.

    The app is packaged, deployed, and installed on your Office 365 Developer Site.

    After installation, the app for SharePoint starts. If the app doesn’t start automatically because, for example, a popup blocker is enabled, choose the app link to start the app.

  2. Choose the Click here to launch your app in a new window link.

    The screen for the app for SharePoint appears.

  3. Choose the Get count of lists in web button.

    A dialog box specifies that the web for the current app for SharePoint contains two lists. (The web contains the Design Gallery and Master Page Gallery lists by default.)

  4. In the List name here box, enter Test List, and then choose the Create List button.

  5. Open the Lists list to verify that the new list appears in it.

  6. Choose the Get count of lists in web button again.

    The web now contains three lists, including the list that you just created.

  7. In the Lists list, choose Test List, and then choose the Delete Selected List button.

    Test List disappears from the list of available lists.

  8. When you finish, close the browser window, and then choose the Close button in Launch App window to return to the project that you were editing.

Now that users can create and delete lists, you can perform the following steps to enable them to add and delete list items.

To add code and controls for adding and deleting list items

  1. Choose the Default.aspx file to edit it.

  2. Under the selectlistbox element, add this code.

        <p>
        Items
        <br />
        <input type="text" value="item name here" id="createitembox"/><button id="createitembutton">Create Item</button>
        </p>
        <p>
        <select id="selectitembox"></select> <button id="deleteitembutton">Delete Selected Item</button>
        </p>
    

    This code adds an input box where users can specify the name of an item, a button to add the item to the list, and a button to delete the item from the list.

  3. Choose the App.js file to edit it.

  4. In the $(document).ready() function, add definitions for functions that are called when the user chooses the Create Item and Delete Selected Item buttons. Also, add a jQuery event handler for the Lists list box to ensure the list items get updated when you select a new list.

    $("#createitembutton").click(function (event) {
                createitem();
                event.preventDefault();
            });
    
            $("#deleteitembutton").click(function (event) {
                deleteitem();
                event.preventDefault();
            });
        
            // Update the list items dropdown when a new list
            // is selected in the Lists dropdown.
            $("#selectlistbox").change(function (event) {
                getitems();
                event.preventDefault();
            });
    
    NoteNote

    If the list items aren't displaying when you run the app, be sure that the displayLists(); statement comes after the previous code.

    In the next step, you’ll add JavaScript functions for the new definitions and a support function (getItems()). This table describes what the main functions do.

    Function name

    Description

    createItem()

    Adds an item to the list that the user chooses, and gives that item the name that the user specifies in the Items box.

    deleteItem()

    Deletes the item that the user chooses from the list.

    getItems()

    Retrieves the collection of items (and its children) in the list that the user chooses.

  5. Add this code to bottom of App.js, after the onDeleteListFail() function.

    function createitem() {
        // Retrieve the list that the user chose, and add an item to it.
        var selectListBox = document.getElementById("selectlistbox");
        var selectedListTitle = selectListBox.value;
        var selectedList = web.get_lists().getByTitle(selectedListTitle);
    
        var listItemCreationInfo = new SP.ListItemCreationInformation();
        var newItem = selectedList.addItem(listItemCreationInfo);
        var listItemTitle = document.getElementById("createitembox").value;
        newItem.set_item('Title', listItemTitle);
        newItem.update();
        context.load(newItem);
        context.executeQueryAsync(onItemCreationSuccess, onItemCreationFail);
    }
    
    function onItemCreationSuccess() {
        // Refresh the list of items.
        getitems();
    }
    
    function onItemCreationFail(sender, args) {
        // The item couldn’t be created – display an error message.
        alert('Failed to create the item. ' + args.get_message());
    }
    
    function deleteitem() {
        // Delete the item that the user chose.
        var selectListBox = document.getElementById("selectlistbox");
        var selectedListTitle = selectListBox.value;
        var selectedList = web.get_lists().getByTitle(selectedListTitle);
        var selectItemBox = document.getElementById("selectitembox");
        var selectedItemID = selectItemBox.value;
        var selectedItem = selectedList.getItemById(selectedItemID);
        selectedItem.deleteObject();
        selectedList.update();
        context.load(selectedList);
        context.executeQueryAsync(onDeleteItemSuccess, onDeleteItemFail);
    }
    
    function onDeleteItemSuccess() {
        // Refresh the list of items.
        getitems();
    }
    
    function onDeleteItemFail(sender, args) {
        // The item couldn’t be deleted – display an error message.
        alert('Failed to delete the item. ' + args.get_message());
    }
    
    function getitems() {
        // Using a CAML query, get the items in the list that the user chose, and 
        // set the context to the collection of list items.
        var selectListBox = document.getElementById("selectlistbox");
        var selectedList = selectListBox.value;
        var selectedListTitle = web.get_lists().getByTitle(selectedList);  
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml("<View><ViewFields>" +
            "<FieldRef Name='ID' />" +
            "<FieldRef Name='Title' />" +
            "</ViewFields></View>')");
        listItemCollection = selectedListTitle.getItems(camlQuery);
        context.load(listItemCollection, "Include(Title, ID)");
        context.executeQueryAsync(onGetItemsSuccess, onGetItemsFail);
    }
    
    function onGetItemsSuccess(sender, args) {
        // The list items were retrieved.
        // Show all child nodes.
        var listItemEnumerator = listItemCollection.getEnumerator();
        var selectItemBox = document.getElementById("selectitembox");
        if (selectItemBox.hasChildNodes()) {
            while (selectItemBox.childNodes.length >= 1) {
         selectItemBox.removeChild(selectItemBox.firstChild);
            }
        }
            while (listItemEnumerator.moveNext()) {
                var selectOption = document.createElement("option");
                selectOption.value = listItemEnumerator.get_current().get_item('ID');
                selectOption.innerHTML = listItemEnumerator.get_current().get_item('Title');
                selectItemBox.appendChild(selectOption);
            }
    }
    
    function onGetItemsFail(sender, args) {
        // The list items couldn’t be retrieved - display an error message.
        alert('Failed to get items. Error: ' + args.get_message());
    }
    

All of the UI and code is in place, so go ahead and run the app to be sure it works.

To run the updated app for SharePoint

  1. At the bottom of the page, choose the Run button again.

  2. In the List name here box, enter New Test List, and then choose the Create List button.

    The new list is added to the Lists list.

  3. In the Lists list, choose New Test List.

  4. In the Item name here box, enter Item 1, and then choose the Create Item button.

    The new list item appears in the Items list.

  5. Repeat the previous step to add Item 2 and Item 3.

  6. In the list of items, choose Item 2, and then choose the Delete Selected Item button.

    Item 2 disappears from the list of items.

  7. When you finish, close the browser window.

Now that you’ve created a basic app for SharePoint, consider exploring the following paths:

  • Open your project in Visual Studio by choosing the Open in Visual Studio button, as shown in Figure 3. "Napa" Office 365 Development Tools automatically installs the necessary tools and opens your project in Visual Studio.

    Figure 3. The Open in Visual Studio button

    Open in Visual Studio button

    You can also download and install these tools directly by visiting the Downloads page of the Apps for Office and SharePoint Dev Center.

  • Create an app for SharePoint by using Visual Studio. For more information, see Get started developing apps for SharePoint.

Show:
© 2014 Microsoft