Ads

Showing posts with label java script. Show all posts
Showing posts with label java script. Show all posts

Friday, 17 March 2017

How to open any SharePoint page as model dialog SP2010

As we all know that sharepoint 2010 is opening a lot of forms in its newly featured model dialog.

Few of this pages are list forms like NewForm.aspx, EditForm.aspx, DispForm.aspx, pages while creating new object like list,site…etc.

While customize your sharepoint site, if by any chance you required any of your page to show in model dialog then below is the code for the same.
function OpenDialog(strPageURL,strDialogTitle) {
//Creating New Object for SharePointDialog
var newDialogOptions = SP.UI.$create_DialogOptions();
//set URL for Dialog to open
newDialogOptions.url = strPageURL;
//you can set your custom size by setting height and width
autoSize: true,
//set title to show on head of dialog
newDialogOptions.title = strDialogTitle;
// This line required only if you want to call a function when we close dialog -- here we refresh the page
newDialogOptions.dialogReturnValueCallback = Function.createDelegate(null,CallbackFunc);

//open the dialog
SP.UI.ModalDialog.showModalDialog(newDialogOptions);
return false;
}

function CallbackFunc(result, target) {
//Refresh the current page
location.reload(true);
//some suggest to use below line but sometime this was not working
//so we are working on that
//SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);

}
The good thing for us is you can open any page with this dialog.
That page might have you custom webpart as well or anything will work.

Even JavaScript, query string, postback etc… available on that page because that page work similar as normal page it will also remove limitation of traditional model dialog.

If we want to refresh parent page after closing popup then also we can do that (as shown in code)

One more thing if you want to open another model dialog from already open model dialog then also this one is working

Friday, 17 February 2017

News Tickers in SharePoint 2013 using JQuery

Lets create a custom list called "News"
We will get news text from title of this list and display in SharePoint page page

VS --> New Project --> SP 2013 empty project --> Deploy as a farm solution
Add new item --> Visual web part
Add jQuery reference to layout folder & add its reference in ascx page of web part

Add script in same page:
< script > $(document).ready(function() {
    $('#NewsTicker').vTicker({
        speed: 500,
        pause: 3000,
        showItems: 1,
        animation: 'fade',
        mousePause: true,
        direction: 'up' /*Text direction*/
    });
}); < /script>

Add style CSS in same page:
<style type="text/css" media="all">
    #NewsTicker
    {
        width: 844px;
        margin: auto;
    }

    #NewsTicker ul li div
    {
        height:30px;
        background: Yellow;
    }

    <div style="width:1310px; height:30px; border-style:solid; border-width:2px; border-color:#FFCB05">
        <div style="float:left;background-color:White; height: 27px; width: 118px;">
            <h2 style="font-family:Arial; font-size:22px; background-color:#FFCB05; color:Black;">News</h2>
        </div>
        <div id="NewsTicker" style="float:left; padding-left:15px; font-size:24px; font-family:Arial; height: 29px;">
            <ul style="width: 920px">
                <asp:Literal ID="ltNews" runat="server" Text=""></asp:Literal>
            </ul>
        </div>
    </div>
</style>

Now write C# code in page load to bind data:
private void BindData()
{
    Guid siteId = SPContext.Current.Site.ID;
    Guid webId = SPContext.Current.Web.ID;
    StringBuilder sb = new StringBuilder();
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
        using(SPSite site = new SPSite(siteId))
        {
            using(SPWeb web = site.OpenWeb(webId))
            {
                SPList list = web.Lists.TryGetList("News"); /*Create the list*/
                if (list != null)
                {
                    foreach(SPListItem item in list.Items)
                    {
                        sb.AppendLine("<li>");
                        sb.AppendLine("<div>");
                        sb.AppendLine(item.Title); /*Get the title column*/
                        sb.AppendLine("</div>");
                        sb.AppendLine("</li>");
                    }
                }

            }
        }
    });
    ltNews.Text = sb.ToString();
}

Finally deploy and add this webpart in page to see the result

