sharepoint list item click event and value change - sharepoint

So my goal is to allow the user to click the item on the list and it automatically changes a value on the item. Mostly I want a easy to allow the user to mark the item as being read. This list will be updated every week, so it will allow the user to know what is new easier. I have already set up the views so the users can only see their own data on the personal view.
I have looked online and I'm not having great luck. This is what I have so far.
<script src="https://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script><script type="text/javascript">
$(document).ready(function() {
$(".ms-listviewtable > tbody > tr").click(function(){ //only works before ajax runs
setTimeout( function() {
//alert("Hello! I am an alert box!!");
var ctx = SP.ClientContext.get_current("https://...");
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getByTitle('Ticket');
this.oListItem = oList.getItemById(items[0].id);
this.oListItem.set_item('read','yes');
this.oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}, 200); //had to be put in place to give time for the list to be selected
});
});
These are the issues I have.
the first time I click a item it tells be SP.ListOperation.Selection.getSelectedItems is null. However if I click the same item it will give me the ID number. Then if I click it a third time it will tell me its null again.
It does not change the vaule, but it does give me the right ID number after I click it two times.
EDIT,
see comments below

Using this code:
$("table.ms-listviewtable").on("mouseup", "tr.ms-itmhover", function() {
//your code
});

Related

Changing the title of the header

I use the SAPUI5 Framework.
Within a page there are two possibilities for action, to make a new patient and to edit a patient. The new and edit, control/view pages are compiled into one, one control and one view for both new and edit.
Since they both are within one-page control/view, whenever I try to make a new patient or to edit a patient I get the same title for both of these Options.
My approach.
Get the URL of the page -> New or Edit. -> Split till I get, if it's new or edit.
If its new, change the title to New if edit that the title to Edit.
var completurl = window.location.href;
var split = completurl.split("/");
if(split[7] == 'new'){
this.byId("semantic:DetailPageID").setTitle("New");
}
else {
this.byId("semantic:DetailPageID").setTitle("Edit");
}
Expected: To change the title of the header.
Actuality: Doesn't do shit
First you need the different buttons in your main.view.xml.
main.view.xml:
<Button press="onPressNew" text="New"/>
<Button press="onPressEdit" text="Edit"/>
Now you could use a local model for saving the action
editNew.controller.js:
onPressEdit: function () {
this.myLocalModel.setProperty("/Action", "Edit");
//Navigate to editNew.view.xml
},
onPressNew: function () {
this.myLocalModel.setProperty("/Action", "New");
//Navigate to editNew.view.xml
}
In your editNew.view.xml, you could use expression binding
editNew.view.xml:
<Page id="pageEditNew" title="{= ${localModel>/Action} === 'Edit' ? ${i18n>title_edit} : ${i18n>title_new}}">

Populating a dropdown based on selection in another dropdown in ASP.NET MVC 5

hoping someone can point out where I am going wrong. I am working on an MVC 5 ASP.NET application. In my View I have a form which, amongst other controls, has 2 dropdown boxes.The first dropdown is populated with values in the Viewbag, but I want to populate the second dropdown based on the value selected in the first dropdown. I've read lots of other posts but still can't work it out.
Here is the code for the dropdowns.
#Html.DropDownList("EquipmentPortList", new SelectList(ViewBag.EquipmentPortList, "hvid", "hvnamn"), "--Select Equipment--")
#Html.DropDownList("PortConnectedList", Enumerable.Empty<SelectListItem>(), "--Select Port--")
Here is the change event code for the first dropdown :-
$(document).on('change', '#EquipmentPortList', function () {
var url = '#Url.Action("GetPortInt", "bearers")';
var ports = $('#PortConnectedList');
var id = $(this).val();
$.getJSON(url, { portid: id }, function (response) {
ports.empty();
$.each(response, function (index, item) {
ports.append($('</option>').text(item.portnamn).val(item.portid));
});
});
});
Here is the method in the controller :-
public ActionResult GetPortInt(int portid)
{
var PortConnectedList = from h in nadb.hvportar
where h.porthvid == portid && (h.portnamn.Contains("NT") || (h.portnamn.Contains("Port")) || (h.portnamn.Contains("/")))
orderby h.portid
select new { h.portid, h.portnamn };
return Json(PortConnectedList, JsonRequestBehavior.AllowGet);
}
OK, so the first dropdown populates correctly, and when I select a value I can see (using alerts) that the change event fires and the value is correctly selected.
I can see with the use of a breakpoint that the method is triggered and returns the correct data from the database, but after that I don't know what is wrong as the dropdown does not populate.
I picked up the code change event code from another post and amended it to fit my own project but I can't see what I'm missing. Thanks.
Stephen, your DotnetFiddle link actually showed me the answer. This line :-
ports.append($('</option>').text(item.portnamn).val(item.por‌​‌​tid));
Should read
ports.append($('<option></option>').text(item.portnamn).val(‌​‌​item.portid));
Once I changed that it worked. Many thanks.

