The code below is a controller for a Visualforce page (form). The controller determines if the form was previously created and saved or saved in progress in a previous action. If the form is new it will query a table that contains all the question for the form (the questions can be altered, changed inserted ETC from the record view level). Thus it's dynamic. If the form has previously been created then it instead finds the previously saved questions and the form loads with responses saved from the prior action.

I would like as much honest feedback as possible, since I have not had much feedback in terms of code quality, only in end results. If you guys want more code or a particular type (trigger, Visualforce etc), I can also post it.

   @Author Daniel Haro
   @name QARiskAssessmentController
   @CreateDate 07/22/2017  
   @Description: Loads form questions retrieved from Related question bank if a new form otherwise loads previous save data from questions object with previously saved progress or saved answers.
   @Version <1.0>

    public class QARiskAssesmentControllerv2 {
        public String combinedScore{get;set;}
        public String Title{get;set;}
        public list<Risk_Question__c> formQuestions {get;set;}
        public list<Risk_Question__c> questions = new list <Risk_Question__c>();
        public String riskScore{get;Set;}
        public String metaScore{get;Set;}
        public String TotalRevenue{get;Set;}
        public string ServiceGroups{get;Set;}
        public String PricingStructure{get;Set;}
        public Boolean HideGuid{get;Set;}
        private map <String,Decimal> impactLevelMap =new Map<String,Decimal>();
        private map <String,Boolean> impactLevelcommentRequiredMap = new map<String,Boolean>();
        public Boolean RiskLevelError{get;set;}
        public Boolean CommentError{get;set;} 
        public QA_Risk_Assessment__c qaRisk {get;set;}
        public boolean hideStar{get;set;}
        public User currUser {get;set;}
        public ApexPages.StandardController Globalcontroller; //{get;set;}  //was standard set controller
        private ApexPages.standardController m_sc = null;
        private  QA_Plan_Review__c qaRvw;
        private pageReference returnToPlan;
        private String QAPlanReviewId;
        private id QARiskFormID;
        private QA_Risk_Assessment__c qra = new QA_Risk_Assessment__c(); 
        private  String baseId;
        private  list<QA_Master_Plan__c> relatedMaster = new list<QA_Master_Plan__C>();
        private  list<QA_Plan__c> relatedPlan = new list<QA_Plan__C>();
        private String returnHome;
        public String risktier{get;set;}

        public QARiskAssesmentControllerv2 (ApexPages.StandardController controller){  //was standard set controller
            list<String> addfieldList = new list<String>();
            formQuestions = new list<Risk_Question__c>();
            HideGuid = true;
            RiskLevelError = false;
            commentError = false;
            Globalcontroller = controller;
            baseId = (String) controller.getRecord().get('QA_Plan_Review__c');
            QAPlanReviewId = (String) baseId;

            if(String.isblank(QAPlanReviewId) && ApexPages.currentPage().getParameters().get('parentid') != null)
                QAPlanReviewId = (id) ApexPages.currentPage().getParameters().get('parentid');

            if(String.isblank(QAPlanReviewId) && ApexPages.currentPage().getParameters().get('QA_Plan_Review__c') != null)
                QAPlanReviewId = (id) ApexPages.currentPage().getParameters().get('QA_Plan_Review__c');


            if(qaRisk == null || qaRisk.Status__c != 'Completed' ){
                riskScore = 'Not yet calculated';
                metaScore = 'Not yet calculated';
                combinedScore = 'Not yet calculated';
                risktier = 'Not yet calculated';


        private void DebugInfo(String showDebugInfo){

            if(showDebugInfo == 'relatedRecords' ){
                System.debug('Review is set to :' + qaRvw);
                System.debug('Qa Plan is set to :' + relatedPlan[0] );
                System.debug('Qa Master Plan is set to :' + relatedMaster[0]);

            if(showDebugInfo == 'pointers'){
              System.debug('This pages Parameters are :' + ApexPages.currentPage().getParameters());
              system.debug('qa review id is ' +QAPlanReviewId);
              System.debug('base id is set to :  ' + baseID);


        private void loadRelatedrecords(){

            if(!String.isblank(QAPlanReviewId) && QAPlanReviewId != null)
               qaRvw = [select Name, QA_Plan__r.Name, QA_Plan__r.Opportunity_ID__c,QA_Plan__c,QA_Plan_Review__c,QA_Master_Plan__c,
                         from  QA_Plan_Review__c where id =: QAPlanReviewId]; 

            if(!String.IsBlank(qaRvw.QA_Master_Plan__c))  {
               relatedMaster = [select id,name,Total_Revenues__c,Total_Deal_Potential__c,Total_Deal_Potential2__c,Service_Plan__c,Pricing_Structure__c
                                 from QA_Master_Plan__c where id =: qaRvw.QA_Master_Plan__c];
                system.debug('related master results ' + relatedMaster);
                returnHome = relatedMaster[0].id;
                relatedPlan = [select id,Total_Current_Revenue_2__c,Total_Deal_Potential__c,Service_Plan__c,Pricing_Structure__c
                               from QA_Plan__c where id =: qaRvw.QA_Plan__c ];

                returnHome = relatedPlan[0].id;

        public void setDefaultValues(){

            if(String.isBlank(riskScore) )
                riskScore = 'Not yet calculated';
            if(QARisk != null && !String.isBlank(qaRisk.Last_Know_Risk_Score__c))
                riskScore = qaRisk.Last_Know_Risk_Score__c;
            if(String.isBlank(risktier) )
                risktier = 'Not yet calculated';
            if(QARisk != null && !String.isBlank(qarisk.Last_Known_risk_tier__c))
                risktier =qarisk.Last_Known_risk_tier__c;
            if(QARisk != null && !String.isBlank(QARisk.Last_known_meta_Score__c))
                metaScore = QARisk.Last_known_meta_Score__c;
                metaScore = 'Not yet Calculated';
              combinedScore = 'Not yet calculated';
            if(QARisk != null && !String.isBlank(qaRisk.Last_known_combined_score__c))
              combinedScore = QARisk.Last_known_combined_score__c;

        public PageReference Cancel(){
            return (new pageReference('/'  + returnHome));

        private void setFinancialData(){
            if(relatedMaster != null && !relatedMaster.isEmpty()){
                TotalRevenue = String.valueOf(relatedMaster[0].Total_Revenues__c);
                ServiceGroups = relatedMaster[0].Service_Plan__c;
                PricingStructure = relatedMaster[0].Pricing_Structure__c;

            if(relatedPlan != null && !relatedPlan.isEmpty()){

                TotalRevenue = String.valueOf(relatedPlan[0].Total_Current_Revenue_2__c);
                ServiceGroups = relatedPlan[0].Service_Plan__c;
                PricingStructure = relatedPlan[0].Pricing_Structure__c;
        private void calculateRisk(String pricing){
                Risk_Calculator riskcalculator;
                riskcalculator = new Risk_Calculator(formQuestions,pricing);
                riskScore = String.valueOf(riskcalculator.getRiskScore().setScale(2));
                combinedScore = String.valueOF(riskcalculator.getCombinedRiskScroe().setScale(2));
                risktier = riskcalculator.getRiskTeir();
                QARisk.Last_Known_risk_tier__c = risktier;
                QARisk.Last_Know_Risk_Score__c = riskScore;
                metaScore = String.valueOf(riskcalculator.getMetaScore().setScale(2));
                QARisk.Last_known_meta_Score__c = metaScore;
                QARisk.Last_known_combined_score__c = combinedScore;

        public PageReference save(){
            String pricing;
            list<QA_Master_plan__C> master = new list <QA_master_plan__c>();
            list<QA_Plan__c> plan = new list<QA_Plan__c>();

            if(QARiskFormID == null)

            //Get qa_Master or QA_Plan
            if(qaRvw.QA_Master_Plan__c != null){
                master = [select id,name,Pricing_Structure__c 
                          from QA_Master_Plan__c where id =: qaRvw.QA_Master_Plan__c];
                pricing = master[0].Pricing_Structure__c;
                plan = [select id,name,Pricing_Structure__c
                        from QA_Plan__c where id =: qaRvw.QA_Plan__c];
                pricing = plan[0].Pricing_Structure__c;
       if(riskLevelError == false && CommentError == false){
                if(QARiskFormID != null)
                qaRvw.Risk_Assessement_Status__c = 'Completed';
                qaRvw.opp_risk_status__c = 'Completed';
                qaRisk.Status__c = 'Completed';
                        return (new pageReference('/' + returnHome));

            return null;

        public PageReference saveProgress(){

            if(QARiskFormID == null){

            if(QARiskFormID != null){

            if(QARVW.Plan_Type_at_Review__c == 'Delivery'){
               qaRvw.Risk_Assessement_Status__c = 'Drafted';
                qaRvw.opp_risk_status__c = 'Drafted'; }

               qaRvw.opp_risk_status__c = 'Drafted';
               qaRvw.Risk_Assessement_Status__c = 'Drafted';

            update(qaRvw); //null pointer error
            return (new pageReference('/' +returnHome));

        public void loadData(){
            //reterive QA RiskAssemeent form
            list<RiskQuestionComparable> orderList = new list<RiskQuestionComparable>();
            list<QA_Risk_Assessment__c> assesmentList = new list <QA_Risk_Assessment__c>();        
            list<QA_Risk_Assessment__c> assesmentListInsert = new list <QA_Risk_Assessment__c>();        
            assesmentList = [select id,Last_Know_Risk_Score__c,Last_known_meta_Score__c,Last_Known_risk_tier__c,
                             from QA_Risk_Assessment__c where QA_Plan_Review__c =: QAPlanReviewId ];

            if(assesmentList != null && !assesmentList.isEmpty()){
                QARiskFormID = assesmentList[0].id;
                QARisk = assesmentList[0];
            //Set title of form
            Title = 'Opportunity Risk Assesment';
            if(QARVW.Plan_Type_at_Review__c == 'Delivery')
                Title = 'Delivery Risk Assesment';        
            //if this is a new a form then get a fresh batch of question and create new set and junction records for future support 
            if(QARiskFormID == null){ 
                Question_Bank__c demo1 = new Question_Bank__c();
                if(QARVW.Plan_Type_at_Review__c == 'Delivery'){
                    demo1 = [select id
                             from Question_Bank__c where Bank_Title__c =: 'Delivery QA Risk Assessment'];
                    Title = 'Delivery Risk Assesment';
                if(QARVW.Plan_Type_at_Review__c == 'Opportunity') {
                    demo1 = [select id
                             from Question_Bank__c where Bank_Title__c =: 'Opportunity QA Risk Assessment'];
                    Title = 'Opportunity Risk Assesment';

                questions = [select id,Base_Question__c,Guidance_Above__c,Guidance_High__c,Guidance_Normal__c,name,Active__c,Order_number__c,weight__c,Title__c,Category__c,
                             from Risk_Question__c where Question_Bank__c =: demo1.id AND ACTIVE__C =: true];

            //if this is an existing form with question already exist load reterive existing questions / answers 
            if(QARiskFormID != null){ //will update logic later
                System.debug('loading old questions!');
                list<Question_Bank_Form_Junction__c> junctionList = new list<Question_Bank_Form_Junction__c>();
                list<id> QuestionIDList = new list<id>();

                junctionList = [select id,Risk_Question__c 
                                from Question_Bank_Form_Junction__c where QA_Risk_Assessment__c =: QARiskFormID]; // will update to formID

                for(Question_Bank_Form_Junction__c junction :junctionList )
                formQuestions= [select id,Base_Question__c,Guidance_Above__c,Guidance_High__c,Guidance_Normal__c,Name,Level_of_Risk__c,Order_number__c,Category__c,weight__c,
                                from Risk_Question__c where id in: QuestionIDList]; //will update to formID
                for(Risk_Question__c riskQuestion : formQuestions)
                    orderList.add(new RiskQuestionComparable(riskQuestion,riskQuestion.Order_number__c));
                for(RiskQuestionComparable riskQuestion : orderList)

        private void loadMaps(){

            list<Risk_Assessment_Controls__c> racm = Risk_Assessment_Controls__c.getall().Values();
            Risk_Assessment_Controls__c alpha = Risk_Assessment_Controls__c.getInstance('Risk Assessment Form');
            list<String> riskControl = new list<String>();
            Map<String,Schema.SObjectField> riskControlfieldMap = Schema.getGlobalDescribe().get('Risk_Assessment_Controls__c').getDescribe().fields.getMap();

            for(String field : riskControlfieldMap.keySet()){
                if(field.contains('x') || field.contains('X'))
            for(String field : riskControl)
                List<String> decoder;
                String Value =  (String) alpha.get(field);
                decoder = Value.split(';');
                if(decoder[2] == 'TRUE')
                if(decoder[2] == 'FALSE')

        private void GenerateQuestionSet(){

            //Generates a fresh batch of Qustions based on form id and related question bank. Note that this is done prior to loading and is unable to save data at 
            //this time. Therefore the complete process ois broken into 2 sections(see setJuction()) for the other half of this process (which is called 
            //from the save methods.)
            list<RiskQuestionComparable> orderList = new list<RiskQuestionComparable>();
            map<decimal,Risk_Question__c> ordermap = new map<decimal,Risk_Question__c>();
            list<Question_Bank_Form_Junction__c> qBank = new list<Question_Bank_Form_Junction__c>();
            map<String,String> categoryTracker = new map<String,String>();
            for(Risk_Question__c question : questions ){
                //Question_Bank_Form_Junction__c newJunction = new Question_Bank_Form_Junction__c();
                // newJunction
                Risk_Question__c newQuestion = new Risk_Question__c();
                newQuestion.Base_Question__c = question.Base_Question__c;
                newQuestion.Guidance_Above__c = question.Guidance_Above__c; 
                newQuestion.Guidance_High__c = question.Guidance_High__c;
                newQuestion.Guidance_Normal__c = question.Guidance_Normal__c;
                newQuestion.Name = question.Name;
                newQuestion.Active__c = question.Active__c;
                newQuestion.Order_number__c = question.Order_number__c;
                newQuestion.weight__c = question.weight__c;
                newQuestion.Title__c = question.Title__c;
                newQuestion.Risk_Assessment_Category__c = question.Risk_Assessment_Category__c;
                orderList.add(new RiskQuestionComparable(newQuestion,newQuestion.Order_number__c));

            for(RiskQuestionComparable riskQuestion : orderList)

        //create the pathway nessary to maintaine a set of question for any give Risk_Assesment record. This method is onlt call once per record
        //Once the question bank is set for a given record the qeustions for that record are set in stone and will never change regardless of changes to the question bank set of

        private void setJunction(){
            list<Question_Bank_Form_Junction__c> qBank = new list<Question_Bank_Form_Junction__c>();

            QARisk = new QA_Risk_Assessment__c();  
                QARisk.QA_Plan_Review__c =  QAPlanReviewId; 
                QAPlanReviewId = baseID;

            // newJunction


            for(Risk_Question__c question : formQuestions)   {
                Question_Bank_Form_Junction__c newJunction = new Question_Bank_Form_Junction__c();
                newJunction.QA_Risk_Assessment__c = QARisk.id; // will be the current form!!!
                newJunction.Question_Bank__c = null; // will be the question bank or null (not 100% that I want ot add this yet)
                newJunction.Risk_Question__c = question.id; // this question goes here

        private void validateForm(){
            list<Risk_Question__c> templist = new list<Risk_Question__c>();
            riskLevelError = false;
            CommentError = false;
            for(Risk_Question__c question : formQuestions){
                if(impactLevelMap.get(question.Level_of_Risk__c) == null)
                    riskLevelError = true;
                if(impactLevelcommentRequiredMap.get(question.Level_of_Risk__c) != null && impactLevelcommentRequiredMap.get(question.Level_of_Risk__c)){   
                    question.comment_required__c = true;
                        CommentError = true;      

  • \$\begingroup\$ Welcome to Code Review! I removed the paragraph about the situation with the PM, as it is not necessarily relevant to the code itself. I hope you get great answers! \$\endgroup\$ – Phrancis Oct 28 '17 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.