AngularJS in a SharePoint 2013 page to add list item using CSOM

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets create one simple list form in angular to submit list item.

  1. Create one custom list "Employee Details"
    • FirstName, LastName, Location 
  2. Add one script editor web part to add script in page
    • Add web part --> Media & Content --> Script Editor --> ok to Add it
  3. Edit webpart in "edit Snippet" and write below codes

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  
<script>  
    function ContactsCtrl($scope) {  
        $scope.contact = { firstName: "", lastName: "", location: "" };  
        $scope.addContact = function ($event) {  
            var x = $scope.contact;  
            $event.preventDefault();  
            var clientContext = new SP.ClientContext.get_current();  
            var web = clientContext.get_web();  
            var list = web.get_lists().getByTitle('Employee Details');  
  
            // create the ListItemInformational object  
            var listItemInfo = new SP.ListItemCreationInformation();  
            // add the item to the list  
            var listItem = list.addItem(listItemInfo);  
            // Assign Values for fields  
            listItem.set_item('Title', x.firstName);  
            listItem.set_item('LastName', x.lastName);  
            listItem.set_item('FullName', x.firstName + " " + x.lastName);  
            listItem.set_item('Location', x.location);  
  
            listItem.update();  
  
            clientContext.executeQueryAsync(  
                Function.createDelegate(this, onQuerySucceeded),  
                Function.createDelegate(this, onQueryFailed)  
            );  
  
        };  
  
        onQuerySucceeded = function () {  
            alert('Successfully updated the contact');  
        }  
  
        onQueryFailed = function (sender, args) {  
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
        }  
    }  
</script>  
   
<h1>Employee Information:</h1>  
<br />  
<div ng-app="">  
    <div ng-controller="ContactsCtrl">  
        <strong>Emp First Name</strong>  
        <input type="text" ng-model="contact.firstName" /><br />  
        <br />  
        <strong>Emp Last Name</strong>   
        <input type="text" ng-model="contact.lastName" /><br />  
        <br />  
        <strong>Emp Location </strong> 
        <input type="text" ng-model="contact.location" /><br />  
        <br />  
        <input type="submit" value="Submit" ng-click="addContact($event)" />  
    </div>  
</div>  


Tuesday, 14 February 2017

List search using Angular JS

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets assume to do search in a custom list called "ListA"

Create one js file "ListSearch.js" and upload in any library
var spApp = angular.module("spApp", []).controller("viewItemController", function($scope, $http) {
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('ListA')/items";
    $http({
        method: "GET",
        url: url,
        headers: {
            "accept": "application/json;odata=verbose"
        }
    }).success(function(data, status, headers, config) {
        var dataResults = data.d.results;
        $scope.contacts = dataResults;
    }).error(function(data, status, headers, config) {});
})

Create one html file with below html or we can put it in a content editor to get the result.

    <html>
   
    <head>
        <script type="text/javascript" src="/SiteAssets/jquery-3.0.0.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/angular.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/listSearch.js"></script>
    </head>
   
    <body>
        <h3>View Contacts</h3>
        <hr/>
        <div ng-app="spApp">
            <div ng-controller="viewItemController"> Search Items:<input type="text" placeholder="searchItems" ng-model="searchText" />
                <table>
                    <tr>
                        <th>Product</th>
                        <th>Total Sales</th>
                        <th>Sales Target</th>
                    </tr>
                    <tr ng-repeat="contact in contacts|filter:searchText">
                        <td>{{contact.Product}}</td>
                        <td>{{contact.Total_x0020_Sales}}</td>
                        <td>{{contact.Sales_x0020_Target}}</td>
                    </tr> <br /> </table>
            </div>
            <hr /> </body>
   
    </html>



Tuesday, 2 December 2014

Filter Column based on another column - Cascade Drop Down JavaScript

We can use Content Editor Web Part to add java script in page (NewForm.aspx)

Lets Create 3 lists.
List-1 called "State" : Custom list with a column "Title" with all states.

