SharePoint List Form Textfield to a dropdown - forms

I've found a video from SharePointTech that explains how to change a textfield to a dropdown list on a List Form using data from open API. I'm trying to recreate it, but I'm hitting a roadblock with the new SharePoint Online. Instead of using "Country/Region", I created a new custom list with Company_Name. I took the person's code and made little changes that made a reference to "WorkCountry". When I save the changes (stop editing), the changes do not reflect and I get the same textfield. I had to use SharePoint Designer 2013 to create a new TestNewForm for new entry. Has anyone been able to reproduce this in SharePoint 2013 Designer? If so, would you be able an example?

I use jQuery's ajax method.
Updated code for your reference(you need to change the list name to your list name,InternalName is also):
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
var demo = window.demo || {};
demo.nodeTypes = {
commentNode: 8
};
demo.fetchCountries = function ($j) {
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Company_Name')/items",
type: "get",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$j('table.ms-formtable td.ms-formbody').contents().filter(function () {
return (this.nodeType == demo.nodeTypes.commentNode);
}).each(function (idx, node) {
if (node.nodeValue.match(/FieldInternalName="Country_x002f_Region"/)) {
// Find existing text field (<input> tag)
var inputTag = $(this).parent().find('input');
// Create <select> tag out of retrieved countries
var optionMarkup = '<option value="">Choose one...</option>';
$j.each(data.d.results, function (idx, company) {
optionMarkup += '<option>' + company.Title + '</option>';
});
var selectTag = $j('<select>' + optionMarkup + '</select>');
// Initialize value of <select> tag from value of <input>
selectTag.val(inputTag.val());
// Wire up event handlers to keep <select> and <input> tags in sync
inputTag.on('change', function () {
selectTag.val(inputTag.val());
});
selectTag.on('change', function () {
inputTag.val(selectTag.val());
});
// Add <select> tag to form and hide <input> tag
inputTag.hide();
inputTag.after(selectTag);
}
});
},
error: function (data) {
console.log(data)
}
});
}
if (window.jQuery) {
jQuery(document).ready(function () {
(function ($j) {
demo.fetchCountries($j);
})(jQuery);
});
}
</script>
My source list:
Test result:
Updated:
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
var demo = window.demo || {};
demo.nodeTypes = {
commentNode: 8
};
demo.fetchCountries = function ($j) {
$.ajax({
url: 'https://restcountries.eu/rest/v1/all',
type: "get",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$j('table.ms-formtable td.ms-formbody').contents().filter(function () {
return (this.nodeType == demo.nodeTypes.commentNode);
}).each(function (idx, node) {
if (node.nodeValue.match(/FieldInternalName="Country_x002f_Region"/)) {
// Find existing text field (<input> tag)
var inputTag = $(this).parent().find('input');
// Create <select> tag out of retrieved countries
var optionMarkup = '<option value="">Choose one...</option>';
$j.each(data, function (idx, company) {
optionMarkup += '<option>' + company.name + '</option>';
});
var selectTag = $j('<select>' + optionMarkup + '</select>');
// Initialize value of <select> tag from value of <input>
selectTag.val(inputTag.val());
// Wire up event handlers to keep <select> and <input> tags in sync
inputTag.on('change', function () {
selectTag.val(inputTag.val());
});
selectTag.on('change', function () {
inputTag.val(selectTag.val());
});
// Add <select> tag to form and hide <input> tag
inputTag.hide();
inputTag.after(selectTag);
}
});
},
error: function (data) {
console.log(data)
}
});
}
if (window.jQuery) {
jQuery(document).ready(function () {
(function ($j) {
demo.fetchCountries($j);
})(jQuery);
});
}
</script>
The difference in API will not have a great effect, the key is here '$ j.each (data, function (idx, company) {'. The structure of the return value of different APIs are different, you need to find useful data in return value.

Related

How to get items from SharePoint by Current User via REST or JSOM?

