Sharepoint - Custom error messages - sharepoint

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>

Related

SharePoint Hosted App - Creating cascaded drop down on hosted web lists

I have created a SharePoint Hosted App(Javascript Object Model) that creates lists on the host web.
I need to put some javascript into new and edit forms in order to create the cascaded drop down effect on 2 lookup fields.
Here is how I create the lists and the fields for it:
// Create a new list on host web
var createList = function (listTitle, onSuccess, onFieldsReady) {
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(listTitle);
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
var lists = hostWeb.get_lists();
var newList = lists.add(listCreationInfo);
currentContext.load(newList);
currentContext.executeQueryAsync(onSuccess(newList, onFieldsReady), onListCreationFail);
}
// Create a new field on a list
var createField = function (list, fieldType, fieldName, fieldDisplayName, fieldRequired, onSuccess) {
var fields = list.get_fields();
var fieldXml = "<Field Type='" + fieldType + "' Required='" + fieldRequired + "' DisplayName='" + fieldDisplayName + "' Name='" + fieldName + "'></Field>";
var createdField = fields.addFieldAsXml(fieldXml, true, SP.AddFieldOptions.addFieldInternalNameHint | SP.AddFieldOptions.addFieldToDefaultView);
currentContext.load(createdField);
currentContext.executeQueryAsync(onSuccess, onProvisionFieldFail);
}
Can you please give me some advise?
Regards,
Marian
You should consider ditching the idea of using NewForm and Editform.aspx. Just write your own form and use the JSOM or WebApi to add/edit list items.
Sample code for adding item to a list:
jQuery.ajax({
url: "http://<site url>/_api/web/lists/GetByTitle('Test')",
type: "POST",
data: JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }),
headers: {
"X-HTTP-Method":"MERGE",
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"content-length": <length of post body>,
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: doSuccess,
error: doError
});
Reference: http://msdn.microsoft.com/en-us/library/office/jj164022(v=office.15).aspx
Try this.
var clientContext = new SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('ListName');
if(list) {
var fldCollection = list.get_fields();
var fieldLookup1 = clientContext.castTo(
fldCollection.addFieldAsXml('<Field Name="FieldName1" Type="Lookup" DisplayName="My Lookup Field 1" List="Lists/MyLookupList" ShowField="Title" />', true, SP.AddFieldOptions.addToDefaultContentType),
SP.FieldLookup
);
fieldLookup1.set_title("MyLookupField1");
fieldLookup1.set_description("Lookup field 1 description");
fieldLookup1.update();
list.update();
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
Please let me know if it works ;)
Have a nice day!

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

Sharepoint 2013: Inserting image on page javascript csom

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

We get two different error reports for SharePoint surveys

The nice response when a user tries to answer a survey twice is the message: "You are not allowed to respond again to this survey." But some of us are getting the standard "crash" screen for ASP.NET applications.
Is this a configuration item or something (we're on SP2007)?
Thanks in advance...
I ended up getting around this problem by completely substituting the default "Respond to..." button handler with this code, which replaces any attempt to re-take the survey with an alert informing the user he's done it already.
$(document).ready(function() {
var myQueryOptions = "<QueryOptions />";
//this was amazing: the value you need gets supplied by <UserID Type='Integer'/> (via Vadim Gremyachev)
var myQuery = "<Query><Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer'/></Value></Eq></Where></Query>"; //find any instance of the current user
var listPromise = $().SPServices({
operation: "GetListItems",
listName: "{58ECDD94-8817-43A9-ACEC-42A1657E2F25}", //dev Survey list
CAMLViewFields: "<ViewFields><FieldRef Name='ID' /></ViewFields>",
CAMLQuery: myQuery,
CAMLQueryOptions: myQueryOptions
});
listPromise.done(function() {
var iCount = $(listPromise.responseXML).SPFilterNode("rs:data").attr("ItemCount");
if(iCount > 0) {
$("[id*='_ctl00_toolBarTbl_RptControls_ctl00_diidIONewItem']").each(function() {
$(this).attr("onclick", "");
$(this).attr("href", "");
$(this).on("click", function() {alert("You've already taken the survey!");});
});
}
iCount++;
});
listPromise.fail(function() { alert("whoops");});
}); // $(document).ready()

CRM 2011 - setting a default value with JScript

We have CRM 2011 on premise. The Contact entity was customized to use a lookup to a custom entity Country instead of just a text field. When creating a new Contact we would like the country field to be set to Canada by default. I have the following function that does that:
function SetDefaultCountryCode(countryFieldId) {
var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}";
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
On the form OnLoad I invoke the function like that:
// set Country fields to Canada if not set
SetDefaultCountryCode('cga_address1country');
We have two servers - DEV and TEST. This JScript works fine in DEV. When I run it in TEST it does not work because the Canada in TEST has different id (GUID) - when I create it manually. I was hoping I could export the Country entity values from DEV and import them in TEST preserving their GUIDs. Unfortunately this did not work. I export the data to Excel file and it has the GUIDs of the countries. I also delete any existing Country records in TEST before importing. When I try to import it the import succeeds but does not create any records. If I add a new row in the excel file without specifing a Guid it will import it. It seems to me the import functionality was not meant to preserve the GUIDs of the records. But this also means my script will not work because it depends on the GUIDs.
I have two questions here:
Is it possible to export / import entity data preserving the GUIDs ?
If I cannot have the same GUIDs in DEV and TEST how I can make the JScript to work properly?
Thank you in advance for any help / feedback.
It's very bad practice to hard code your GUIDs and you discovered the problems of it.
As you stated above, we cannot have the same GUIDs but we have the same name. So, we have to query the name of the country using JScript and jQuery to retrieve the GUID.
In order to retireve information from client-side (or Entity Form):
We will use/consume REST Endpoint (testing in browser).
Upload jQuery lib.
Upload Json2 lib.
Use the AJAX function from the jQuery library.
Define your entity, columns and criteria.
Lets, look for querying REST Endpoint.
http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'
Take this URL, subsitute your actual values and paste it into your browser, you'll find that the response is returned in XML format. If there is any error, please ensure that the Entity name and its attribute are case senisitve.
After seeing your your results, we are going to call this URL using an AJAX call.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: 'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'',
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
// now we have the GUID of Canada, now I can continue my process
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
But before you copy the code to your form, you have to download the jQuery lib from here
Then upload it as a Web resource, add this web resource to the Form load libs.
Here is the complete code to be put in the form load event handler:
var context = GetGlobalContext();
// retireve the invoice record id (Opened Form)
var invoiceId = context.getQueryStringParameters().id;
var customerId;
//Retrieve the server url, which differs on-premise from on-line and
//shouldn't be hard-coded.
// this will return something like http://yourHostName/yourOrg
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT;
function SetDefaultCountryCode(countryFieldId, odataUri) {
odataUri = odataUri + '/ContactSet?$select=ContactId,FullName&$filter=FullName eq \'Ahmed Shawki\'';
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
}
One more thing, don't forget to check "Pass execution context as first parameter" box on the form properties.
EDIT: Beside adding the jQuery library into the form load event handler, add the Json2 lib as a web resource.
For more information about the REST Endpoint.
It is indeed possible to export and import records along with their guids, just not natively. You'd have to build an app that would export the data for you, then create identical records through the CRM API in the target environment. You just have to clear out fields that aren't valid for create (createdon, statecode, etc.) and just specify the same Guid. CRM will then create the record with that Guid.
The old 4.0 Configuration Data Tool does this. I can't recall if it works against a 2011 org, but it could be a starting point.

Resources