Sharepoint 2013: Inserting image on page javascript csom - sharepoint

I create a new page with javascript csom. I am able to give it a title, byline, content etc., but it won't accept an image reference. It doesn't give me any error messages, nor reaching my error function, but I'm obviously missing something here as the new page does not have any images attached.
Any ideas on how to do this?
Here is my code:
var pageInfo = new SP.Publishing.PublishingPageInformation();
var newPage = pubWeb.addPublishingPage(pageInfo);
context.load(newPage);
context.executeQueryAsync(function () {
var listItem = newPage.get_listItem();
context.load(listItem);
context.executeQueryAsync(function () {
var title = $('#head').val();
listItem.set_item('Title', title);
listItem.set_item('PublishingPageImage', { "Url": "/sites/intranett/PublishingImages/ExampleImage.png", "Description": "testing" });
listItem.update();
context.executeQueryAsync(function () { }, onFailedCallback);
}, onFailedCallback);
}, onFailedCallback);

I needed to include the html image tag when setting the PublishingPageImage property.
listItem.set_item('PublishingPageImage', "<img alt='image' src='/sites/intranett/PublishingImages/ExampleImage'>");

Related

How to put selection text in chrome.contextMenus?

How can I add selection text in context.Menus?
I want to create a Chrome extension which will work similarly to the right-click search function in Google Chrome (i.e. right click on selected text -> "Search 'selection text')
I made a preview
I assume this is something with chrome.contextMenus.update but i don't know how to make it work
background.js:
chrome.runtime.onInstalled.addListener(function () {
var context = "selection";
var title = "Search";
var id = chrome.contextMenus.create({
"title": title,
"contexts": [context],
"id": "context" + context
});
});
// add click event
chrome.contextMenus.onClicked.addListener(onClickHandler);
// The onClicked callback function.
function onClickHandler(info, tab) {
var sText = info.selectionText;
var url = "https://www.google.com/search?source=hp&q=" + encodeURIComponent(sText);
window.open(url, '_blank');
};

SharePoint: get list Title or URL (JSLink)

I have a JSLink function overriding the default footer of a list view webpart. How can I retrieve this list's title (or URL) so that it can be added to the footer?
(function () {
var overrideContext = {};
overrideContext.Templates = {};
overrideContext.Templates.Footer = overrideCustomFooter;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext); })();
function overrideCustomFooter() {
return "<div><a href='https://somesite/Lists/[LIST TITLE]'>See more</a></div>"; }
Thank you very much in advance!
There are several options available:
Via SP.PageContextInfo object:
The following example absolute url of list:
const listBasUrl = _spPageContextInfo.webAbsoluteUrl + _spPageContextInfo.listUrl
Via context passed into Templates.Footer function:
ctx.listUrlDir -server relative url to List
Example
function renderFooter(ctx){
console.log(ctx.listUrlDir);
return "";
}
where
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
Templates: {
Footer: renderFooter
},
});

Sharepoint - Custom error messages

I'm a beginner sharepoint developer for a work project.
Specifications ask for custom error message.
When I create a list with a number field the error message is "Only numbers can go here".
<Field Name="Libelle" ID="{487dfca6-af3c-4939-94b1-2e5ae5aefb44}" DisplayName="Libelle" Type="Number" EnforceUniqueValues="TRUE" Indexed="TRUE" Required="TRUE" />
Can I change this?
The validation message for the SPField is a property on the field called ValidationMessage in the Microsoft.SharePoint namespace, or validationMessage in the SP namespace if you are working with the SP.js framework.
The validation message is controlled from a property that differs depending on what model you are using when developing towards SharePoint.
Field.ValidationMessage in the Microsoft.SharePoint.Client namespace
SP.Field.validationMessage in the SP.js namespace
SPField.ValidationMessage in the Microsoft.SharePoint namespace
Using C# to set the validation message on SPField
using (SPWeb web = site.OpenWeb())
{
//Get the list with your field
SPList list = web.Lists["Your list name here"];
//Get the field
SPField field = list["FieldName"];
field.ValidationMessage = "Your custom validation message.";
}
Using JSOM to set the validation message on SP.Field
function setValidationMessage() {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle("Your list title");
var field = list.get_fields().getByInternalNameOrTitle("Your field title or internal name");
field.set_validationMessage("Your new validation message");
field.update();
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
console.log("Validation message successfully updated!");
}
function onQueryFailed(sender, args) {
console.log("Failed to update validation message!");
}
Using the Sharepoint REST api to set the validation message on SP.Field
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists(listid)/fields(fieldid)/validationMessage",
type: "POST",
data: JSON.stringify({
'__metadata': {
'type': 'SP.Field'
},
'validationMessage': 'Your custom validation message!'
}),
headers: {
"IF-MATCH": "*",
"X-HTTP-Method":"PATCH",
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
});
Additional info here.
You can also set the validation message from the settings in the SharePoint site by going to the column in site settings, select "Validation" and the "Validation message".
Open your list like this:-
https://site.sharepoint.com/Lists/List Title/NewForm.aspx?RootFolder=
Note:- Replace 'List Title' with your List Title
Edit this page and add 'Content Editor WebPart'(under 'Media and Content')
In content Editor Webpart Paste this script:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$(document).ready(function(){
$("input[title='Libelle']").blur(function(){
var txt = $("input[title='Libelle']").val();
if(!isNumber(txt)){
$("input[title='Libelle']").val("");
alert('Only numbers can go here');
}
});
});
</script>