List-2 called "CityState" : Custom list with a column 'City' and one for its State. State Column will be lookup to the previous list "State". Here I have renamed "Title" column as "City".



City will hold column "City" information. State will be a dropdown that loads as a lookup.

List called "Data" : Custom list with a column to have Company name, a column for State[ lookup to the column "Title" in first list "State"], a column for city[ lookup to "City" column of second list "CityState"]


Now State is a lookup column and brings all the value from the first list "State".


Now City is a lookup column and brings all the value from the column "City" in the list "CityState" . So far no filtering is happening.



Step 3: Edit the page. You can modify the URL to edit NewForm.aspx. To the end of the URL append PageView=Shared&ToolPaneView=2. This will open the form in edit mode.

your URL must be like this http://sample.com/sites/MySPSite/Lists/Data/NewForm.aspx?PageView=Shared&ToolPaneView=2

Step 4: Add Content Editor Web Part.



Step 5: Write the following code in a text. save as html. upload into SharePoint.Link this html page to content editor web part or Write code in Web Part's text editor directly. SPSErvices JS File  helps us with the SPCascadeDropDown function.


<SCRIPT type=text/javascript src="http://mysite.com/sites/MySite/Documents/jquery-1.4.2.min.js"></SCRIPT>
<SCRIPT type=text/javascript src="http://mysite.com/sites/MySite/Documents/jquery.SPServices-0.5.6.min.js"></SCRIPT>
<SCRIPT type=text/javascript>

$(document).ready(function(){

        $().SPServices.SPCascadeDropdowns({
        relationshipList:"CityState",
        relationshipListParentColumn:"State",
        relationshipListChildColumn:"Title",
        parentColumn:"State",
        childColumn:"City"
      });
  
});


</SCRIPT>

Step 6: After the content editor web part is saved and you exit the page from edit mode, City gets filtered based on the State.




Step 7: To remove the identity that the code was generated from Content Editor Web Part, within the Web Part Setting, Under Appearance, For Chrome Type select "None". Click OK. Click Apply. Publish the Page.

Step 8: Now instead of showing all cities depending upon the selected state, you need to show only a particular set of cities based on a CAML query, then that also can be achieved.

Step 9: Create a column of type "Yes\No" in second list "CityData" called "Visible".




Step 10: Now add the CAML query to the SPServices.SPCascadeDropDown function. Notice the comma after the ChildColumn.
 $(document).ready(function(){

        $().SPServices.SPCascadeDropdowns({
        relationshipList:"CityState",
        relationshipListParentColumn:"State",
        relationshipListChildColumn:"Title",
        parentColumn:"State",
        childColumn:"City",
        CAMLQuery: "<Eq><FieldRef Name='Visible' /><Value Type='Boolean'>1</Value></Eq>"
      
      });
  
});

Step 11:  Now for a selected State, Its relevant Cities with Visible ="True" only gets displayed.









Tuesday, 18 November 2014

Learn Angular JS

AngularJS is quite new. Version 1.0 was released in 2012.
Miško Hevery, a Google employee, started to work on AngularJS in 2009.
It is a JavaScript framework. It is a library written in JavaScript.
We can be added to a web page with a script tag
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Directives

AngularJS extends HTML with ng-directives.
  1. The ng-app directive defines an AngularJS application.
  2. ng-app directive defines the root element of an AngularJS application
  3. ng-app directive will auto-bootstrap (automatically initialize) when a web page is loaded
  4. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
  5. ng-app can have a value (like ng-app="myModule"), to connect code modules.
  6. The ng-bind directive binds application data to the HTML view. 
ng-init directive defines initial values for an AngularJS application
ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
The ng-model directive can also:
  • Provide type validation for application data (number, email, required).
  • Provide status for application data (invalid, dirty, touched, error).
  • Provide CSS classes for HTML elements.
  • Bind HTML elements to HTML forms.
 Example:
 <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>
   <div ng-app="">
   <p>Name: <input type="text" ng-model="name"></p>
   <p ng-bind="name"></p>
