Day 4 Assignment (VFpage, JavaScript)

I have created a 5 Days Salesforce based programming and configuration assignments for practice and improving your skills. This blog have the third day assignment. Since all the blogs are related I would recommend beginners to start from Day 2 assignment and not directly jump to this blog.    

Requirement: We have a university “St Judes” which wants its salesforce account to get configured by us. Following are the requirement of this client. 

1. Create a VF page listing a quick search for all the Professors. A quick search will be a on key press VF page. If the users press “V” in the field all the professors with starting name “V” like Vineet, Vinay .. etc will list down in the page. AJAX Toolkit Developer Guide

SOLUTION: VisualForce Page


Visual force page code.

<apex:page id="page" controller="Basic2SearchProfessorsDynamically" sidebar="false">
    <apex:form id="form">
        <apex:pageMessages id="errors" />
        <apex:pageBlock title="Find Me A Professor!" mode="edit" id="block">
        <table width="100%" border="0">
                <td width="200" valign="top">
                    <apex:pageBlock title="Parameters" mode="edit" id="criteria">
                        <script type="text/javascript">
                            function doSearch() {
                        <apex:actionFunction name="searchServer" action="{!runSearch}" reRender="results,errors,debug">
                            <apex:param name="profName" value="" />
                            <apex:param name="mail" value="" />
                            <apex:param name="YOE" value="" />
                        <table cellpadding="2" cellspacing="2" id="table">
                                <td style="font-weight:bold;">Name<br />
                                    <input type="text" id="profName" onkeyup="doSearch();" />
                                <td style="font-weight:bold;">Email<br />
                                    <input type="text" id="mail" onkeyup="doSearch();" />
                                <td style="font-weight:bold;">Year Of Experience<br />
                                    <input type="text" id="YOE" onkeyup="doSearch();" />
                <td valign="top">
                    <apex:pageBlock mode="edit" id="results">
                        <apex:outputPanel id="panel" rendered="true">
                            <apex:pageBlockTable value="{!profList}" var="prof">
                                <apex:variable value="{!0}" var="cnt"/>
                                <apex:column headerValue="Action">
                                        <apex:commandButton value="Delete" style="background: red; color: white;" action="{!deleteProf}" rendered="true" reRender="panel">
                                            <apex:param value="{!prof.Id}" name="profToRemove" assignTo="{!rowToRemove}"/>
                                            <apex:param name="index" value="{!cnt}"/>
                                        <apex:variable var="cnt" value="{!cnt+1}"/>
                                    <apex:column >
                                    <apex:facet name="header">
                                        <apex:commandLink value="Professor Name" action="{!toggleSort}" reRender="results">
                                            <apex:param name="sortField" value="Name" assignTo="{!sortField}" />
                                    <apex:outputField value="{!prof.Name}" />
                                <apex:column >
                                    <apex:facet name="header">
                                        <apex:commandLink value="Professor Email" action="{!toggleSort}" reRender="results">
                                            <apex:param name="sortField" value="Email__c" assignTo="{!sortField}" />
                                    <apex:outputField value="{!prof.Email__c}" />
                                <apex:column >
                                    <apex:facet name="header">
                                        <apex:commandLink value="Year of Experience" action="{!toggleSort}" reRender="results">
                                            <apex:param name="sortField" value="Year_Of_Experience__c" assignTo="{!sortField}" />
                                    <apex:outputField value="{!prof.Year_Of_Experience__c}" />
        <apex:pageBlock title="Debug - SOQL" id="debug">
            <apex:outputText value="{!debugSoql}" />

2. The quick search will have a delete button beside each Professor row. This will delete a particular Professor. Once the Professor is deleted all the students from the Professors Course will get de-enrolled(Removed) 

SOLUTION: VisualForce Page Controller

public with sharing class Basic2SearchProfessorsDynamically {

//the soql without the order and limit private String soql {get; set;}

//the row to be delete public String rowToRemove{get; set;}

//the collection of professors to display public List<Basic2Proffessor__c> profList {get; set;}

//Required Professor(Dummy Professor) Basic2Proffessor__c reqProf = [SELECT Id, Name FROM Basic2Proffessor__c WHERE Name = ‘Professor Required’];

//the current sort direction. default is asc public String sortDir { get { if (sortDir == null) { sortDir = ‘asc’; } return sortDir; } set; }

//the current field to sort by. defaults to Name public String sortField { get { if (sortField == NULL) { sortField = ‘Name’; } return sortField; } set; }

//format the soql for display on the visualforce page public String debugSoql { get { return soql + ‘ order by ‘ + sortField + ‘ ‘ + sortDir + ‘ LIMIT 20’; } set; }

//init the controller and display some sample data when the page loads public Basic2SearchProfessorsDynamically() { soql = ‘SELECT Name, Email__c, Year_Of_Experience__c FROM’ + ‘ Basic2Proffessor__c WHERE Name != \” + reqProf.Name + ‘\”; runQuery(); }

//toggles the sorting of query from asc –> desc public void toggleSort() { //simply toggle the direction sortDir = sortDir.equals(‘asc’) ? ‘desc’ : ‘asc’; //run the query again runQuery(); }

//run the actual query public void runQuery() { try { profList = Database.query(soql + ‘ order by ‘ + sortField + ‘ ‘ + sortDir + ‘ LIMIT 20’); } catch(Exception e) { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, ‘Ooops!’)); } }

//runs the search with parameters passed via Javascript public PageReference runSearch() { String profName = ApexPages.currentPage().getParameters().get(‘profName’); String mail = ApexPages.currentPage().getParameters().get(‘mail’); String YOE = ApexPages.currentPage().getParameters().get(‘YOE’); System.debug(‘———-‘ + profName); System.debug(‘//////////////’ + mail); System.debug(‘>>>>>>>>>>>>’ + YOE); soql = ‘SELECT Name, Date_Of_Birth_DOB__c, Email__c, Expertise__c, Year_Of_Experience__c FROM’ + ‘ Basic2Proffessor__c WHERE Name != \” + reqProf.Name + ‘\”; if (!profName.equals(”)) { soql += ‘ AND Name LIKE ‘ + ‘\” + profName + ‘%\”; }

if (!mail.equals(”)) { soql += ‘ AND Email__c LIKE ‘ + ‘\” + mail + ‘%\”; }

if (!YOE.equals(”)) { soql += ‘ AND Year_Of_Experience__c = ‘ + YOE; }

//run the query again runQuery(); return NULL; }

//To Delete the the Professor public PageReference deleteProf() { Id profId = ApexPages.currentPage().getParameters().get(‘profToRemove’); System.debug(‘<<<<<<<<———‘ + profId); Basic2Proffessor__c profToBeRemoved = [SELECT Id FROM Basic2Proffessor__c WHERE Id =: profId];

try { Basic2Class__c profClass = [SELECT Name, Class_Teacher__c FROM Basic2Class__c WHERE Class_Teacher__c =: profToBeRemoved.Id]; System.debug(‘———-‘ + profClass); if (profClass != NULL) { profClass.Class_Teacher__c = reqProf.Id; List<Basic2Class__c> updateClass = new List<Basic2Class__c>(); updateClass.add(profClass); System.debug(‘———->>>’ + profClass); update updateClass; } } catch (Exception e) { System.debug(e); } List<Basic2Course__c> course = [SELECT Id FROM Basic2Course__c WHERE Basic2Proffessor__c =: profId]; List<Basic2CorseStudenetJunction__c> junction = [SELECT Id, Name FROM Basic2CorseStudenetJunction__c WHERE Basic2Course__c IN: course]; System.debug(‘>>>>>>>>>>>>>>’ + profToBeRemoved); System.debug(‘>>>>>>>>>>>>>>’ + course); System.debug(‘>>>>>>>>>>>>>>’ + junction);

Integer indexVal = Integer.valueof(system.currentpagereference().getparameters().get(‘index’)); profList.remove(indexVal – 1);

delete profToBeRemoved; delete junction; return NULL; }


3. Make sure the various student’s Passport size photo can be uploaded into salesforce and will be visible on every student details page. Places where custom Student list is shown should also have each students image on the list.

SOLUTION: VisualForce Page and Controller


<apex:page id=”page” controller=”Advance1SetProfilePic” sidebar=”false” showHeader=”false”> <script>

function ValidateRadio() { var selectedRadio = document.getElementById(‘page:form:block:section:sectionItem:radio’); var selectedInput = selectedRadio.getElementsByTagName(‘input’); var flag = false; for (var i = 0; i < selectedInput.length; i++) { if (selectedInput[i].checked == true) { flag = true; break; } } if (!flag) { alert(‘Please Select one Picture’); return false; } else { Validate(); } }

function AlertAndClose() { alert(“Profile Pic is Applied”);; }

</script> <apex:form id=”form”> <apex:actionFunction name=”Validate” action=”{!SaveImage}” onComplete=”AlertAndClose();” reRender=”” />

<apex:pageBlock id=”block” title=”Select Image”>

<apex:pageBlockButtons > <apex:commandButton rendered=”{!IF(Items.size > 0, true, false)}” value=”Save” onclick=”return ValidateRadio();” /> <apex:commandButton value=”Cancel” onClick=”window.close();” /> </apex:pageBlockButtons>

<apex:pageBlockSection id=”section” title=”All Images” rendered=”{!IF(Items.size > 0, true, false)}”> <apex:pageBlockSectionItem id=”sectionItem”> <apex:selectRadio id=”radio” value=”{!selectedImage}”> <apex:selectOptions id=”radioOption” value=”{!Items}” /> </apex:selectRadio> </apex:pageBlockSectionItem> </apex:pageBlockSection>

<apex:pageBlockSection rendered=”{!IF(Items.size > 0, false, true)}” > <apex:outputLabel value=”No attachments to display or there is no valid image in attachments.” /> </apex:pageBlockSection>

</apex:pageBlock> </apex:form> </apex:page>

4. Create a Custom Java script button “Course Same Time” on Course Object which will find other Courses with same number of days (Endate-StartDate)duration in a Pop-up. Call an Apex Class Method Using a Button

SOLUTION: VisualForce Page and Controller

Same Course Details Search Button

Same Course Details Search Button


public with sharing class Advance1ShowCourseSameTime {

private String courseId;

public Id getCourseId() {

return ApexPages.CurrentPage().getParameters().get(‘Id’);


public Advance1ShowCourseSameTime() {

courseId = ApexPages.CurrentPage().getParameters().get(‘Id’); }

public List<Basic2Course__c> getCourses() { Basic2Course__c currentCourse = [SELECT Id, Name, Start_Date__c, End_Date__c FROM Basic2Course__c WHERE Id =: courseId]; Integer dateDifference = currentCourse.End_Date__c.month() – currentCourse.Start_Date__c.month(); List<Basic2Course__c> courseList = [SELECT Id, Name, Basic2Class__c, Total_Attendance_Required__c, Number_Of_Students_Registered__c, Basic2Proffessor__c, Basic2University__c, Course_Time__c, Start_Date__c, End_Date__c FROM Basic2Course__c WHERE Start_Date__c != NULL AND End_Date__c != NULL];

List<Basic2Course__c> courseSameTime = new List<Basic2Course__c>();

for (Basic2Course__c course : courseList) { if (course.End_Date__c.month() – course.Start_Date__c.month() == dateDifference) { courseSameTime.add(course); } } return courseSameTime; } }


<apex:page id=”page” controller=”Advance1ShowCourseSameTime” sidebar=”false” showHeader=”false”> <apex:form id=”form”> <apex:pageBlock id=”block” title=”Courses Same Time”> <apex:variable value=”{!CourseId}” var=”courseId” /> <apex:pageBlockTable id=”table” rendered=”{!IF(Courses.size > 0 , true, false)}” value=”{!Courses}” var=”course”> <apex:column headerValue=”Course Name” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.Name}”/> <apex:column headerValue=”Class Name” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.Basic2Class__c}” /> <apex:column headerValue=”Professor Name” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.Basic2Proffessor__c}” /> <apex:column headerValue=”University Name” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.Basic2University__c}” /> <apex:column headerValue=”Start Date” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.Start_Date__c}” /> <apex:column headerValue=”End Date” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.End_Date__c}” /> <apex:column headerValue=”Course Time (In Days)” style=”{!IF(course.Id == courseId, ‘font-weight: bolder;’, ”)}” value=”{!course.Course_Time__c}” /> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>

Important links to Learn:-

Using ActionFunction vs. RemoteAction


Author: AJ

Share This Post On

Submit a Comment

Your email address will not be published.

× How can I help you?