Page 1 of 1

GetItemById in edit form

Posted: 05 Nov 2014
by romslo
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?

Re: GetItemById in edit form

Posted: 06 Nov 2014
by Dmitry Kozlov
Hi,

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

Code: Select all

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);
	});
});

Re: GetItemById in edit form

Posted: 06 Nov 2014
by romslo
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...?

Re: GetItemById in edit form

Posted: 06 Nov 2014
by romslo
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.

Re: GetItemById in edit form

Posted: 07 Nov 2014
by Dmitry Kozlov
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:

Code: Select all

<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/ ... spsod.html