Sharepoint 2010 list creation using ecmascript

i am new to ECMAScript and share point development, i have small requirement i need to create one list using ECMAScript and while creation it has to check whether the list already exists in the site ,if list doesn't exist new list has to create.
You can use SPServices with "GetListCollection" to find all the lists in a Sharepoint, and then use "AddList" to create it.
Something like:
var myList="My List Test"; // the name of your list
var listExists=false;
$().SPServices({
operation: "GetListCollection",
async: true,
webURL:"http://my.share.point/my/dir/",
completefunc: function (xData, Status) {
// go through the result
$(xData.responseXML).find('List').each(function() {
if ($(this).attr("Title") == myList) { listExists=true; return false }
})
// if the list doesn't exist
if (!listExists) {
// see the MSDN documentation available from the SPService website
$().SPServices({
operation: "AddList",
async: true,
webURL:"http://my.share.point/my/dir/",
listName:myList,
description:"My description",
templateID:100
})
}
}
});
Make sure to read the website correctly, and especially the FAQ. You'll need to include jQuery and then SPServices in your code.
You could utilize JSOM or SOAP Services for that purpose, below is demonstrated JSOM solution.
How to create a List using JSOM in SharePoint 2010
function createList(siteUrl,listTitle,listTemplateType,success,error) {
var context = new SP.ClientContext(siteUrl);
var web = context.get_web();
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(listTitle);
listCreationInfo.set_templateType(listTemplateType);
var list = web.get_lists().add(listCreationInfo);
context.load(list);
context.executeQueryAsync(
function(){
success(list);
},
error
);
}
How to determine whether list exists in Web
Unfortunately JSOM API does not contains any "built-in" methods to determine whether list exists or not, but you could use the following approach.
One solution would be to load Web object with lists collection and then iterate through list collection to find a specific list:
context.load(web, 'Lists');
Solution
The following example demonstrates how to determine whether List exist via JSOM:
function listExists(siteUrl,listTitle,success,error) {
var context = new SP.ClientContext(siteUrl);
var web = context.get_web();
context.load(web,'Lists');
context.load(web);
context.executeQueryAsync(
function(){
var lists = web.get_lists();
var listExists = false;
var e = lists.getEnumerator();
while (e.moveNext()) {
var list = e.get_current();
if(list.get_title() == listTitle) {
listExists = true;
break;
}
}
success(listExists);
},
error
);
}
Usage
var webUrl = 'http://contoso.intarnet.com';
var listTitle = 'Toolbox Links';
listExists(webUrl,listTitle,
function(listFound) {
if(!listFound){
createList(webUrl,listTitle,SP.ListTemplateType.links,
function(list){
console.log('List ' + list.get_title() + ' has been created succesfully');
},
function(sender, args) {
console.log('Error:' + args.get_message());
}
);
}
else {
console.log('List with title ' + listTitle + ' already exists');
}
}
);
References
How to: Complete basic operations using JavaScript library code in SharePoint 2013

Titanium mobile - Common JS. Objects values are lost when lauching a fireEvent

I'm dev an app into titanium mobile in javascript.
The dynamic menu insert each new object(id,text,...., page) into a loop for (var x in tab).
with thoses items, specifics views are made.
var items = [];
var menuIconsItem = require('view/module/menuIconsItem');
for(var i in itemTab) {
var page = itemTab[i].page;
items[i] = new menuIconsItem(itemTab[i]);
menuFirstLine.add(items[i]);
(function(itemsEvent) {
itemsEvent.addEventListener('click', function() {
Ti.App.fireEvent('test' +i, {
id : i
});
})
})(items[i]);
}
on the other controller side, i only get the last id reference.
If i = 0 to 5, i only get the last reference. The rest is undefined.
How could i do please?
First you have to set id for your menuIconsItem, I am taking button an an example here.
items[i] = Titanium.UI.createButton({
id:"button_"+i,
_index: i
})
Then do this:
(function(itemsEvent) {
itemsEvent.addEventListener('click', function(e) {
alert(e.source.id);
})
})(items[i]);

Resources