MS Dynamics CRM 2011, Get subgrid elements from other form

I am new to jscript and have problems to get all elements in a subgrid.
I tried the code from this sites,
Retrieve rows in crm2011 subgrid with JScript
https://lakshmanindian.wordpress.com/2012/05/25/retrieve-subgrid-rows-in-crm-2011-using-jscript/
but get every time the error message:
(Translated)
Error in the user defined event of the field
Field:window
Event: onload
Error: The preference "control" of a undefined or null reference can not be called.
The last code I tried:
var grid = document.getElementById("accountContactsGrid").control;
for (var rowNo = 0; rowNo<grid.getRecordsFromInnerGrid().length; rowNo++)
for (var cellNo = 0; cellNo<grid.getRecordsFromInnerGrid()[rowNo][3].cells.length; cellNo++)
alert(grid.getRecordsFromInnerGrid()[rowNo][3].cells[cellNo].outerText);
I tried it in the entity Account(Company) with the subgrid "accountContactsGrid".
My main goal would be to catch all the assigned elements in the account form and list it under the contacts form. But only if the checkbox "Eko" is activated.
This is my working code so far:
var chkEko = Xrm.Page.getAttribute("testcrm_ekonomi").getValue();
if (chkEko === true)
{
alert("Eko active: " + chkEko);
}
else
{
alert("Eko not active: " + chkEko);
}
After a time and the help of some threads I was able to get information of this grid. But now I have the problem to catch the elements.
I looked up the variable "grid" and found out that variable is an Object.
Since I don't really know the properties of the objects I tried to get it all.
But it seems, that my code doesn't work and I can not understand why.
Here is the code so far:
function subgridItemCount() {
// Get the Subgrid Control
var grid = Xrm.Page.ui.controls.get('accountContactsGrid')._control;
var keys = Object.keys(grid);
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
for(var i = 0; i<keys.length; i++) {
document.write(keys[i]);
}
}
First I wanted to get the property of the object and then the propertyValue.
Or is there an other way to get all values of an object?
It seems like I am on the wrong way. This is what I try to do:
In the account/company form is an existing grid which is called Contacts. In this field are some Contacts assigned (with the button "add existing contact").
Now when I open some Contact there should be a box/grid/iframe with a list of all companies this contact is assigned too.
This list should be linked to the Companies (When i click on them CRM should open the form).
Maybe someone can give me a tip?
My plan was first to look for all companies and then to compare the assigned contacts to the opened one with some Jscript. Then the script should list all matching contacts in the contact form.
This way is not really performant since the script needs to read all companies first. But I don't know an other way...

Why my YUI 2 server side pagination, Datasouce is not called on every click of pagination link

My code looks like below. I am feching the json records from the server side using structs action. it is returning the records fine and i could able to see the table with data. pagination links created fine. when i click next and datasource is called on each click of any link on the pagination. if i click on colum header also, the datasource is being called.
my questions are:
1)When datasource is being called. because i am seeing sometime called and some times not. like when i got from 1page to 2page, datasource is called fine. when i go back to previous pages by clicking 'prev' link, datasource is being called. but after that if i click again on next to go to 2nd page, datasource is not being called. when exactly datasource is called and how many times it will called. is it for every link in the pagination calls datasource?
2)If my datasource returns 100 recods of data and my records per page is set to 25, then do i see the 4 pages. I am confused here with server side pagination and datasource calls.
datasource is not called for each page link and next or prev link clicks? if not, when datasource is called? please explain me. I know how many total records are there in the begining and my requirement is showing 25 records per page when ever user clicks on page number or next or prev links. i have the capability to bring corresponding 25 records based on the page number from server side.
3)how to capture the 'next' and 'prev' clicks on the pagination.
my requirement is to dynamically fetch the json data using datasource from the server whenever user click on page number links or next or prev.
Please help me out with this. I am new to YUI. I have to User YUI 2 only since we are already using it.
<div id="dynamicdata"></div>
<script type="text/javascript">
YAHOO.example.DynamicData = function() {
var myColumnDefs = [ // sortable:true enables sorting
{key:"PIN", label:"PIN", sortable:true},
{key:"CODE", label:"CODE", sortable:true}
];
// Customize request sent to server to be able to set total # of records
var generateRequest = function(oState, oSelf) {
// Get states or use defaults
oState = oState || { pagination: null, sortedBy: null };
var sort = (oState.sortedBy) ? oState.sortedBy.key : "PIN";
var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
var results = (oState.pagination) ? oState.pagination.rowsPerPage : 25;
var total = YAHOO.util.Dom.get("total").value *1;
// Validate input
if(!YAHOO.lang.isNumber(total) || total < 0 || total > 200) {
YAHOO.util.Dom.get("total").value = 0;
total = 0;
alert("Total must be between 0 and 200.");
}
// Build custom request
return "sort=" + sort +
"&dir=" + dir +
"&startIndex=" + startIndex +
"&results=" + (startIndex + results) +
"&total=" + total;
};
// DataTable configuration
var myConfigs = {
generateRequest: generateRequest,
initialRequest: generateRequest(), // Initial request for first page of data
dynamicData: true, // Enables dynamic server-driven data
sortedBy : {key:"PIN", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
paginator: new YAHOO.widget.Paginator({ rowsPerPage:10 }) // Enables pagination
};
var myDataSource = new YAHOO.util.DataSource("<%=request.getContextPath()%>/results.do?startIndex="+localStartIndex+"&rowsPerPage="+rowsPerPage);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {
resultsList: "data",
fields: [
{key:"SSN"},
{key:"PIN"}
]
}
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", myColumnDefs, myDataSource, myConfigs);
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", myColumnDefs, myDataSource, myConfigs);
// Update totalRecords on the fly with values from server
myDataTable.doBeforeLoadData = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = 200;
return oPayload;
};
return {
ds: myDataSource,
dt: myDataTable
};
}();
As far as I remember, the DataTable will always ask for fresh data whenever it changes pages or sorts by a different column. It doesn't cache previous requests nor does it keep track what it has asked. If you don't see requests arriving on the server side it might be because of caching, but not in DataTable or DataSource but by the browser itself, which is a matter of issuing the proper headers on the server to tell the browser not to cache.
If I am not mistaken, that this is supported by the behavior you describe. The first page is requested twice, once when you first draw the table, once again when you return from page 2. All other pages are never requested twice. Why? Because the first time around the URL formed is slighty different from the URL when you return to it. The browser cache only knows about URLs.

