Number of items to show in Javascript - sharepoint

I'm using Content Search Web Part on SP 2013, I'm trying to get the value for Number of items to show option in Javascript from the ctx object. I have tried ctx.ListData.ResultTables[0].RowCount but seems like this value is for the count on the current page only, not the configured in the 'Number of items to show' option within web part configuration.
Number of items to show value in UI
In addition, do you know where can I find more information on how to debug the ctx object or the properties or methods it uses. Any help would be appreciated. Thanks in advance.

We can use JSOM to achieve it. The following code for your reference.
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveWPProperties, "sp.js");
function retrieveWPProperties(){
var pageurl=_spPageContextInfo.serverRequestPath; //current page
var currentCtx = new SP.ClientContext.get_current();
var pageFile = currentCtx.get_web().getFileByServerRelativeUrl(pageurl);
var webPartManager = pageFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webPartDefs = webPartManager.get_webParts();
currentCtx.load(webPartDefs, 'Include(WebPart.Properties)');
currentCtx.executeQueryAsync(
function () {
if (webPartDefs.get_count()) {
for (var i = 0; i < webPartDefs.get_count() ; i++) {
var webPartDef = webPartDefs.getItemAtIndex(i);
var webPart = webPartDef.get_webPart();
var properties = webPart.get_properties();
//console.log(JSON.stringify(properties.get_fieldValues())); //print all properties
if(properties.get_fieldValues().Title=="Content Search"){
var resultsPerPage=properties.get_fieldValues().ResultsPerPage;
alert(resultsPerPage);
}
}
}
else {
console.log("No web parts found.");
}
},
function (sender, args) {
console.log(args.get_message());
});
}
</script>

Related

How to automate site creation on save in a SP list form using JSOM?