I have a SharePoint list with two columns:
users (type people, multiple values allowed)
responsible_department (type string)
I want to get the items from this list where the current user is in the ùsers` field. The field can have multiple users (multiple users allowed)!
I am currently able to get the current user:
var currentUser;
function init() {
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
console.log(currentUser.get_loginName());
}
function onQueryFailed(sender, args) {
console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
No i need to query the mutli user field in my list for all items where my current user is part of the people field. I dont know how to query for this.
Can someone help me out?
I found a solution on MSDN and this works for me:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var siteURL = _spPageContextInfo.webAbsoluteUrl;
var listname = "CustomList";
var currentUserId=_spPageContextInfo.userId;
var url = siteURL + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,PeopleField/ID&$filter=substringof('"+currentUserId+"',PeopleField/ID)&$expand=PeopleField/ID";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
var item=items[i];
console.log(item.Title);
}
},
error: function (data) {
}
});
});
</script>

multipart form save as attributes in backbonejs

Can any body give example to save the multipart form by using backbone js model?
How to combine the form data with file data and save to model
I am setting the model attributes and how to include the file data in the attributes. I adapted the code from one of the site to Forc Backbone to save an attribute as a file. I could not relate it to my form
<form enctype="multipart/form-data">
<input type="file" name="ImageData">
<input type="text" name="UserName">
</form>
Model
User = Backbone.Model.extend({
readAvatar : function (file, callback) {
var reader = new FileReader(); // File API object for reading a file locally
reader.onload = (function (theFile, self) {
return function (e) {
// Set the file data correctly on the Backbone model
self.set({avatar_file_name : theFile.name, avatar_data : fileEvent.target.result});
// Handle anything else you want to do after parsing the file and setting up the model.
callback();
};
})(file, this);
reader.readAsDataURL(file); // Reads file into memory Base64 encoded
}
attribute : function(attr) {
return Object.defineProperty(this.prototype, attr, {
get: function() {
return this.get(attr);
},
set: function(value) {
var attrs;
attrs = {};
attrs[attr] = value;
return this.set(attrs);
}
});
};
});
var form_data = form.serializeArray();
View
this.model.data = form_data;
var profiledata;
if (window.FormData) {
profiledata = new FormData();
console.log(profiledata);
}
if (profiledata) {
jQuery.each($('#ImageData')[0].files, function(i, file) {
//reader.readAsDataURL(file);
profiledata.append("ImageData[]", file);
});
}
this.model.ImageData = profiledata;
//and save the data
this.model.save
Rather than handling the FileReader logic in the model, I've been managing that in the view.
Check this out:
<form enctype="multipart/form-data">
<input type="file" name="ImageData">
<input type="text" name="UserName">
<button>Submit</button>
</form>
View:
var FormView = Backbone.View.extend({
events: {
"submit form" : "submit",
"change input[type=file]" : "encodeFile"
},
render: function () {
var content = this.template();
this.$el.html(content);
return this;
},
encodeFile: function (event) {
var file = event.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (fileEvent) {
this.model.set({
avatar_data: fileEvent.target.result // file name is part of the data
});
}.bind(this)
reader.onerror = function () {
console.log("error", arguments)
}
reader.readAsDataURL(file);
},
submit: function (event) {
event.preventDefault();
this.model.set({ UserName: $('input[name=UserName]').val() });
this.model.save();
}
});

Form has enctype="multipart/form-data" but Request Content-Type is application/x-www-form-urlencoded; charset=UTF-8

I have a basic form in ASP.Net MVC4 using Html helpers. I have an input file in the form for uploading a file which will be added to a database. In my view model I have a property for the input file:
public HttpPostedFileBase AssetFile { get; set; }
In my view I have the form helper:
#using (Html.BeginForm("Create", "Contact", FormMethod.Post, new { enctype = "multipart/form-data" }))
Inside my form:
#Html.TextBoxFor(model => model.AssetFile, new { #type = "file", #name = "AssetFile" })
Yet, when I post the form there are no files in the Request.Files. Then I noticed that in Fiddler the Request Header has Content-Type: application/x-www-form-urlencoded; charset=UTF-8. I have another form with an input file and the header has Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryCfBFSR0RXQRnasfb and this form works fine. I tried doing this without Html helpers and same thing happens. The view model itself inherits from another view model where the input file actually belongs but then I have a string property mapped to a textbox and the form is picking up this value. There is no nested forms (on this page this is the only form) but I am having the same problem with another page that has multiple form (not nested) using multiple partial views that contain the forms like this:
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { #enctype = "multipart/form-data" })){ #Html.Partial("EditorTemplates/_Profile", Model.InstitutionProfileInformation)}
Thanks in advance for any help.
OK - Here's the weirdness. Since they're (the original coder(s)) using partial views they ajaxified this thing. When the partial view (with the form) is rendered:
var loadContactDiv = function (e) {
isChanged = false;
var url = e.href;
$("#Contacts").load(url, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
}
$("#Contacts").find('form').submit(divSubmitHandler).change(function () {
isChanged = true;
});
$("#ReturnButton").click(function () {
loadContacts();
});
});
return false;
};
Then when the user click the submit button:
var divSubmitHandler = function () {
var form = $("#Contacts").find('form');
var test = form.serialize();
debugger;
$.ajax({
url: (form).attr('action'),
data: form.serialize(),
type: "POST",
success: function (data) {
if (data == "") {
loadContacts();
} else {
$("#Contacts").html(data);
$("#Contacts").find('form').submit(divSubmitHandler).change(function () {
isChanged = true;
});
$("#ReturnButton").click(function (e) {
loadContacts();
});
}
}
});
return false;
};
Still stuck: http://prntscr.com/20v2cp
Since you are not submitting the form, but using $.ajax to process the request remotely and then get the result, the enctype is ignored from the form itself.
As you can also see the form data is serialize and sent.
So the fix here is simple, to submit the content-type correctly, just add a
content-type
option to the ajax request like so,
var divSubmitHandler = function () {
var form = $("#Contacts").find('form');
var test = form.serialize();
debugger;
$.ajax({
url: (form).attr('action'),
**contentType: 'multipart/form-data',**
data: form.serialize(),
type: "POST",
success: function (data) {
if (data == "") {
loadContacts();
} else {
$("#Contacts").html(data);
$("#Contacts").find('form').submit(divSubmitHandler).change(function () {
isChanged = true;
});
$("#ReturnButton").click(function (e) {
loadContacts();
});
}
}
});
return false;
};
This should do the trick. However if it does not work, please refer to Jquery Form Ajax submit.
jQuery AJAX submit form
Have a nice session!

jQuery select2 genemuFormBundle issue

I am trying to implement ajax call using select2 as per this example:
https://github.com/genemu/GenemuFormBundle/blob/master/Resources/doc/jquery/select2/ajax.md
Here is my code:
var $configs = {{ configs|json_encode|raw }};
$field = $('#{{ id }}');
$configs = $.extend($configs, {
ajax: {
id: function (friend) { return friend.username; },
url: $field.data('url'),
data: function (term, page) {
return { q: term, page_limit: 10, page: page };
},
results: function (data, page) {
var more = (page * 10) < data.total;
return { results: data, more: more };
}
},
formatResult: function (friend) {
var markup = "<div class='friend-results-box'>";
if (friend.avatar !== undefined) {
markup += "<img width='60' height='75' src='" + friend.avatar + "'/>";
}
markup += "<h5>" + friend.username + "</h5>";
markup += "<div class'clearfix'></div>";
markup += "</div>";
return markup;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text'); // ?
callback({"term":elementText});
},
formatSelection: function (friend) { return friend.username; },
escapeMarkup: function (m) { return m; },
dropdownCssClass: "dropdown-friends"
});
$field.select2($configs);
Now my issues are:
Value is being filled in with ID when my intention is to have a
value taken from json defined there as friend.username
After page reload initial value is not being presented on the screen
(as value is being set to ID) and select2 does not pick it up
Any tips or help would be much appreciated!
Your initSelection function has this: callback({"term":elementText});
by default Select2 expects {id:"someid", text:"sometext"}
Best to start simple with no formatting of any kind, get that working then make it look like you want.

load one drop down on selection of other in asp.net mvc

how can i load second dropdown on selection of first and third on second. in asp.net mvc 2
I have the dropdown trigger an ajax post that sends the selected ID selected to a controller and then return a partial view which overwrites the html for a placeholder div.
View; this sets the ActionUrl, you will also need a placeholder div (in my case called departments) for the drop down to be injected:
<script type="text/javascript">
var ActionUrl = '<%= Url.Action("RenderDepartments", "ControllerName") %>';
</script>
<script src="<%: ResolveUrl("~/Scripts/Custom/DepartmentFilter.js")%>" type="text/javascript"></script>
<%: Html.DropDownListFor(model => model.OfficeId, Model.ListItems, "-- Please Select --", new { onchange = "GetDepartments()" })%>
// ^^ ON CHANGE IS IMPORTANT ^^
<div id="departments"></div>
JQuery;
function GetDepartments() {
$.ajax(
{
type: "POST",
url: ActionUrl,
data: { officeId: $("#OfficeId").val() },
success: function (data) {
$("#departments").html(data);
}, error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('XMLHttpRequest:' + XMLHttpRequest.responseText);
alert('textStatus:' + textStatus);
//alert('errorThrown:' + errorThrown);
}
});
}
Controller Action;
public ActionResult RenderDepartments(int? officeId)
{
if (officeId.HasValue)
{
var departments = new SelectList(ents.GetDepartments(officeId), "departmentID", "Name");
var model = new DropdownListViewModel(departments);
return PartialView("DepartmentDropdown", model);
}
return null;
}
This is nullable because the user could submit "-- please select --" which will in this case return null and remove the departments dropdown.