Following is my code:
retrieveListItems('https://sustec29-public.sharepoint.com');
function retrieveListItems(siteUrl) {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
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 listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\ngroup: ' + oListItem.get_item('group') +
'\ndisc: ' + oListItem.get_item('disc');
}
$('#message').text(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
`
but browser views error -
The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
if i write
'\ntitle: ' + oListItem.get_item('title') + '\nbody: ' + oListItem.get_item('body');
and rename field table`s - all ok.
But i want add own field..
Try to add ViewFields section to your caml query:
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name="ID"/>' +
'<Value Type="Number">1</Value></Geq></Where></Query>' +
'<RowLimit>10</RowLimit><ViewFields><FieldRef Name="group" /><FieldRef Name="disk" /></ViewFields></View>'
EDIT:
Another way you can try to achieve this is to add Include string to your load method call:
clientContext.load(collListItem, 'Include(Id, disk, group)');
Related
I want to use client side rendering(js link) for document library, the challenge for me is Sharepoint document library will be created dynamically when the remote event receiver triggers.
I know we need to pass js link reference in elements.xml file, but in my case list will be created later, so how can I achieve it?
Thanks in advance.
You can add script (JSLink) programmatically, after your condition event receiver:
C#:
using (SPSite site = new SPSite("http://sp/sites/test"))
{
SPWeb web = site.RootWeb;
SPFile page = web.GetFile("SitePages/Test.aspx");
page.CheckOut();
using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
XmlElement p = new XmlDocument().CreateElement("p");
p.InnerText = "<script type='text/javascript'>alert('Hello World');</script>";
ContentEditorWebPart cewp = new ContentEditorWebPart
{
Content = p
};
wpmgr.AddWebPart(cewp, "Header", 0);
}
page.CheckIn(String.Empty);
}
JS:
var siteUrl = '/sites/MySiteCollection';
var serverRelativeUrl = '/sites/MySiteCollection/Default.aspx';
function addWebPart() {
var clientContext = new SP.ClientContext(siteUrl);
var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);
var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webPartXml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +
'<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"' +
' xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"' +
' xmlns=\"http://schemas.microsoft.com/WebPart/v2\">' +
'<Title>My Web Part</Title><FrameType>Default</FrameType>' +
'<Description>Use for formatted text, tables, and images.</Description>' +
'<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>' +
'<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>' +
'<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>' +
'<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>' +
'<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />' +
'<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />' +
'<MissingAssembly>Cannot import this Web Part.</MissingAssembly>' +
'<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />' +
'<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, ' +
'PublicKeyToken=94de0004b6e3fcc5</Assembly>' +
'<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' +
'<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">' + '/sites/SiteAssets/Test.js</ContentLink>' +
'<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">' +
'<![CDATA[This is a first paragraph!<DIV> </DIV>And this is a second paragraph.]]></Content>' +
'<PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>';
var oWebPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
this.oWebPart = oWebPartDefinition.get_webPart();
limitedWebPartManager.addWebPart(oWebPart, 'Left', 1);
clientContext.load(oWebPart);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
alert('Web Part added: ' + oWebPart.get_title());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
Suppose I have 2 Lists: Teams and Employees. Each team has a number of employees:
Teams
ID
Name
Employees
ID
Name
TeamID (foreign key of Teams)
If I created a Join query of Employees LEFT JOIN Teams, could I then set_item and update the Name field in Teams?
var ctx = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('Employees');
var queryText =
"<View>" +
"<Query></Query>" +
"<ProjectedFields>" +
"<Field Name='TeamName' Type='Lookup' List='Team' ShowField='Name' />" +
"</ProjectedFields>" +
"<Joins>" +
"<Join Type='INNER' ListAlias='Team'>" +
"<Eq>" +
"<FieldRef Name='TeamID' RefType='Id'/>" +
"<FieldRef List='Team' Name='ID'/>" +
"</Eq>" +
"</Join>" +
"</Joins>" +
"<ViewFields>" +
"<FieldRef Name='TeamName'/>" +
"</ViewFields>" +
"</View>";
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(queryText);
var listItemsCollection = list.getItems(camlQuery);
ctx.executeQueryAsync(onSuccess, onError);
And then, update the TeamName field:
var first = listItemsCollection.get_data()[0];
first.set_item("TeamName", "something");
first.update();
ctx.executeQueryAsync(onSuccess, onError);
Is this supported? (I currently have not way of trying this)
If not, what could be the alternative?
No, only those fields that contains list item could be updated. But you could consider the following approach for updating projected fields.
Since projected fields are returned as lookup values, you could retrieve projected list item and update it's properties as demonstrated below:
var listTitle = 'Employees';
var joinListTitle = 'Teams'
var joinFieldName = 'TeamID';
var projectedFields = ['Name'];
getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,
function(items){
var item = items.get_data()[0]; //get first item
var itemId = item.get_item('TeamsName').get_lookupId(); //get projected list item id
var propertiesToUpdate = {'Name': 'New Team Name'};
updateListItem(joinListTitle,itemId,propertiesToUpdate,function(item){
console.log('List Item has been updated');
},
logError);
},
logError);
where
function createJoinQuery(joinListTitle,joinFieldName,projectedFields,joinType)
{
var queryText =
"<View>" +
"<Query/>" +
"<ProjectedFields>";
for(var idx in projectedFields) {
queryText += String.format("<Field Name='{0}{1}' Type='Lookup' List='{0}' ShowField='{1}' />",joinListTitle,projectedFields[idx]);
}
queryText +=
"</ProjectedFields>" +
"<Joins>" +
"<Join Type='{2}' ListAlias='{0}'>" +
"<Eq>" +
"<FieldRef Name='{1}' RefType='Id'/>" +
"<FieldRef List='{0}' Name='ID'/>" +
"</Eq>" +
"</Join>" +
"</Joins>" +
"</View>";
var qry = new SP.CamlQuery();
qry.set_viewXml(String.format(queryText,joinListTitle,joinFieldName,joinType));
return qry;
}
function getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var items = list.getItems(createJoinQuery(joinListTitle,joinFieldName,projectedFields,'INNER'));
ctx.load(items);
ctx.executeQueryAsync(
function() {
success(items);
},
error
);
}
function updateListItem(listTitle,itemId, propertiesToUpdate,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var listItem = list.getItemById(itemId);
for(var name in propertiesToUpdate) {
listItem.set_item(name,propertiesToUpdate[name]);
}
listItem.update();
ctx.executeQueryAsync(function() {
success(listItem);
},error);
}
I am trying to make it if the date and time are already booked in the calender dont book, i am using this code and nothing get displayed? Any Sugestions?
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists();
var targetList;
function createItem() {
targetList = list.getByTitle("AppbokningarList");
var listItemCreation = new SP.ListItemCreationInformation();
var newItem = targetList.addItem(listItemCreation);
var listItemTitle = document.getElementById('Textrubrik').value;
alert(listItemTitle);
var listItemCustom = document.getElementById('datepicker').value;
alert(listItemCustom);
var listItemFromTime = document.getElementById('timepicker').value;
alert(listItemFromTime);
var listItemtoDate = document.getElementById('datepickerto').value;
alert(listItemtoDate);
var listItemToTime = document.getElementById('timepickerTo').value;
alert(listItemToTime);
var listItemBeskrivning = document.getElementById('Textbeskrivning').value;
alert(listItemBeskrivning);
newItem.set_item('Title', listItemTitle);
var result = listItemCustom + " " + listItemFromTime;
newItem.set_item('EventDate', result);
var result2 = listItemtoDate + " " + listItemToTime;
newItem.set_item('EndDate', result2);
newItem.set_item('Description', listItemBeskrivning);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<Where><Geq><FieldRef Name='EventDate' /><Value Type='DateTime'>" + result + "</Value></Geq><Leq><FieldRef Name='EndDate' /><Value Type='DateTime'>" + result2 + "</Value></Leq><FieldRef Name='RecurrenceID' /></Where>");
this.collListItem = targetList.getItems(camlQuery);
context.load(collListItem);
var property = new SP.EventProperties();
if (collListItem > 0) {
property.cancel = true;
}
newItem.update();
context.load(newItem);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var succeded = "Mötet är nu bokat!";
alert(succeded);
}
function onQueryFailed(sender, args) {
var failed = "Redan bokat!";
alert(failed);
}
Look at all your set_items. Most likely your date fields need an actual date object to be stored successfully to SP.
var currDate = new Date();
listItem.set_item('DateColumn',currDate);
listItem.update();
Cool stuff here to: http://alexeybbb.blogspot.com/2012/09/sharepoint15-js-update-datetime-field.html
Trying to fetch the last modified time of Sharepoint list. Found a code that states the author and modified by. It was working fine when it had the line
<input id="btnGetFieldUserValue" onclick="getFieldUserValue()" type="button" value="Get Created by and Modified by"/>
but when i changed to
<div id="create" onload="getFieldUserValue()"> </div>
No repose in the content editor webpart of sharepoint 2013.
Help.
My task is to show the last updation time of the list. Any other way to do that, please share.
var listItem;
var list;
var clientContext;
function getFieldUserValue() {
this.clientContext = SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
this.list = webSite.get_lists().getByTitle("Resource Readiness");
this.listItem = list.getItemById(1);
clientContext.load(this.listItem);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
}
}
function OnLoadSuccess(sender, args) {
var fieldUserValueCreatedBy = this.listItem.get_item("Author");
var fieldUserValueModifiedBy = this.listItem.get_item("Editor");
document.getElementById("create").innerHTML = fieldUserValueModifiedBy.get_lookupValue() ;
alert("Created By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n Modified By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n");
}
function OnLoadFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}</script>
You have to wait for script files:
function getFieldUserValue(){
SP.SOD.executeOrDelayUntilScriptLoaded(loadContext, 'sp.js');
}
function loadContext() {
this.clientContext = SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
this.list = webSite.get_lists().getByTitle("Resource Readiness");
this.listItem = list.getItemById(1);
clientContext.load(this.listItem);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
}
}
function OnLoadSuccess(sender, args) {
var fieldUserValueCreatedBy = this.listItem.get_item("Author");
var fieldUserValueModifiedBy = this.listItem.get_item("Editor");
document.getElementById("create").innerHTML = fieldUserValueModifiedBy.get_lookupValue() ;
alert("Created By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n Modified By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n");
}
function OnLoadFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
Is it possible to use Item-level Permissions in SP 2013 to disable other users modifying items not created by them but still allow them to modify a single field (column) from that item?
I want everyone to be able to input information in that column after clicking "Edit" item button but yet not able to modify any other field if the item is not created by him.
Only the item creator should be able to modify all the fields.
Any ideas how to achieve that are more than welcome :)
You could use client object model for the same as follows:
$(document).ready(function () {
if(CheckCreatedBy() != GetCurrentUser())
{
$("input[Title='EditableByAllUsers']").prop("disabled", true);
}
});
function CheckCreatedBy()
{
var clientContext = new SP.ClientContext.get_current();
var siteColl = clientContext.get_site();
var oList = siteColl.get_rootWeb().get_lists().getByTitle('ChangeEditForm');
var itemId = _spGetQueryParam('id') ;
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>'+ itemId +'</Value></Eq></Where></Query></View>');
this.collListItem= oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this,this.onCheckCreatedBySuccessMethod), Function.createDelegate(this, this.onCheckCreatedByFailureMethod));
return this.value;
}
function onCheckCreatedBySuccessMethod(sender, args)
{
var CreatedBy = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
CreatedBy = oListItem.get_item('Author').get_lookupValue();
alert(CreatedBy);
return CreatedBy ;
}
}
function onCheckCreatedByFailureMethod(sender, args)
{
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function GetCurrentUser()
{
var ClientContext = new SP.ClientContext.get_current();
this.CurrentWeb = ClientContext.get_web();
ClientContext.load(this.CurrentWeb.get_currentUser());
ClientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
return this.value;
}
function onSuccessMethod(sender, args)
{
var userObject =this.CurrentWeb.get_currentUser().get_title();
return userObject;
}
function onFailureMethod(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
It can also be done using XSL. This will help you with the same.
I hope this helps.