GetItemById in edit form

rss

Posted by romslo - Nov 5 ’14 at 09:23

I use a code block like this in a form:

...

var context = new SP.ClientContext.get_current();
var mainList = context.get_web().get_lists().getByTitle('MyList');

var listItem = mainList.getItemById(1);
context.load(listItem);

context.executeQueryAsync( Function.createDelegate(this, function() {
var title = listItem.get_item('Title')

})
);

...

 

This works perfect in the display form. In the edit form, I get an error saying that the Title field has not been initialized.

I have tried to load the Title field as part of the context.load() with no success. Network trace shows that the data is correct in the response.

Any suggestions how to solve this?

  • Dmitry Kozlov
    Dmitry Kozlov
    Admin
    Member for: 5 years 11 months
    #1 by Dmitry Kozlov Nov 6 ’14 at 02:14

    Hi,

    The following core works just fine on all kind of forms:

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
    	var context = new SP.ClientContext.get_current();
    	var mainList = context.get_web().get_lists().getByTitle('MyList');
    
    	var listItem = mainList.getItemById(1);
    	context.load(listItem);
    
    	context.executeQueryAsync(function() {
    		var title = listItem.get_item('Title');
    		alert(title);
    	});
    });
    
  • romslo
    Member
    Member for: 5 years 3 months 18 days
    #2 by romslo Nov 6 ’14 at 04:32

    [#1]: Thank you for the confirmation. Now I got it working.

    I startet to confirm that this code worked in a simple form, then I stripped down my complex form and built it up bit by bit. The error was triggered because I had an explicit reference to sp.runtime.js. Maybe multiple references to this file causes trouble...?

  • romslo
    Member
    Member for: 5 years 3 months 18 days
    #3 by romslo Nov 6 ’14 at 10:37

    [#1]: By the way. How is best practice to include extra js-files (e.g. sp.workfowservices.js and sp.runtime.js)? I have linked them in a HTML control.

  • Dmitry Kozlov
    Dmitry Kozlov
    Admin
    Member for: 5 years 11 months
    #4 by Dmitry Kozlov Nov 7 ’14 at 03:39

    [#3]: Hi,

    To prevent loading the same scripts twice, I'd recommend to use ScriptLink control for out-of-the-box scripts. Put the following code into HTML-control:

    <SharePoint:ScriptLink language="javascript" name="sp.runtime.js" Localizable="false" OnDemand="true" runat="server"/>
    <SharePoint:ScriptLink language="javascript" name="sp.workflowservices.js" Localizable="false" OnDemand="true" runat="server"/>
    

    And use sp.workflowservices.js following way in JavaScript:

    SP.SOD.executeFunc('sp.workflowservices.js', 'SP.WorkflowServices', function() {
        // your code here
    });
    

    Get more information on SharePoint SOD:
    http://www.ilovesharepoint.com/2010/08/sharepoint-scripts-on-demand-spsod.html

Displaying 1 to 4 of 4 messages