Sharepoint List redirect with new id

I have a list within Sharepoint, using a custom new form I have added a custom list form control ("New item form" for the list) and changed the SaveButton to a standard input HTML button, and added an 'onclick' event that is as follows:
onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={NewFormWizard2.aspx?id=}')}"
This works as in saves the data and redirects to the NewFormWizard2.aspx?id= page.
How do I get the ID of the created item to be passed to the redirected page?
Thus once the form is completed it would redirect to NewFormWizard2.aspx?id=23
jtherkel was close, but was missing a '}' on the end of the redirect url. I used an extra concat below
<input type="button" value="Submit" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={lists/MyListName/DispForm.aspx?ID=',/dsQueryResponse/Rows/Row/#ID,'}'))}" />
I am not sure where the ID will exist on the page you host the Javascript from. Does it appear in the querystring or on a field on the page?
There is nothing in the request or response that will identify the item. I have had this issue when doing some web loadtesting.
I can only suggest that your create the item using the webservices as that at gives you some return xml.
This answer does not solve the "new form" issue, but it might help others with the syntax for screens that contain existing list items.
I tested this quickly in my SharePoint (MOSS 2007) environment.
onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={NewFormWizard2.aspx?id=',/dsQueryResponse/Rows/Row/#ID))}"
The concat syntax is an XSLT instruction that tells the processor to combine the values enclosed in single quotes. I adapted this answer from info I found here.
Loading Values in a Custom List Form
http://wssdevelopment.blogspot.com/2007_04_01_archive.html
I hope this would be helpfull:
1- In SharePoint Designer create new page, call it for example "LastItem.aspx" and place a dataview on it with a single form view for the destination list item.
2-Limit paging to just one record, set the sorting by ID and descending and filter the list to just show item which is created by [current user].
3-Now you do not need to pass any query string to this page. just replace the default "OK" button in NewForm.aspx of the list with a standard HTML input button and add this to its definition "onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={LastItem.aspx}". After submitting a new item to list you will be redirected to an edit view of the created item.
You can do the same for save button in LastItem.aspx to redirect to some other page after clicking on save button.
found an approach using pure javascript (JQuery) and the SPAPI code from http://darrenjohnstone.net/.
The list contains two fields, title and BodyCopy
I've thewn created a form that asks for a title and a question, both text fields, then the submit button calls the following function: (note that ServerAddress and LIST_question need to be updated to your own details).
The function then uploads the details using the SOAP service within LISTS.ASMX and using the response gets the ID of the new item and redirects the page.
var LIST_question = '{xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}';
var ServerAddress = 'http://xxx/';
function submitQuestion()
{
var title = new String($("#title").val());
var t = new String($("#question").val());
t=t.trim();
if(t=="")
return;
title=title.trim();
if(title=="")
return;
var lists = new SPAPI_Lists(ServerAddress) ;
//
var newItem = { Title : title, BodyCopy : t};
var items = lists.quickAddListItem(LIST_question, newItem);
var id=-1;
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row');
if(rows.length ==1)
{
var r = rows[0];
var id = r.getAttribute('ows_ID');
window.location.href='DispForm.aspx?ID='+id;
}
else
{
alert("Error: No row added");
}
}
else
{
alert('There was an error: ' + items.statusText);
return;
}
}
You can achieve this using JavaScript http://www.sharepointdrive.com/blog/Lists/Posts/Post.aspx?ID=9

Resources