Sharepoint 2013 - Fetch last modified date of the list - sharepoint

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

Related

Use client side rendering(js link) for dynamically created Sharepoint document library

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

Add group to list using SharePoint 2010 JSOM

Can someone give me an example of adding a SharePoint group to a list using the javascript client object model. I was able to create groups and add them to the site but I haven't seen any documentation on adding the groups to a list? I know how to do this via c# but not javascript.
How to grant permissions for Group in List via CSOM (JavaScript) in SharePoint 2013
The following example demonstrates how to grant Contribute permissions for group Approvers in list:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var group = web.get_siteGroups().getByName("Approvers");
var roleDef = web.get_roleDefinitions().getByType(SP.RoleType.contributor);
var roleDefBindings = SP.RoleDefinitionBindingCollection.newObject(context);
roleDefBindings.add(roleDef);
list.get_roleAssignments().add(group,roleDefBindings);
list.update();
context.load(group);
context.load(list);
context.load(roleDef);
context.executeQueryAsync(
function () {
console.log('For group ' + group.get_title() + ' has been granted ' + roleDef.get_name() + ' permissons in List ' + list.get_title());
},
function (sender, args) {
console.log("Error: " + args.get_message());
}
);
Since SP.GroupCollection does not contain the method getByName in SharePoint 2010, use the method SP.GroupCollection.getById(id) instead to return Group client object:
var group = web.get_siteGroups().getById(16); //get Approvers group by Id
function getGroupByName(groupName, completeFunction) {
if (groupName == null) {
throw new Error("Group Name cannot be null");
}
var rv = null;
var currentContext = SP.ClientContext.get_current();
var currentWeb = currentWeb = currentContext.get_web();
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
currentContext.executeQueryAsync(getGroupByName_Success, getGroupByName_Failed);
function getGroupByName_Success() {
var groupEnumerator = allGroups.getEnumerator();
while (groupEnumerator.moveNext()) {
rv = groupEnumerator.get_current();
var groupTitle = rv.get_title();
if (groupTitle == groupName) {
groupFound = true;
break;
}
}
if (groupFound == false) {
rv = null;
}
completeFunction(rv);
}
function getGroupByName_Failed(sender, args) {
alert("Error Occurred: " + args.get_message() + "\n" + args.get_stackTrace());
}
}

i want display list in sharepoint 2013 uses js

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

SP list item - disable "Edit" for all users except for the item creator but still leave a single column editable for all users

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.

Why does this code return a value two times?

I made a code to copy over files and then it has to return the path of the copied folder but it returns a value twice!?
Also it shows the MessageBox twice and it executes SaveData also twice!?
Why does this happen??
public string Copy(string sourceDir, string targetDir)
{
System.IO.Directory.CreateDirectory(targetDir);
foreach (var file in System.IO.Directory.GetFiles(sourceDir))
System.IO.File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)));
foreach (var directory in System.IO.Directory.GetDirectories(sourceDir))
Copy(directory, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(directory)));
XML_INFO info = new XML_INFO();
info.xmlIDCode = (tmpPluginNumberID.ToString());
SaveData(info, targetDir + #"\" + tmpPluginName + ".xml");
System.IO.File.Delete(Environment.CurrentDirectory + #"\GameData\" + tmpPluginName + ".xml");
MessageBox.Show(System.IO.Directory.GetParent(targetDir + #"\aFile.xml").ToString());
return targetDir;
}
this code is called from here :
private void COPY_TO_GAME_BUTTON_Click(object sender, EventArgs e)
{
foreach (var v in listView1.SelectedItems)
{
ListViewItem lvi = ((ListViewItem)v);
tmpPluginNumberID = int.Parse(lvi.SubItems[4].Text);
tmpPluginName = lvi.Text;
string sourceDir = lvi.SubItems[1].Text;
DialogResult dr = MessageBox.Show("Do you want to copy the selected plugin to GameData?" + Environment.NewLine + "By clicking 'no' the plugin will be copied to the root of the game." + Environment.NewLine + "Note that only plugins copied to GameData are supported with Stats and Update data.", "How do we install?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
lvi.SubItems[3].Text = "Imported to GameData";
lvi.SubItems[2].Text = Copy(sourceDir, Environment.CurrentDirectory + #"\GameData");
saveXML(lvi.Text, lvi.SubItems[1].Text,lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[4].Text, true);
}
else if (dr == DialogResult.No)
{
Copy(sourceDir, Environment.CurrentDirectory + #"\");
lvi.SubItems[2].Text = "GameData path is unavailable when copied to root the game.";
lvi.SubItems[3].Text = "Stats are unavailable when copied to root the game";
saveXML(lvi.Text, lvi.SubItems[1].Text, lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[4].Text, true);
}
else
{
}
}
}
AHA I found it I called the function also inside the function to fix it I made this function :
public void CopyPhaseTwo(string sourceDir, string targetDir)
{
System.IO.Directory.CreateDirectory(targetDir);
foreach (var file in System.IO.Directory.GetFiles(sourceDir))
System.IO.File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)));
foreach (var directory in System.IO.Directory.GetDirectories(sourceDir))
Copy(directory, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(directory)));
}

Resources