For one of the Clients Requirements, I have to automate Sharepoint site creation on a button click. Basically there will be a SharePoint list form in which a user will enter data as title, url, and select a template. Once clicked on save it should create a sharepoint site. I have been able to implement this using a HTML form web part but now i need to Use SharePoint OOTB list form and need to do the same thing. Below is the code I wrote that creates a sharepoint site upon button click, the code works fine and creates a site depending upon the selection. I am using SharePoint online.
Any ideas on how to convert this approach to A Sharepoint list form approach?
<script src="//code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction(){
CreateSubWeb();
return true;
}
function CreateSubWeb() {
// defualt list Title field
var webTitle=$("input[title='Client_x0020_Name']").val();
//custom fields URL and Template
var url=$("input[title='Site_x0020_URL']").val();
var template=$("input[title='Custom_x0020_Template']").val();
// current web url
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var clientContext = new SP.ClientContext(webUrl);
this.oWebsite = clientContext.get_web();
var webCreationInfo = new SP.WebCreationInformation();
webCreationInfo.set_title(webTitle);
webCreationInfo.set_language(1033);
webCreationInfo.set_url(url);
webCreationInfo.set_useSamePermissionsAsParentSite(true);
if(template == 'Customer W Project'){
webCreationInfo.set_webTemplate("{2936BD84-30AD-413E-8933-2A6B7856D10F}#Template 2");
}
else
{
webCreationInfo.set_webTemplate("{ED884F01-6B10-4791-A704-FF05A047D0F3}#Template 1");
}
oWebsite.get_webs().add(webCreationInfo);
oWebsite.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
function onQuerySucceeded(sender, args) {
alert('success');
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
The code below for your reference, add the code into script editor web part in new form page.
<script src="//code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction(){
var templateName=$("select[title='Custom Template']").val();
getTemplateName(templateName).done(function(template) {
createSubSite(template);
});
return true;
}
var createSubSite = function(templateName) {
// defualt list Title field
var webTitle=$("input[title='Title Required Field']").val();
//custom fields URL and Template
var url=$("input[title='Site URL']").val();
// current web url
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var clientContext = new SP.ClientContext(webUrl);
this.oWebsite = clientContext.get_web();
var webCreationInfo = new SP.WebCreationInformation();
webCreationInfo.set_title(webTitle);
webCreationInfo.set_language(1033);
webCreationInfo.set_url(url);
webCreationInfo.set_useSamePermissionsAsParentSite(true);
webCreationInfo.set_webTemplate(templateName);
oWebsite.get_webs().add(webCreationInfo);
oWebsite.update();
clientContext.executeQueryAsync(function() {
console.log("Done");
}, function(sender,args){
console.log("failed. Message:" + args.get_message());
});
}
var getTemplateName = function(templateName) {
var dfd = new $.Deferred();
var clientContext = SP.ClientContext.get_current();
var templates = clientContext.get_web().getAvailableWebTemplates(1033, false);
clientContext.load(templates);
clientContext.executeQueryAsync(function() {
var templateGuidName;
for (var template in templates.get_data()) {
if (templates.itemAt(template).get_title() === templateName) {
templateGuidName = templates.itemAt(template).get_name();
break;
}
}
dfd.resolve(templateGuidName);
}, function() { dfd.reject(); });
return dfd.promise();
}
</script>

SharePoint userProfileProperties JSOM (JavaScript Object Model)

I am tryin to get some info from PeopleManager.getMyProperties() function.
I get the object,some values are null.when i check it from User Profile from Management,I can see the value. How can i fix this one ?
There is my working code to get object.
Note : I want to access Custom Property from User Profile which I created before.
I can see the property in the object but value is not coming.
Thank You All..
$(document).ready(function(){
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties;
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Get properties of the current user
userProfileProperties = peopleManager.getMyProperties();
clientContext.load(userProfileProperties);
//Execute the Query.
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
console.log(userProfileProperties)
}
function onFail(sender, args) {
console.log("Error: " + args.get_message());
}
Try the below code and let me know. It works fine for me. I have passed the user name instead of My account. So that you can pass any user account here.
function getUserProperties(userName) {
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
var profilePropertyNames = ["FirstName", "LastName", "CustomProperty"]; //Have to load all the needed properties here
var targetUser = userName.trim();
var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(clientContext, targetUser, profilePropertyNames);
userProfileProperties = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);
clientContext.load(userProfilePropertiesForUser);
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
// userProfileProperties result index is same as the properties loaded above
var firstName=userProfileProperties[0];
var lastName=userProfileProperties[1];
var customprop=userProfileProperties[2];
}
Mark it as answer if it helps.
I forget to write the solution,sorry for that one.
I tried the code which written by #NaveenPrasath. It is giving a lot of fields but it didn't return "Custom Prop Field".
Working code is shown below.
function getUserProperties(targetUser) {
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
personProperties = peopleManager.getPropertiesFor(targetUser);
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
function onRequestSuccess() {
var fullName = personProperties.get_userProfileProperties()['CustomPropField'];
}

FabricJS double click on objects

I am trying to perform a special action whenever the user double clicks any object located inside the canvas. I have read the docs and not found any mouse:dblclick-like event in the documentation. I tried doing something like:
fabric.util.addListener(fabric.document, 'dblclick', callback);
Which does trigger the dblclick event but does not give specific information about the actual object that is being clicked on the canvas.
Any ideas of the most FabricJS-y way of doing this?
The more elegant way is to override fabric.Canvas._initEventListeners to add the dblclick support
_initEventListeners: function() {
var self = this;
self.callSuper('_initEventListeners');
addListener(self.upperCanvasEl, 'dblclick', self._onDoubleClick);
}
_onDoubleClick: function(e) {
var self = this;
var target = self.findTarget(e);
self.fire('mouse:dblclick', {
target: target,
e: e
});
if (target && !self.isDrawingMode) {
// To unify the behavior, the object's double click event does not fire on drawing mode.
target.fire('object:dblclick', {
e: e
});
}
}
I've also developed a library to implement more events missed in fabricjs : https://github.com/mazong1123/fabric.ext
This is similar to #LeoCreer's answer but actually gets access to the targeted object
fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function (e) {
var target = canvas.findTarget(e);
});
The Correct way to add custom events to Fabric.js
window.fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function (event, self) {
yourFunction(event);
});
or use fabric.ext
I'm using this workaround:
var timer = 0;
canvas.item(0).on('mouseup', function() {
var d = new Date();
timer = d.getTime();
});
canvas.item(0).on('mousedown', function() {
var d = new Date();
if ((d.getTime() - timer) < 300) {
console.log('double click')
}
});
Here is a quick and easy way to add a double click event handler to Fabric JS -
Include following code snippet to your html file. Just ensure this is loaded after the main fabric.js library
<script type="text/javascript">
fabric = (function(f) { var nativeOn = f.on; var dblClickSubscribers = []; var nativeCanvas = f.Canvas; f.Canvas = (function(domId, options) { var canvasDomElement = document.getElementById(domId); var c = new nativeCanvas(domId, options); c.dblclick = function(handler) { dblClickSubscribers.push(handler) }; canvasDomElement.nextSibling.ondblclick = function(ev){ for(var i = 0; i < dblClickSubscribers.length; i++) { console.log(ev); dblClickSubscribers[i]({ e :ev }); } }; return c; }); return f; }(fabric));
</script>
Then add this code to listen a double click event:
canvas.dblclick(function(e) {
});
To get information about the actual object that is being clicked on the canvas, use following method -
canvas.getActiveObject();
eg.
canvas.dblclick(function(e) {
activeObject = canvas.getActiveObject();
});
I am late but now fabricjs has mousedblclick event.
Listed at: http://fabricjs.com/docs/fabric.Object.html
See all events:
http://fabricjs.com/events