</div>
Output:                            Click Here to Try urself-1

 AngularJS directives are HTML attributes with an ng prefix.
The ng-init directive initialize AngularJS application variables

<div ng-app="" ng-init="firstName='John'">
     <p>The name is <span ng-bind="firstName"></span></p>
     <p>The name is {{ firstName }}</p>
</div>
Output: The name is John       Click Here to Try urself-2

In above you can use data-ng-, instead of ng-, if you want to make your page HTML5 valid

<div data-ng-app="" data-ng-init="firstName='John'">
    <p>The name is <span data-ng-bind="firstName"></span></p>
</div>

AngularJS directives used in this tutorial:
Directive Description Explained
ng-app Defines the root element of an application. Directives
ng-bind Binds the innerHTML of HTML elements to application data. Introduction
ng-click Defines the behavior when an element is clicked. HTML Events
ng-controller Defines the controller object for an application. Controllers
ng-disabled Binds application data to the HTML disabled attribute. HTML DOM
ng-hide Hides or shows HTML elements. HTML DOM
ng-include Includes HTML in an application. Includes
ng-init Defines initial values for an application. Directives
ng-model Binds the value of HTML controls to application data. Directives
ng-repeat Defines a template for each data in a collection. Directives
ng-show Shows or hides HTML elements. HTML DOM


Data Binding

The {{ firstName }} expression, is an AngularJS data binding expression.
Data binding in AngularJS, synchronizes AngularJS expressions with AngularJS data.
{{ firstName }} is synchronized with ng-model="firstName".

<div ng-app="" ng-init="quantity=1;price=5">
    Quantity: <input type="number"    ng-model="quantity">
    Costs:    <input type="number" ng-model="price">
    Total in dollar: {{ quantity * price }}
</div>
Output:              Try urself

Repeating HTML Elements

The ng-repeat directive repeats an HTML element:
ng-repeat directive clones HTML elements once for each item in a collection (in an array).

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>
Output:         Try yourself

As Array element
<div ng-app="" ng-init="names=[{name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'},{name:'Kai',country:'Denmark'}]">
<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>
</div>
Output:                   Try yourself

Expressions:

AngularJS expressions are written inside double braces: {{ expression }}.
If you remove the ng-app directive, HTML will display the expression as it is.

<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>
Output: My first expression: 10         Try urself-3
Number
<div ng-app="" ng-init="quantity=1;cost=5">
    <p>Total in dollar: {{ quantity * cost }}</p>
    <p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
Output: Total in dollar: 5        Try Urself-3
String
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
    <p>The name is {{ firstName + " " + lastName }}</p>
    <p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
Output: The full name is: John Doe    Try urself-3
Object
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
    <p>The name is {{ person.lastName }}</p>
    <p>The name is <span ng-bind="person.lastName"></span></p>
</div>
Output: The name is Doe    Try urself-3
Array
<div ng-app="" ng-init="points=[1,15,19,2,40]">
    <p>The third result is {{ points[2] }}</p>
    <p>The third result is <span ng-bind="points[2]"></span></p>
</div>
Output: The third result is 19      Try urself-3

Controllers

The ng-controller directive defines the controller.
The controller code will execute when the page loads.

<div ng-app="" ng-controller="personController">
    First Name: <input type="text" ng-model="firstName"><br>
    Last Name: <input type="text" ng-model="lastName"><br>
    <br>
    Full Name: {{firstName + " " + lastName}}

    Full Name: {{fullName()}}
</div>

<script>
    function personController($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
            $scope.fullName = function() {
                   return $scope.firstName + " " + $scope.lastName;
            }
    }
</script>
||or||
<script src="personController.js"></script>
Try yourself-4

Filters

currency Format a number to a currency format.
filter Select a subset of items from an array.
lowercase Format a string to lower case.
orderBy Orders an array by an expression.
uppercase Format a string to upper case.

uppercase / lowercase filter format strings to upper case:
       <p>The name is {{ lastName | uppercase }}</p>
       <p>The name is {{ lastName | lowercase }}</p>
 currency filter formats a number as currency:
       <p>Total = {{ (quantity * price) | currency }}</p>
