Showing posts with label Javascript Client Object Model with list. Show all posts
Showing posts with label Javascript Client Object Model with list. Show all posts

Friday, July 4, 2014

Get fields using Javascript Client Object Model SharePoint 2013


Using the Javascript Client Object Model, you can get values from a listitem. 

How to use the JSOM is described here Code Project

Title – SP.ListItem.get_item(‘Title‘);

ID – SP.ListItem.get_id();

Url -SP.ListItem.get_item(‘urlfieldname‘).get_url()

Description – SP.ListItem.get_item(‘descriptionfieldname‘).get_description();

Current Version – SP.ListItem.get_item(“_UIVersionString“);

Lookup field – SP.ListItem.get_item(‘LookupFieldName’).get_lookupValue(); // or get_lookupID();

Created By – SP.ListItem.get_item(“Author“).get_lookupValue();

Modified by – SP.ListItem.get_item(“Editor“).get_lookupValue();

Choice Field – SP.ListItem.get_item(‘ChoiceFieldName‘);

Created Date – SP.ListItem.get_item(“Created“);

Modified Date – SP.ListItem.get_item(“Modified“); -> case sensitive does not work with ‘modified’

File  – SP.ListItem.get_file();

File Versions -  File.get_versions();.

Content Type – SP.ListItem.get_contentType();

Parent List – SP.ListItem.get_parentList();

Note:  (‘LookupFieldName’).get_lookupValue() sometimes returns an array of data, especially when your lookup allows multiple values.
In that case you will need to iterate the array and get each value individually.

 SP.ListItem.get_item(‘LookupFieldName’)[0].get_lookupValue(); - this will get the first item in the array.


For Arrays:
       for(var i = 0; i < oListItem.get_item("LookupFieldName").length; i++)
{
     alert(oListItem.get_item("LookupFieldName")[i].get_lookupId()); // or get_lookupValue()


Example, How to get Blog templeate Posts list authors user names:





<html>
<head>
    <title></title>

    <script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>


    <script type="text/javascript">
        var hostweburl;

        // Load the required SharePoint libraries.
        $(document).ready(function () {

            // Get the URI decoded URLs.
            hostweburl =
                decodeURIComponent(
                    getQueryStringParameter("SPHostUrl")
            );

            // The js files are in a URL in the form:
            // web_url/_layouts/15/resource_file
            var scriptbase = hostweburl + "/_layouts/15/";

            // Load the js files and continue to
            // the execOperation function.
            $.getScript(scriptbase + "SP.Runtime.js",
                function () {
                    $.getScript(scriptbase + "SP.js", execOperation);
                }
            );
        });
        var siteUrl = '/sites/devsite/devblog';
        // Function to execute basic operations.
        function execOperation() {
            retrieveListItems();
        }

        function retrieveListItems() {

            var clientContext = new SP.ClientContext(siteUrl);
            var oList = clientContext.get_web().get_lists().getByTitle('Posts');

            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
                '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></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 postAuthor = '';

            var listItemEnumerator = collListItem.getEnumerator();

            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                postAuthor = oListItem.get_item('Author').get_lookupValue();
                $('#author').text(postAuthor);
            }
          
        }

        function onQueryFailed(sender, args) {

            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }

        // Function to retrieve a query string value.
        // For production purposes you may want to use
        // a library to handle the query string.
        function getQueryStringParameter(paramToRetrieve) {
            var params =
                document.URL.split("?")[1].split("&");
            var strParams = "";
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
            }
        }
    </script>
</head>
<body>
    <div id="author"></div> 
</body>
</html>


Code: Iterates through all items in Posts list, get lookup field value of author columns and inserts a value in to div.

while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                postAuthor = oListItem.get_item('Author').get_lookupValue();
                $('#author').text(postAuthor);
            }

Have a good day!!!