Category Archives: Knockoutjs

Sortable, searchable table with pagination using knockout.js in Salesforce

This is a demo using knockout.js to create a table for listing records of any object custom, standard or combinations of data from multiple objects.  The table is sortable and searchable using a typeahead search field.  It also includes a dropdown to limit the number of records visible as well as pagination.

This is what it looks like in its most basic styling:

This is the link to the working demo

 

This is the component that holds the knockout code:

This is the controller to retrieve the records using a remote action:

The visualforce page:

 

Readonly attribute in knockoutjs

HTML:

<input data-bind="value: text, readOnly: locked"  ></input> 

In knockout:

  ko.bindingHandlers.readOnly = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        if (value) {
            element.setAttribute("readOnly", true); 
        }  else {
            element.removeAttribute("readOnly");
        }  
    }  
}
 
var viewModel = {
   
    locked = ko.observable(false)
};

Tab out of knockout datepicker

Need to add this to the data-bind parameters:

onClose: function(dateText) {
$(this).focus();
}

example:

<input style="float:left;" placeholder="Date of Birth" id="studentDOB" class="textAnswer datepickerDOB" type="text" 
    data-bind="datepicker: {
            onClose: function(dateText){$(this).focus();},
            changeMonth:true,
            changeYear:true,
            yearRange: '-25:c'},
    value : studentDOB, valueUpdate: 'input'" />               		

Get and pass date from Controller and pass to knockout

Javascript remote on site:

Visualforce.remoting.Manager.invokeAction(
  	'{!$RemoteAction.ApplicationController.getStudentInfo}',    
  	    function(student){                        	                        	                       	                                                                              		
    		Application.studentLastName(student.LastName); 
    		Application.studentFirstName(student.FirstName);
    		Application.studentPhone(student.Phone);
    		Application.studentAltPhone(student.OtherPhone);
    		Application.studentEmail(student.Email);   		
    		Application.studentHomeAddress(student.MailingStreet);			    		
    		Application.studentCity(student.MailingCity);			    		
    		Application.studentZip(student.MailingPostalCode);
    		Application.studentCountry(student.MailingCountry);
    		if(student.Birthdate != null){
    			var dob = normalizeDate(student.Birthdate);
	    		var dobAlt = normalizeDate2(student.Birthdate);
	    		Application.studentDOB(dob);
	    		document.getElementById('studentDOB_alternate').value = dobAlt;
	    }
  	},{escape : false});

Script to convert date from controller to mm-dd-yyyy

function normalizeDate(dateVal){ 
	mydate = new Date(dateVal);
    data = new Date(mydate -  mydate.getTimezoneOffset() * 60000);
    var d = mydate.getDate()+1;
    var m = mydate.getMonth()+1;
    var y = mydate.getFullYear();
    return (m<=9?'0'+m:m) +'-' + (d<=9?'0'+d:d)+'-' + y;		
}

Script to convert date from controller to yyy-mm-dd to send back to controller

function normalizeDate2(dateVal){ 
	mydate = new Date(dateVal);
    data = new Date(mydate -  mydate.getTimezoneOffset() * 60000);
    var d = mydate.getDate()+1;
    var m = mydate.getMonth()+1;
    var y = mydate.getFullYear();		    
    return y + '-' + (m<=9?'0'+m:m) +'-' + (d<=9?'0'+d:d);		
}

Knockout send to controller

self.goToParentSection = function(){
    			if (studentInfoValidation().length === 0) {		
					var parentIsEdit = self.parentIsEdit();
					var studentDetails = {
						representativeId : self.representativeId(),						
						applicationId : self.applicationId(),										
						studentFirstName : self.studentFirstName(),
						studentLastName : self.studentLastName(),
						studentDOB : (j$('#studentDOB_alternate').val()),
						studentPhone : self.studentPhone(),
						studentOtherPhone : self.studentAltPhone(),
						studentEmail : self.studentEmail(),
						studentCountry : self.studentCountry(),
						studentHomeAddress : self.studentHomeAddress(),
						studentCity : self.studentCity(),
						studentState : self.studentState(),
						studentZip : self.studentZip(),
						studentId : self.studentId(),
						studentInfoComplete : self.studentDetailsComplete(),
						householdId : self.householdId()																																	
					}
					Visualforce.remoting.Manager.invokeAction(
	                	'{!$RemoteAction.ApplicationController2.studentInfo}',studentDetails,   
	                        function(results){                        	
	                        	self.studentId(results.Id);	                            				                
	                        },{escape : false});
																
				}
				else {
		            alert('Please check your submission.');
		            studentInfoValidation.showAllMessages();
		        }		        					
			}			

Controller

@RemoteAction
    public static object studentInfo(Map<string, string> studentDetails){
		Date dt = Date.valueOf(studentDetails.get('studentDOB'));  
        studentId = studentDetails.get('studentId');
		Contact studentToUpdate = [SELECT id,AccountId, Name FROM Contact WHERE Id =: studentId];
		string contactRecordTypeId;    		
		RecordType rt = [select Id, Name from RecordType where DeveloperName = 'Student_Master' and SobjectType = 'Contact' limit 1];
		contactRecordTypeId = rt.Id;
		studentToUpdate.RecordTypeId = contactRecordTypeId;
		studentToUpdate.LastName = studentDetails.get('studentLastName');
		studentToUpdate.FirstName = studentDetails.get('studentFirstName');
		studentToUpdate.Phone = studentDetails.get('studentPhone');
		studentToUpdate.OtherPhone = studentDetails.get('studentOtherPhone');
		studentToUpdate.Email = studentDetails.get('studentEmail');   		
		studentToUpdate.MailingStreet = studentDetails.get('studentHomeAddress');  		
		studentToUpdate.MailingCity = studentDetails.get('studentCity');
		studentToUpdate.MailingState = studentDetails.get('studentState');
		studentToUpdate.MailingPostalCode = studentDetails.get('studentZip');
		studentToUpdate.MailingCountry = studentDetails.get('studentCountry');    		
		studentToUpdate.BirthDate = dt;    			
		
		update studentToUpdate;

		return studentToUpdate;    
	}

Visualforce page with datepicker