orderBy filter orders an array by an expression:
----------------------------Common Used for bellow codes -----------------
function namesController($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Hege',country:'Sweden'},
        {name:'Kai',country:'Denmark'}
    ];

---------Above can refer as <script src="namesController.js"></script>-------------
    
<div ng-app="" ng-controller="namesController">
<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>
</div>
<script src="namesController.js"></script>    Try Here
 

 filter filter selects a subset of an array:   Try Here
    <ul>
          <li ng-repeat="x in names | filter:test | orderBy:'country'">
          {{ (x.name | uppercase) + ', ' + x.country }}
         </li>
   </ul>

AngularJS filters used in this tutorial:
Filter Description
currency Format a number to a currency format.
filter Select a subset of items from an array.
lowercase Format a string to lower case.
orderBy Orders an array by an expression.
uppercaseFormat a string to upper case.

Reading a JSON File

 http://www.w3schools.com/website/Customers_JSON.php
 [
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
}
]


AngularJS $http is a core service for reading data from web servers.
$http.get(url) is the function to use for reading server data.

<div ng-app="" ng-controller="customersController">
<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

|| or ||
     <table>
          <tr ng-repeat="x in names">  or   
<tr ng-repeat="x in names | orderBy : 'Country'"> 
                <td>{{ x.Name }}</td>
                <td>{{ x.Country }}</td>   or
<td>{{ x.Country | uppercase}}</td>
          </tr>
    </table>

</div>

<script>
function customersController($scope,$http) {
    $http.get("http://www.w3schools.com/website/Customers_JSON.php")
    .success(function(response) {$scope.names = response;});
}
</script>   

Try Here
  • AngularJS application is defined by ng-app. The application runs inside a <div>.
  • ng-controller directive names the controller object.
  • customersController function is a standard JavaScript object constructor.
  • AngularJS will invoke customersController with a $scope and $http object.
  • $scope is the application object (the owner of application variables and functions).
  • $http is an XMLHttpRequest object for requesting external data.
  • $http.get() reads static JSON data from http://www.w3schools.com/website/Customers_JSON.php.
  • If success, the controller creates a property (names) in the scope, with JSON data from the server.  
  • code above can also be used to fetch data from a database

Fetching Data From a PHP Server Running MySQL

 <div ng-app="" ng-controller="customersController">
<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
function customersController($scope,$http) {
    var site = "http://www.w3schools.com";
    var page = "/website/Customers_MySQL.php";
    $http.get(site + page)
    .success(function(response) {$scope.names = response;});
}
</script>  Try Here


Fetching Data From an ASP.NET Server Running SQL

<script>
function customersController($scope,$http) {
    var site = "http://www.w3schools.com";
    var page = "/website/Customers_SQL.aspx";
    $http.get(site + page)
    .success(function(response) {$scope.names = response;});
}
</script>

ng-disabled / ng-show / ng-hide Directive

ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
<div ng-app="">
     <p> <button ng-disabled="mySwitch">Click Me!</button> </p>
    <p> <input type="checkbox" ng-model="mySwitch">Button </p>
</div>
Try Here

<div ng-app="">
     <p ng-show="true">I am visible.</p>
     <p ng-show="false">I am not visible.</p>
     <p ng-show="hour > 12">I am visible.</p>
     <p ng-hide="true">I am not visible.</p>
     <p ng-hide="false">I am visible.</p> 

</div>
Try Here

ng-click Directive

<div ng-app="" ng-controller="myController">
     <button ng-click="count = count + 1">Click me!</button>
     <p>{{ count }}</p>
</div>
<script>
function myController($scope) {
    $scope.count = 0;
}
</script>    Try Here

Module Example 


In this example,
"myApp.js" contains an application module definition.
"myCtrl.js" contains a controller.




<body>
<div ng-app="" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
function myCtrl($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
}
</script>
</body>
Try Here

<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>
</body>

Try Here


When to Load the Library

