Kode
Kode

Reputation: 3215

Pass Value to NewForm.aspx via QueryString

I am trying to pass a value via a querystring to populate a field in a NewForm.aspx list. Example: http://example.com/Lists/mylist/Newform.aspx?ID=3

I am constrained from using JavaScript and must stick to a querystring. Is this possible?

Upvotes: 1

Views: 27596

Answers (3)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59358

SharePoint JS Library contains GetUrlKeyValue function for extracting query string parameter, for example:

var itemId = GetUrlKeyValue('ID'); //get Item Id from query string

How to populate form field in New Form page in SharePoint 2013?

In SharePoint 2013 was introduced a Client Side Rendering (CSR) technique for customizing List Views & Forms.

Since CSR is the default rendering mode in SharePoint 2013, I would recommend this approach to customize a New Form page in order to populate form fields. As an introductory please follow this article Introduction to Client Side Rendering in SharePoint 2013.

Suppose a Tasks list that contains a Task Category lookup field. Then the following rendering template could be used for setting TaskCategory lookup field value retrieved from a query string parameter named cat:

(function () {
    var ctx = {};
    ctx.Templates = {};
    ctx.Templates.Fields = {
        'TaskCategory': {
            'NewForm': renderTaskCategory
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();


function renderTaskCategory(ctx) {
    var catId = GetUrlKeyValue('cat'); //extract cat parameter from a query string 
    ctx.CurrentFieldValue =  catId; //set lookup field value 
    return SPFieldLookup_Edit(ctx); //default template for rendering Lookup field control
}

How to apply changes

In order to apply the changes we need to set the JSLink property of XLV web part:

  • First of all, let's save this JS template and name it Tasks.js. Then upload the specified into SharePoint Site Assets library
  • open New Form page in Edit mode and go to web part properties
  • find under Miscellaneous group JSLink property and specify its value: ~sitecollection/SiteAssets/Task.js as shown on figure below enter image description here

Result

enter image description here

Upvotes: 8

Manu Singh
Manu Singh

Reputation: 414

Yes, this is possible. Just use parameter other than "ID" e.g. use http://example.com/Lists/mylist/Newform.aspx?MasterId=3 . Some of the Query String parameters are reserved by SharePoint itself. e.g. ID, contents

You can use SharePoint Client Context REST API to get the data and display it. Add a content editor on newform and follow below process. Add reference to these three scripts:
1. /_layouts/15/SP.Runtime.js
2./_layouts/15/SP.js
3. //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
And use below example:

                <script type="text/javascript">

                    $(document).ready(function () {
                        GetListData(getParameterByName("MasterId"));
                    });
                    function getParameterByName(name) {
                        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                        var regexS = "[\\?&]" + name + "=([^&#]*)";
                        var regex = new RegExp(regexS);
                        var results = regex.exec(window.location.href);
                        if (results == null)
                            return "";
                        else
                            return decodeURIComponent(results[1].replace(/\+/g, " "));
                    }
                    function GetListData(strMasterId) {
                        context = new SP.ClientContext.get_current();
                        web = context.get_web();
                        var list = web.get_lists().getByTitle('CustomListName');
                        var myquery = new SP.CamlQuery();
                        myquery.set_viewXml("<View><Query>" +

                                               "<Where>" +
                                                  "<Eq>" +
                                                      " <FieldRef Name='ID'/>" +
                                                        "<Value Type='Counter'>" + strMasterId + "</Value>" +
                                                  "</Eq>" +
                                                   "</Where>" +
                                                      "</Query></View>");
                        myItems = list.getItems(myquery);
                        context.load(myItems);
                        context.executeQueryAsync(Function.createDelegate(this, this.GetListDataSuccess), Function.createDelegate(this, this.GetListDataFailed));
                    }
                    function GetListDataSuccess() {
                        var ListEnumeratorAcc = this.myItems.getEnumerator();
                        while (ListEnumeratorAcc.moveNext()) {
                            var currentItem = ListEnumeratorAcc.get_current();
                            $("input[title='Project Name']").val(currentItem.get_item('ProjectName')[0]);
                            $("input[title='Project Location']").val(currentItem.get_item('ProjectLocation')[0]);
                        }
                    }
                    function GetListDataFailed(sender, args) {
                        alert("failed. Message:" + args.get_message());
                    }
                </script>

Upvotes: 4

user2440074
user2440074

Reputation:

Use JavaScript:

var UrlParams = document.URL.split("?")[1].split("&");

var GetUrlParam = function (name)
{
    for (var i = 0; i < UrlParams.length; i++)
    {
        var param = UrlParams[i].split("=");
        if (param[0] == name) return decodeURIComponent(param[1]);
    }

    return null;
}

Then just simply call "GetUrlParam('ID')" and set your field value;

Upvotes: 1

Related Questions