I am looking to have an email to send that will populate the e-mail address, Subject and Body of the e-mail. I tried the following but it will not work. Can someone assist?
<script src="/SiteAssets/jquery-3.4.0.js"></script>
<script type="text/javascript">
function SendMail()
{
var emailID = getEmailFromPeoplePicker('User Requesting Assistance');
var subject = getSubject('Ticket Number');
var body = getBody('Description of Problem');
location.href = "mailto:"+emailID+"?subject="+subject+"&body="+body;
}
function getSubject(subject)
{
return $('input[title="'+subject+'"]').val();
}
function getBody(body)
{
return $('input[title="'+body+'"]').val();
}
function getEmailFromPeoplePicker(title) {
//Get the people picker field
var ppDiv = $("div[title='" + title + "']")[0];
//cast the object as type PeoplePicker
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
//Get list of users from field (assuming 1 in this case)
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var userEmail;
//The description field contains the login info without the lookup extras. In new forms this
//field can be undefined depending on the field being checked. Only check if userInfo is
//initialized.
if(userInfo != null)
{
userEmail = userInfo.EntityData.Email;
}
return userEmail;
}
</script>
Email User
If you use the code in your post, the "Ticket Number" and "Description of Problem" will be all the single text field. If the "Description of Problem" field is multiple line of text field, the code will not works.
To get multiple lines of text, we can use the code below to achieve it. If you can't get the email of the user, you need check if the user have the email(go to user profile to check it).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function SendMail(){
var emailID = getEmailFromPeoplePicker('User Requesting Assistance');
var subject = getSubject('Ticket Number');
var body = getBody('Description of Problem');
location.href = "mailto:"+emailID+"?subject="+subject+"&body="+body;
}
function getSubject(subject){
return $('input[title="'+subject+'"]').val();
}
function getBody(body){
return $('nobr:contains("'+body+'")').closest('tr').find('.ms-rtestate-write')[0].innerText;
}
function getEmailFromPeoplePicker(title) {
//Get the people picker field
var ppDiv = $("div[title='" + title + "']")[0];
//cast the object as type PeoplePicker
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
//Get list of users from field (assuming 1 in this case)
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var userEmail;
//The description field contains the login info without the lookup extras. In new forms this
//field can be undefined depending on the field being checked. Only check if userInfo is
//initialized.
if(userInfo != null){
userEmail = userInfo.EntityData.Email;
}
return userEmail;
}
</script>
Email User
Related
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>
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'];
}
function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
message.text = txtMessage.text;
message.userName = txtUser.text;
//Posts to this swf
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function jsalertwindow(event:MouseEvent):void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}
As you can see there are two function which are contain mouseevent. I want to send those function with an if-else statement. If user write something in text input component which name is txtUser and,
send_btn.addEventListener(MouseEvent.CLICK, clickButtonHandler);
will work, else(if the user forget writing anything)
send_btn.addEventListener(MouseEvent.CLICK, jsalertwindow);
will work.
And one more question should i use MouseEvent.CLICK or MouseEvent.MOUSE_DOWN? Thanks for your advice.
Assign a single handler to the button click (MouseEvent.CLICK is the right event to use) and check the field is populated in the handler:
function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
// Check the field is populated
if (txtUser.text != "")
{
message.text = txtMessage.text;
message.userName = txtUser.text;
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
else
{
// Nothing in the input field, show the alert
showAlert();
}
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function showAlert():void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}
I am using managed client side object model in sharepoint 2010. And I want to get loginaName of the AssignedTo user in Task list.
In server side object model I use SPFieldUserValue.User.LoginName to get this property but in client side object model FieldUserValue.User does not exists.
How can I resolve this situation ?
Thanks
Here is the code for that. I've taken an example of AssignedTo field from Task list. I hope that helps.
public static User GetUserFromAssignedToField(string siteUrl)
{
// create site context
ClientContext ctx = new ClientContext(siteUrl);
// create web object
Web web = ctx.Web;
ctx.Load(web);
// get Tasks list
List list = ctx.Web.Lists.GetByTitle("Tasks");
ctx.Load(list);
// get list item using Id e.g. updating first item in the list
ListItem targetListItem = list.GetItemById(1);
// Load only the assigned to field from the list item
ctx.Load(targetListItem,
item => item["AssignedTo"]);
ctx.ExecuteQuery();
// create and cast the FieldUserValue from the value
FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];
Console.WriteLine("Request succeeded. \n\n");
Console.WriteLine("Retrieved user Id is: {0}", fuv.LookupId);
Console.WriteLine("Retrieved login name is: {0}", fuv.LookupValue);
User user = ctx.Web.EnsureUser(fuv.LookupValue);
ctx.Load(user);
ctx.ExecuteQuery();
// display the user's email address.
Consol.writeLine("User Email: " + user.Email);
return user;
}
The fuv.LookupValue may contain the display name, not the login name, so my suggestion is (assuming you have the FieldUserValue - fuv in code (as descibed by #ekhanna):
var userId = fuv.LookupId;
var user = ctx.Web.GetUserById(userId);
ctx.Load(user);
ctx.ExecuteQuery();
You get the column which as the FieldUserValue from the list, once you have that you use the lookup id value and then query against the Sites User Info List. In the example below I cache the results to prevent looking up the same id more than once since the query can be expensive.
private readonly Dictionary<int, string> userNameCache = new Dictionary<int, string>();
public string GetUserName(object user)
{
if (user == null)
{
return string.Empty;
}
var username = string.Empty;
var spUser = user as FieldUserValue;
if (spUser != null)
{
if (!userNameCache.TryGetValue(spUser.LookupId, out username))
{
var userInfoList = context.Web.SiteUserInfoList;
context.Load(userInfoList);
var query = new CamlQuery { ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='ID' /><Value Type='int'>" + spUser.LookupId + "</Value></Eq></Where></Query></View>" };
var users = userInfoList.GetItems(query);
context.Load(users, items => items.Include(
item => item.Id,
item => item["Name"]));
if (context.TryExecuteQuery())
{
var principal = users.GetById(spUser.LookupId);
context.Load(principal);
context.ExecuteQuery()
username = principal["Name"] as string;
userNameCache.Add(spUser.LookupId, username);
}
}
}
return username;
}
Everything above worked for me, but instead of:
FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];
I used:
FieldUserValue[] fuv = targetListItem["AssignedTo"] as FieldUserValue[];
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() {}