the AngularJS library is loaded in the <head> section.
load the AngularJS library in the <body> element, but before your own AngularJS scripts i.e either head section or before you define your code.

HTML Controls

  • input elements
  • select elements
  • button elements
  • textarea elements

Input Validation

Try Here; Some Examples Here from W3School

I recommend you to visit my below posts.....
 List search using Angular JS
 AngularJS in a SharePoint 2013 page to add list item using CSOM
 Use REST API & Angular JS Implement custom search for lookup & person/group   
 Questions on Angular JS

Saturday, 31 May 2014

Modal Window Using JavaScript in SharePoint

2 ways to open SharePoint Modal Window using JavaScript:

1. Using the DialogOptions class.
var options = SP.UI.$create_DialogOptions();

options.title = "My Dialog Title";
options.width = 400;
options.height = 600;
options.url = "/_layouts/DialogPage.aspx";

SP.UI.ModalDialog.showModalDialog(options);

2. Using a generic object.
var options = {
    title: "My Dialog Title",
    width: 400,
    height: 600,
    url: "/_layouts/DialogPage.aspx" };

SP.UI.ModalDialog.showModalDialog(options);

Ref.: http://msdn.microsoft.com/en-us/library/ff410058(v=office.14).aspx

JavaScript In OnLoad Event Of Body SharePoint

many times we might require to call some functions on body onload event. As web part does not contain body tag we cannot use onload attribute of body tag.

To overcome this drawback, a developer can use an array i.e. _spBodyOnLoadFunctionNames
The only thing we need to do is to pass the function's name using .push method.

Example:
<script language="javascript">
_spBodyOnLoadFunctionNames.push("TestFunction");

function TestFunction() 

   alert("hello"); 

</script> 

We can use above script in master page, aspx page, content editor web part, visual web part as per the need.

Create link to Download a copy from a SharePoint Document Library

Generate a link using below format:
http://spsite/subsite/_layouts/download.aspx?SourceUrl=http://spsite/subsite/shared documents/fileName.docx
And use this URL in Anchor tag / window.open etc. as per the requirement.

Wednesday, 23 April 2014

Showing the ID on SharePoint List item display/edit screens

Here is a tutorial on how to show items IDs on the display and edit forms.
We are able to display the list item IDs when viewing the list, but the IDs are not present when we open or edit the items.
 

  


To add IDs to the display and edit forms we need to first know their URLs
Default display form name: DispForm.aspx
  • Full URL example (http://localhost/Lists/Sales/DispForm.aspx)
Default edit form name: EditForm.aspx
  • Full URL example (http://localhost/Lists/Sales/EditForm.aspx)


(if you are using custom forms with different names you can use SP Designer to check the default form names)

To edit these forms from the browser like they were a page we can add the text ?toolpaneview=2 to the end of the URL.
This will make the page edit tools available to you.


Add a HTML Form Web Part to the page, now we can add our own custom code to the page.
This solution requires JQuery so you have 2 choices on how to reference it.
  1. If you are in an environment where you have unrestricted access to the internet you can reference JQuery through the google APIs.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


  1. If you are in an environment where internet access is restricted you can download a copy of JQuery and upload it to a SharePoint library then reference it.
<script src="http://localhost/Shared%20Documents/jquery-1.10.2.min.js"></script>
Once you figure out which JQuery you are going to go with copy and paste the code below into the Source.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Get ID
var id = getQueryString()["ID"];
// Get the main form table
var maintable = $('table.ms-formtable');
// Now add a row to the start of the table
maintable.prepend("<tr><td class='ms-formlabel'><h3 class='ms-standardheader'>ID</h3></td>" +
"<td class='ms-formbody'>" + id + "&nbsp;</td></tr>");
})
function getQueryString() {
var assoc = new Array();
var queryString = unescape(location.search.substring(1));
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
assoc[key[0]] = key[1];
}
return assoc;
}
</script>





You should then see the ID field appear on all the forms.


This process will need to be done on both forms (edit and display). On the edit form the ID will appear but not be editable.

Ads