Loading itemTemplate for WinJS.UI.ListView from external source

I am wondering if someone can shed some light on why this does not work.
I can successfully dynamically template each WinJS.UI.ListView item if I define the templates in my html view (First Scenario). However if I load the template from a seperate html file using a $.get statement it does not work (Second Scenario).
self.selectTemplate = function (itemPromise) {
return itemPromise.then(function (item) { ...
First Scenario:
(var itemTemplate = document.getElementById(item.data.controlType + "ItemTemplate");
var container = document.createElement("div");
itemTemplate.winControl.render(item.data, container);
return container;)
Second Scenario:
(var itemTemplatePromise = ko.bindingHandlers.searchPropertyBuilder.loadTemplate(item.data.controlType);
itemTemplatePromise.done(function (itemTemplateLoaded) {
var templateContainer = document.createElement("div");
templateContainer.innerHTML = itemTemplateLoaded;
templateElement = templateContainer.firstChild;
WinJS.UI.process(templateElement);
var container = document.createElement("div");
templateElement.winControl.render(item.data, container);
return container;
});)
}
WinJS.Utilities.markSupportedForProcessing(self.selectTemplate);
WinJS.Namespace.define("TemplateSelector", {
template: self.selectTemplate
});
I can see one bug in the code. but not sure if that is the only issue here. promises needs to be chained. winjs.ui.processAll returns a promise.
itemTemplatePromise.then(function (itemTemplateLoaded) {
var templateContainer = document.createElement("div");
templateContainer.innerHTML = itemTemplateLoaded;
templateElement = templateContainer.firstChild;
return WinJS.UI.processAll(templateElement);
}).then(function onprocessall()
{
var container = document.createElement("div");
templateElement.winControl.render(item.data, container);
return container;
});

How to get current Item in Custom Form Action Sharepoint Designer

On custom edit page of list item, I want to do the following
- On clicking Form Action Hyperlink [DataView Control], custom form action will fire to update
a item hidden field [Status].
I already tried the following
- Passing #ID to the work flow but didnt work
- Create a duplicate ID column and updated it with the ID on Item Creation. and then tried to access in "Update Item in" Action but getting "An unexpected error has occurred" while running it.
[Remember i can only use sharepoint designer]
Try to use these javascript functions:
function GetQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
function GetCurrentItem() {
var itemId = GetQueryVariable("ID");
try {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('list-title');
this.currItem = list.getItemById(itemId);
context.load(currItem);
context.executeQueryAsync(Function.createDelegate(this, this.funcSuccess), Function.createDelegate(this, this.funcFailed));
}
catch (e) {
alert(e);
}
}
function funcSuccess() {}
function funcFailed() {}

Resources