We get two different error reports for SharePoint surveys - sharepoint

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

Related

Getting users job title in Sharepoint List

So I have a SP Online list, that every user can submit his entries. I have a default column of "created by", where the user, that submited the entry is listed. I'd like to have 2 other columns, to get users Department and Job Title copied automatically from users account. How can I do this?
Method 1:
You can use the JSOM to set the Department/JobTitle. Because we don't sure where your user from(AD or some else )
First of all you need to load the “SP.UserProfiles.js, SP.Runtime.js and SP.js” js files on your SharePoint page, use following code snippet to load these files,
$(document).ready(function () {
var scriptbase = _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase + "SP.UserProfiles.js", GetUserInformation);
});
});
});
var userProfileProperties;
function GetUserInformation() {
// Get the current client context.
var clientContext = SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
var targetUser = "domain\\userId";
userProfileProperties = peopleManager.getPropertiesFor(targetUser);
//Execute the Query.
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(onSuccess, onFail); }
function onSuccess () {
// get user information from userProfileProperties and set to your target column.
userProfileProperties.get_userProfileProperties()['Department'];
userProfileProperties.get_userProfileProperties()['SPS-JobTitle'];
// To do: list item replace operation
}
function onFail (sender, args) {
alert("Error: " + args.get_message());
}
Reference:https://msdn.microsoft.com/en-us/library/office/jj679700.aspx
Method 2: Workflow
When user add/edit a item,we trigger the workflow to copy the user's department/JobTitle to target column
Reference for get the Department/Jobtitle.
https://sharepoint.stackexchange.com/questions/97971/get-current-user-information-and-add-to-email-action-in-workflow

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>

List 'created by' in column

I know there is surveylist.get_description and surveylist.get_itemCount. I would like to know if there is a way to get created by fit in a column?
From syntax i guess you are using Javascriot CSOM.
Try this:
surveylist.get_author
Don't forget that you need to explicitly specify which properties you want to retrieve before you can get their values.
Unfortunately List Author property is not exposed via SharePoint CSOM.
How to retrieve List Author property via CSOM?
The idea is to retrieve SPList.SchemaXml property and extract Author property
function getListAuthor(listTitle,OnSuccess,OnError) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
context.load(web);
context.load(list,'SchemaXml');
context.executeQueryAsync(function(sender,args){
var schemaXml = $.parseXML(list.get_schemaXml());
var authorId = parseInt($(schemaXml).find('List').attr('Author')); //SchemaXml contains Author ID only
var listAuthor = web.getUserById(authorId);
context.load(listAuthor);
context.executeQueryAsync(OnSuccess(listAuthor),OnError);
},OnError);
}
//Usage
getListAuthor('Discussions List',
function(author){
console.log('List created by: ' + author.get_loginName())
},
function(sender,args){
console.log('Error occured:' + args.get_message());
}
);

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

Retrieving all Documents from couchdb using Node.js

I am writing a simple test app to experiment with the functionality of node.js and couchdb, so far i am loving it, but i ran in a snag. i have looked for and wide but can't seem to find an answer. My test server(a simple address book) does 2 things:
if the user goes to localhost:8000/{id} then my app returns the name and address of the user with that id.
if the user goes to localhost:8000/ then my app needs to return a list a names that are hyperlinks and takes them to the page localhost:8000/{id}.
I was able to get the first requirement working. i cant not seem to find how to retrieve a list of all names from my couchdb. that is what i need help with. here is my code:
var http = require('http');
var cradle = require('cradle');
var conn = new(cradle.Connection)();
var db = conn.database('users');
function getUserByID(id) {
var rv = "";
db.get(id, function(err,doc) {
rv = doc.name;
rv += " lives at " + doc.Address;
});
return rv;
}
function GetAllUsers() {
var rv = ""
return rv;
}
var server = http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type':'text/plain'});
var rv = "" ;
var id = req.url.substr(1);
if (id != "")
rv = getUserByID(id);
else
rv = GetAllUsers();
res.end(rv);
});
server.listen(8000);
console.log("server is runnig");
As you can see, I need to fill in the GetAllUsers() function. Any help would be appreciated. Thanks in advance.
I would expect you to be doing something like (using nano, which is a library I authored):
var db = require('nano')('http://localhost:5984/my_db')
, per_page = 10
, params = {include_docs: true, limit: per_page, descending: true}
;
db.list(params, function(error,body,headers) {
console.log(body);
});
I'm not pretty sure what you are trying to accomplish with http over there but feel free to head to my blog if you are looking for some more examples. Just wrote a blog post for people getting started with node and couch
As said above it will come a time when you will need to create your own view. Check up the CouchDB API Wiki, then scan thru the book, check what are design documents, then if you like you can go and check the test code I have for view generation and querying.
You can create a CouchDB view which will list the users. Here are several resources on CouchDB views which you should read in order to get a bigger picture on this topic:
Introduction to CouchDB Views
Finding Your Data with Views
View Cookbook for SQL Jockeys
HTTP View API
So let's say you have documents structured like this:
{
"_id": generated by CouchDB,
"_rev": generated by CouchDB,
"type": "user",
"name": "Johny Bravo",
"isHyperlink": true
}
Then you can create a CouchDB view (the map part) which would look like this:
// view map function definition
function(doc) {
// first check if the doc has type and isHyperlink fields
if(doc.type && doc.isHyperlink) {
// now check if the type is user and isHyperlink is true (this can also inclided in the statement above)
if((doc.type === "user") && (doc.isHyperlink === true)) {
// if the above statements are correct then emit name as it's key and document as value (you can change what is emitted to whatever you want, this is just for example)
emit(doc.name, doc);
}
}
}
When a view is created you can query it from your node.js application:
// query a view
db.view('location of your view', function (err, res) {
// loop through each row returned by the view
res.forEach(function (row) {
// print out to console it's name and isHyperlink flag
console.log(row.name + " - " + row.isHyperlink);
});
});
This is just an example. First I would recommend to go through the resources above and learn the basics of CouchDB views and it's capabilities.

Resources