• Developer.mikie.Apex.Student
  • SMARTIE
  • 764 Points
  • Member since 2013
  • Destiny

  • Chatter
    Feed
  • 9
    Best Answers
  • 5
    Likes Received
  • 0
    Likes Given
  • 178
    Questions
  • 552
    Replies
Hello All,

I'm new to Salesforce Apex coding and undergoing some training and classes in Apex. I noticed that we cannot give any condition in List FOR loop. For example, lets say I've a list of 1000 Contacts in myContactList. I need to loop myContactList for one particular account instead of running all the records one by one and check inside the loop if the account name is what am expecting. I've seen we can use SOQL for this. But my question is can we not use the local list variable to have filter and loop only the records which I want to?

Something similar to below code for reference:
for (Contacts myContact : myContactList.Where(Account.Name = 'Acme')){

}

Let me know if there are any way I can achieve this using myContactList instead of having SOQL call.

Thanks.

Regards,
Mohan Babu
This is my first Apex Trigger and I realize it will make most of you cringe your teeth!  It is a simple trigger that will update the lead 'status' field to 'contacted' when the following criteria are met:

1- its 'lead rating' is either D1,D2,D3, or D4
2- the current lead 'status' is "open"
3- the lead has a related task containing "Message Sent:" in the subject 

Can anyone please help me bulkify this?  




trigger dleadstatus on Lead (before insert, before update) {



    for (Lead l : Trigger.new) {
    if((l.Eloqua_Lead_Rating__c =='D1' || l.Eloqua_Lead_Rating__c =='D2'|| l.Eloqua_Lead_Rating__c =='D3'|| l.Eloqua_Lead_Rating__c =='D4')&& l.Status =='Open') {
    List<Task> sentemails = [SELECT Id FROM Task WHERE Subject LIKE '%Message Sent:%'];
    
    if(sentemails.size() > 0) {
    l.Status = 'Contacted';}
    else {l.Status = 'Open';}}}

}
I got this trigger from the help and I am unable to write a test class for it.  My best attempt did not suffice any of the tests.  Could someone please help me.

thank you.


//Reassigns Contact to Account Owner

trigger reassignContact on Contact (before insert, before update) {
   try {

        Set<Id> accountIds = new Set<Id>();
        Map<Id, Id> accountOwnerIdMap = new Map<Id, Id>();
  
        // all the accounts whose owner ids to look up
        for ( Contact c : Trigger.new ) {
            if(c.accountId <> null){
             accountIds.add( c.accountId );
            }
        }
      
        // look up each account owner id
        for ( Account acct : [ SELECT id, ownerId FROM account WHERE id IN :accountIds ] ) {
            accountOwnerIdMap.put( acct.id, acct.ownerId );
        }
      
        // change contact owner to its account owner
        for ( Contact c : Trigger.new ) {
            if(c.AccountId <> null){
             c.ownerId = accountOwnerIdMap.get( c.accountId );
            }
        }
    } catch(Exception e) { //catch errors
        System.Debug('reassignContacts failure: '+e.getMessage()); //write error to the debug log
    }

}

We're trying to get rid of the Notes and Attachments section of the Contact page layout since it's not customizable.  However, we need a new "Attachments" section to replicate the attachments functionality of that related list.

 

I figured out how to create a VF page which shows the Attachments for the contact and have put that on the page layout.  I am stuck at adding an "Add Attachment" button on this page.

 

I think it's down to just writing a controller that will open the standard add attachment page and linking that attachment to the contact.  Any help here would be appreciated.

 

Note that I'm not trying to do anything with the file contents. I just want the standard Add Attachment functionality that you see in the default Notes and Attachments related list.

 

I'm fairly new to VF so this is hopefully something that's pretty simple.  :)

 

THANKS!!

Hi Guys,

I am attempting to integration our salesforce with the account tool MYOB. There are implementations out there already, but they are costly and are normally catered for the out fo the box salesforce implementation, employing opportunities, etc. 

I have successfully installed a custom integration between our custom domain and salesforce, which has a two way synch. We did this through JSON objects both single and lists sent through http Post calls. I wanted to attempt something similar with MYOB, but wouldnt even know where to begin.

i was wondering if anyone had successfully attempted this or something similar and what is the best course of action. I understand the format of web call classes and how tos tructure them within salesforce.

Any help or points in the right direction would be very much appreciated.

Hi Guys,

I cant figure out how to pass my integration class. Please help, any help would be much appreciated.

 

public class Integration {

    // The ExternalOrder class holds a string and integer
    // received from the external fulfillment system.

    public class ExternalOrder {
        public String id {
            get;
            set;
        }
        public String result {
            get;
            set;
        }
    }

    //  Functionally, the method 1) prepares
    // JSON-formatted data to send to the remote service, 2) makes an HTTP call
    // to send the prepared data to the remote service, and then 3) processes
    // any JSON-formatted data returned by the remote service to update the
    // local Invoices with the corresponding external IDs in the remote system.

    @future(callout = true) // indicates that this is an asynchronous call
    public static void postOrder(List < Id > AccountIds, boolean isScheduleExpiry) {

        //Call Accounts associated to Id List
        List < Account > Accounts = [SELECT Id, DestinyLive_Email_Username__c, Support_Expiration__c, Receiving_Support__c, DestinyLive_Premium_Membership_Expiry__c FROM Account WHERE Id IN: AccountIds];
        
        // Create a JSON generator object
        JSONGenerator gen = JSON.createGenerator(true);
        // open the JSON generator
        gen.writeStartArray();
        // iterate through the list of invoices passed in to the call
        // writing each Account ID to the array
        for (Account Acc: Accounts) {
        Datetime ExpiryDate = Acc.DestinyLive_Premium_Membership_Expiry__c;
        String myDatetimeStr = ExpiryDate.format('dd/MM/YYYY');
            gen.writeStartObject();
            gen.writeStringField('id', Acc.Id);
            if(Acc.DestinyLive_Email_Username__c != null && Acc.DestinyLive_Email_Username__c != ''){
            gen.writeStringField('DestinyLive_UserName', Acc.DestinyLive_Email_Username__c);
            }else{
            gen.writeStringField('DestinyLive_UserName', 'NA');
            }
            
            //Set Destiny Client to false as isScheduleExpiry == true because the class is scheduled to run 15 minutes before expiry
            if(isScheduleExpiry == true){
            gen.writeBooleanField('DestinyClient', false);
            }else{
            gen.writeBooleanField('DestinyClient', Acc.Receiving_Support__c);
            }
            gen.writeStringField('Expiry', myDatetimeStr);
            gen.writeEndObject();
        }
        // close the JSON generator
        gen.writeEndArray();
        // create a string from the JSON generator
        String jsonOrders = gen.getAsString();
        // debugging call, which you can check in debug logs
        System.debug('jsonOrders: ' + jsonOrders);

        // create an HTTPrequest object    
        HttpRequest req = new HttpRequest();
        // set up the HTTP request with a method, endpoint, header, and body
        req.setMethod('POST');
        // DON'T FORGET TO UPDATE THE FOLLOWING LINE WITH YOUR APP NAME
        req.setEndpoint('http://requestb.in/1n6j75u1');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(jsonOrders);
        // create a new HTTP object
        Http http = new Http();
        // create a new HTTP response for receiving the remote response
        // then use it to send the configured HTTPrequest
        HTTPResponse res = http.send(req);
        // debugging call, which you can check in debug logs
        System.debug('Fulfillment service returned ' + res.getBody());

        // 3) see above

        // Examine the status code from the HTTPResponse
        // If status code != 200, write debugging information, done
        if (res.getStatusCode() != 200) {
            System.debug('Error from ' + req.getEndpoint() + ' : ' + res.getStatusCode() + ' ' + res.getStatus());
        }
        // If status code = 200, update each Account
        // with the external ID returned by the fulfillment service.
        else {

            // Create a list of external orders by deserializing the
            // JSON data returned by the fulfillment service.
            List < ExternalOrder > orders = (List < ExternalOrder > ) JSON.deserialize(res.getBody(),
            List < ExternalOrder > .class);
            // Create a map of Invoice IDs from the retrieved
            Map < Id, Account > AccMap = new Map < Id, Account > (Accounts);
            // Update the order numbers in the invoices
            for (ExternalOrder order: orders) {
            
            if(order.result == 'Success'){
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= False;
                Acc.DestinyLive_Integration_Status__c = 'Completed - Success';
            }else if(order.result == 'NA'){
                
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= true;
                Acc.DestinyLive_Integration_Status__c = 'Completed - User Not Found';
            }else if(order.result == 'Failure'){
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= true;
                Acc.DestinyLive_Integration_Status__c = 'Completed - Failure';
           }
            }

            update Accounts;
        }
    }
}

current test 
 
@isTest 
private class Integration_Test{
    static testMethod void IntegrationTest() {
    
  List<Id> AccountIds = new List<Id>();           

  List<Account> AccountList = new List<Account>{};
for(Integer i = 0; i < 200; i++){
        Account Accs = new Account( Name = 'Test' + i, DestinyLive_Premium_Membership_Expiry__c = date.today().adddays(40), DestinyLive_Email_Username__c = 'Success22@knmfld.fdfdf', Receiving_Support__c = true, Support_Expiration__c = date.today().adddays(40), Support_Start__c = date.today().adddays(-40));
        AccountList.add(Accs);
    }
    
   insert AccountList;
    
    
    for ( Account Acc : AccountList) {
    AccountIds.add(Acc.Id);
    }
  
    Test.startTest();
     If(!Test.isRunningTest()){
    Integration.postOrder(AccountIds, True);
    }
    Test.stopTest();


}

}

 
Hi There,

I have a page which employs javascript remoting and other javascript functions. I am new to javascript and im still learning.

My biggest issue so far was the taking of values and inserting of values using javascript and field id's.

For me it seemed like nothing I tried or came across would allow me to properly reference any fields and fill them with values, until I came across this type of javascript reference ----       $j("[id$='modal_Bonus_Overtime_Commission']").val()    ---------

This allowed me to reference a field and fill in its value using javascript, success!! Then I realised that I was not able to set checkbox fields in this manner.

I tried all manner of combinations, nothing allowed me to and then finally I inspected the element and found the long ID

Something along the lines of:

document.getElementById("j_id0:Block:j_id9:myform:ThePanel:j_id38:myModal:j_id67:FormBlock:j_id70:j_id177:j_id178:j_id187:j_id188:modal_Company_Car_Provided").checked = true;

Wallah I was back in business, but it seems that this type of Id will change itself occasionally and thus rende rmy entire page unusable.

Is there a better tag i can use when taking data froma nd inserting data into visualforce or html checkbox fields.

This is my page code:
 
<apex:page sidebar="True" docType="html-5.0" controller="Contact_EmploymentHistory" tabStyle="Contact"  showHeader="True" >  

<head>
  <script type="text/javascript">
  
$j = jQuery.noConflict();

function getRemoteHistory(EditId) {
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.Contact_EmploymentHistory.getHistory}',
        EditId,
        function(result, event) {
            if (event.status) {
                // Get DOM IDs for HTML and Visualforce elements like this
                $j("[id$='modal_Id']").val(result.Id);
                $j("[id$='modal_Name']").val(result.Name);
                $j("[id$='modal_Bonus_Overtime_Commission']").val(result.Bonus_Overtime_Commission__c);
                $j("[id$='modal_Employer_Phone']").val(result.Employer_Phone__c);
                $j("[id$='modal_Employment_Basis']").val(result.Employment_Basis__c);
                $j("[id$='modal_Employment_Country']").val(result.Employment_Country__c);
                $j("[id$='modal_Employment_Postcode']").val(result.Employment_Postcode__c);
                $j("[id$='modal_Employment_State']").val(result.Employment_State__c);
                $j("[id$='modal_Employment_Status']").val(result.Employment_Status__c);
                $j("[id$='modal_Employment_Street_Name']").val(result.Employment_Street_Name__c);
                $j("[id$='modal_Employment_Street_No']").val(result.Employment_Street_No__c);
                $j("[id$='modal_Employment_Suburb']").val(result.Employment_Suburb__c);
                $j("[id$='modal_Employment_Type']").val(result.Employment_Type__c);
                $j("[id$='modal_Employment_Unit_No']").val(result.Employment_Unit_No__c);
                $j("[id$='modal_Gross_Taxable_Salary_Wage']").val(result.Gross_Taxable_Salary_Wage__c);
                $j("[id$='modal_Occupation']").val(result.Occupation__c);
                var StartDateJava;
                if (result.Start_Date__c != null) {
                var StartDateJavaMili = new Date(Math.round(Number(result.Start_Date__c)));
                StartDateJava = StartDateJavaMili.getUTCDate() + '/' + (StartDateJavaMili.getUTCMonth() + 1) + '/' + StartDateJavaMili.getUTCFullYear()
               }else{
                StartDateJava = "";
                }
                $j("[id$='modal_Start_Date']").val(StartDateJava);
                var EndDateJava;
                if (result.End_Date__c != null) {
                var EndDateJavaMili = new Date(Math.round(Number(result.End_Date__c)));
                var EndDateJava = EndDateJavaMili.getUTCDate() + '/' + (EndDateJavaMili.getUTCMonth() + 1) + '/' + EndDateJavaMili.getUTCFullYear()
                }else{
                EndDateJava = "";
                }
                $j("[id$='modal_End_Date']").val(EndDateJava);
                if (result.On_Probation__c == true) {
                     document.getElementById($="modal_On_Probation").checked = true;
                    $j("[id$='modal_ProbationExpiryFieldGroup']").show();
                } else {
                    $j("[id$='modal_ProbationExpiryFieldGroup']").hide();
                }
                if (result.Company_Car_Provided__c == true) {
                    document.getElementById("j_id0:Block:j_id9:myform:ThePanel:j_id38:myModal:j_id67:FormBlock:j_id70:j_id177:j_id178:j_id187:j_id188:modal_Company_Car_Provided").checked = true;
                }
                var ProbationExpiryJava;
                if (result.Probation_Expiry__c != null) {
                var ProbationExpiryJavaMili = new Date(Math.round(Number(result.Probation_Expiry__c)));
                var ProbationExpiryJava = ProbationExpiryJavaMili.getUTCDate() + '/' + (ProbationExpiryJavaMili.getUTCMonth() + 1) + '/' + ProbationExpiryJavaMili.getUTCFullYear();
                }else{
                ProbationExpiryJava = "";
                }
                $j("[id$='modal_Probation_Expiry']").val(ProbationExpiryJava);

                $j('#myModal').modal({
                    backdrop: 'static'
                });

            } else if (event.type === 'exception') {
                document.getElementById("responseErrors").innerHTML =
                    event.message + "<br/>\n<pre>" + event.where + "</pre>";
                $j('#myModal').modal({
                    backdrop: 'static'
                });
            } else {
                document.getElementById("responseErrors").innerHTML = event.message;
            }
        }, {
            escape: true
        }
    );
}



function updateWarehouse() {

    var CompanyCar = false;
    if (document.getElementById("j_id0:Block:j_id9:myform:ThePanel:j_id38:myModal:j_id67:FormBlock:j_id70:j_id177:j_id178:j_id187:j_id188:modal_Company_Car_Provided").checked == true) {
        CompanyCar = true;
    } else {
        CompanyCar = false;
    }
    debugger;
    alert( $j("[id$='modal_Probation_Expiry']").val());
    var OnProbation = false;
    if (document.getElementById("j_id0:Block:j_id9:myform:ThePanel:j_id38:myModal:j_id67:FormBlock:j_id70:j_id177:j_id178:j_id187:j_id188:modal_On_Probation").checked == true) {
        OnProbation = true;
    } else {
        OnProbation = false;
    }
    var EH = {
        Id: $j("[id$='modal_Id']").val(),
        Name: $j("[id$='modal_Name']").val(),
        Bonus_Overtime_Commission__c: $j("[id$='modal_Bonus_Overtime_Commission']").val(),
        Employer_Phone__c: $j("[id$='modal_Employer_Phone']").val(),
        Employment_Unit_No__c: $j("[id$='modal_Employment_Unit_No']").val(),
        Employment_Street_No__c: $j("[id$='modal_Employment_Street_No']").val(),
        Employment_Street_Name__c: $j("[id$='modal_Employment_Street_Name']").val(),
        Employment_Suburb__c: $j("[id$='modal_Employment_Suburb']").val(),
        Employment_State__c: $j("[id$='modal_Employment_State']").val(),
        Employment_Postcode__c: $j("[id$='modal_Employment_Postcode']").val(),
        Employment_Country__c: $j("[id$='modal_Employment_Country']").val(),
        Employment_Type__c: $j("[id$='modal_Employment_Type']").val(),
        Employment_Status__c: $j("[id$='modal_Employment_Status']").val(),
        Occupation__c: $j("[id$='modal_Occupation']").val(),
        Employment_Basis__c: $j("[id$='modal_Employment_Basis']").val(),
        Gross_Taxable_Salary_Wage__c: $j("[id$='modal_Gross_Taxable_Salary_Wage']").val(),
        Start_Date__c: DateFixer($j("[id$='modal_Start_Date']").val()),
        End_Date__c: DateFixer($j("[id$='modal_End_Date']").val()),
        Probation_Expiry__c: DateFixer($j("[id$='modal_Probation_Expiry']").val()),
        Company_Car_Provided__c: CompanyCar,
        On_Probation__c: OnProbation,

    };    
    
    
    console.log(EH);
    // Call the remote action to save the record data
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.Contact_EmploymentHistory.setHistory}',
        EH,

        function(result, event) {

            if (event.status) {
                alert("Status");
                alert(result);

            } else if (event.type === 'exception') {

                alert("exception");
                alert(result);

            } else {
                alert("special exception");
                alert(result);
            }

        });

}

function DateFixer(DateConvert) {

    var DateReturned;
    if(DateConvert == ""){
    DateReturned = "4127068800000";
    }else{
    var formattedDays = DateConvert.split("/");
    var DateReturned = Date.UTC(formattedDays[2], ((formattedDays[1]) - 1), formattedDays[0], 0, 0, 0, 0);
    }
    return DateReturned;
}

function FieldRenderer() {

    if (document.getElementById("j_id0:Block:j_id9:myform:ThePanel:j_id38:myModal:j_id67:FormBlock:j_id70:j_id177:j_id178:j_id187:j_id188:modal_On_Probation").checked == true) {
        $j("[id$='modal_ProbationExpiryFieldGroup']").show();
    } else {

        $j("[id$='modal_ProbationExpiryFieldGroup']").hide();
    };
    if ($j("[id$='modal_Employment_Status']").val() != "Previous Employment") {
        $j("[id$='modal_End_Date_FieldGroup']").hide();
    } else {

        $j("[id$='modal_End_Date_FieldGroup']").show();
    };
    if ($j("[id$='modal_Employment_Type']").val() == "PAYG" || $j("[id$='modal_Employment_Type']").val() == "Self Employed") {
        $j("[id$='modal_RenderSection']").show();
    } else if  ($j("[id$='modal_Employment_Type']").val() == "Home Duties" || $j("[id$='modal_Employment_Type']").val() == "Unemployed" || $j("[id$='modal_Employment_Type']").val() == "Retired"){

        $j("[id$='modal_RenderSection']").hide();
    };

}

</Script>
 <style>
        div.hideCurrDate span.dateInput span.dateFormat{
           display:none;
        }
  
div.ct{
text-align:center;
}
</style>
</head>

 <vs:importvisualstrap theme="default" />  
<vs:visualstrapblock id="Block" > 
<apex:pageMessages />

<apex:form id="myform">


<vs:panel title="Employment History Structure" type="primary" id="ThePanel" >     

<vs:row > 
<vs:column type="col-md-1"> 
<div style="text-align:center">
<apex:outputLabel >Number of Records</apex:outputLabel>
</div>
</vs:column> 
</vs:row> 

<vs:row > 
<vs:column type="col-md-1"> 
<div align="center">
<apex:outputText id="NoRecords"  value="{!Con.Number_of_Employment_Records__c}"/>
</div>
</vs:column> 
</vs:row> 
<br/><br/>

<!------------------------ MODAL ATTEMPT --------------------------->
      
<!--modal that will be displayed to the user-->
<vs:modal title="Employment History Information" id="myModal">
<apex:InputHidden id="modal_Id" value="{!SaveId}" />
  <vs:formblock id="FormBlock" styleclass="form-horizontal">
  <div id="responseErrors"></div>
    <vs:formgroup id="FormGroup" >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Type:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield id="modal_Employment_Type" styleClass="form-control" onchange="FieldRenderer();"  Value="{!Con1History.Employment_Type__c}" html-placeholder="Employment Type"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Status:   
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Status__c}" onchange="FieldRenderer();" id="modal_Employment_Status" html-placeholder="Employment Status"/>                                        
          </vs:column>
    </vs:formgroup>
        <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Start Date:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
         
            <apex:inputtext styleClass="form-control" Value="{!Con1History.Start_Date__c}" id="modal_Start_Date"  html-placeholder="Start Date"></apex:inputtext>                                      
        </vs:column>
    </vs:formgroup>
    <apex:outputPanel id="modal_End_Date_FieldGroup">
            <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 End Date:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.End_Date__c}" id="modal_End_Date" html-placeholder="End Date"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
    </apex:outputPanel>
    <apex:outputPanel id="modal_RenderSection">
                <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Occupation:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Occupation__c}" id="modal_Occupation" html-placeholder="Occupation"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Basis:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Basis__c}" id="modal_Employment_Basis" html-placeholder="Employment Basis"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Gross Taxable Salary/Wage:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Gross_Taxable_Salary_Wage__c}" id="modal_Gross_Taxable_Salary_Wage" html-placeholder="Gross Taxable Salary/Wage"></apex:inputfield>                               
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Bonus/Overtime/ <br/> Commission:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Bonus_Overtime_Commission__c}" id="modal_Bonus_Overtime_Commission" html-placeholder="Bonus/Overtime/Commission"></apex:inputfield>     
             <div class="checkbox">
              <apex:outputLabel >
                <apex:inputfield Value="{!Con1History.Company_Car_Provided__c}" id="modal_Company_Car_Provided" /> Company Car Provided
              </apex:outputLabel>
            </div> 
            <div  class="checkbox">
              <apex:outputLabel >
                <apex:inputCheckbox Value="{!Con1History.On_Probation__c}" onclick="FieldRenderer();" id="modal_On_Probation" > On Probation
                  </apex:inputCheckbox>
              </apex:outputLabel>
            </div>                                       
        </vs:column>
    </vs:formgroup>
<apex:outputPanel id="modal_ProbationExpiryFieldGroup">
                <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;" >
  
             <apex:outputLabel styleclass="control-label">
                 Probation Expiry:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Probation_Expiry__c}" id="modal_Probation_Expiry" html-placeholder="Probation Expiry" ></apex:inputfield>                                           
        </vs:column>
    </vs:formgroup>
 </apex:outputPanel>   
                <vs:formgroup id="Group" >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employer:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield Value="{!Con1History.Name}" styleClass="form-control" id="modal_Name" html-placeholder="Employer"></apex:inputfield>                                  
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employer Phone #:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employer_Phone__c}" id="modal_Employer_Phone" html-placeholder="Employment Phone"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Unit No.:   
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Unit_No__c}" id="modal_Employment_Unit_No" html-placeholder="Employment Unit No."></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Street No.:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Street_No__c}" id="modal_Employment_Street_No" html-placeholder="Employment Street No."></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Street Name:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Street_Name__c}" id="modal_Employment_Street_Name" html-placeholder="Employment Street Name"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Suburb:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Suburb__c}" id="modal_Employment_Suburb" html-placeholder="Employment Suburb"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment State:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_State__c}" id="modal_Employment_State" html-placeholder="Employment State"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Postcode:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Postcode__c}" id="modal_Employment_Postcode" html-placeholder="Employment Postcode"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
                    <vs:formgroup >
         <vs:column type="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:center;">
             <apex:outputLabel styleclass="control-label">
                 Employment Country:    
             </apex:outputLabel>
         </vs:column>
         <vs:column type="col-lg-10 col-md-10 col-sm-10 col-xs-10">
            <apex:inputfield styleClass="form-control" Value="{!Con1History.Employment_Country__c}" id="modal_Employment_Country" html-placeholder="Employment Country"></apex:inputfield>                                      
        </vs:column>
    </vs:formgroup>
    </apex:outputPanel>
    <vs:formgroup style="margin-top:30px;">
      <vs:column type="col-lg-12 col-md-12 col-sm-12 col-xs-12">
          <center>
            <apex:commandButton value="Cancel" onclick="updateWarehouse();" styleClass="btn btn-danger"/>
            <apex:commandButton value="Submit" Action="{!SaveHelper}" styleClass="btn btn-success"/>
        </center>
      </vs:column>
    </vs:formgroup>
</vs:formblock>
</vs:modal>  

   <br></br>
   <br></br>
<!------------------------ MODAL ATTEMPT --------------------------->


 
Hi There,

I am attempting to create an email app. I works pretty well, however I have continuously come into an error:

Error:j_id0:j_id79:j_id80:ComponentForm:j_id90:j_id91:myEmailModal:j_id97:myPanel1:j_id100:Templates: Validation Error: Value is not valid

The only thing i can work out is the i thinka  combination of using \n and selectlist is causing the problems. I have a selectlist which is designed to paste a string into an inputtext area depending on your selectlist pick. This works fine, but when I select a tempalte that includes \n it errors with the above message after I try and encode() it. I click the encode button once and it errors, i click a second time and it randomly works. But the selectlist is no longer on that particular tempalt echoice. However, when i use a more simple string - E.G. 'Test', it works without issues and encodes the email fine.

Please help

Component
<apex:component controller="DestinyEmailComponent"> <apex:attribute type="boolean" name="ImportVisualStrap" description="Set this value to true if visualstrap has not already been imported on your page" default="true"/> <apex:attribute name="AssociatedAccount" required="true" type="Id" description="id of Associated Account" assignTo="{!AccountId}"/> <!-- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script src="{!URLFOR($Resource.charCounter)}" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $('.countable').jqEasyCounter({ 'maxChars': 300000, 'maxCharsWarning': 20000, 'msgFontSize': '12px', 'msgFontColor': '#000', 'msgFontFamily': 'Verdana', 'msgTextAlign': 'left', 'msgWarningColor': '#F00', 'msgAppendMethod': 'insertAfter' }); }); </script> --> <script> function MessageRender(Body) { var MessageBodyHidden2 = Body.options[Body.selectedIndex].value; var MessageBody = document.getElementById('j_id0:j_id79:j_id80:ComponentForm:j_id90:j_id91:myEmailModal:j_id97:myPanel1:j_id100:MessageBody'); MessageBody.value = MessageBodyHidden2; MessageBodyHidden2.value = ''; //updateState(); } function EncodeEmail() { //var MessageBody = document.getElementById('j_id0:j_id79:j_id80:ComponentForm:j_id90:j_id91:myEmailModal:j_id97:myPanel1:j_id100:MessageBody'); //debugger; //var EncodeString = MessageBody.value; //debugger; //EncodeString = EncodeString.trim(); //debugger; //var MessageBodyT = document.getElementById('j_id0:j_id79:j_id80:ComponentForm:j_id90:j_id91:myEmailModal:j_id97:myPanel1:j_id100:MessageBodyT'); //debugger; //MessageBodyT.value = MessageBodyT; //MessageBodyT.value = "hello"; } </script> <apex:outputPanel rendered="{!ImportVisualStrap}" layout="none"> <c:importvisualstrap theme="cosmos"/> </apex:outputPanel> <apex:componentBody > <apex:form id="ComponentForm" > <c:visualstrapblock > <div align="center"> <apex:commandButton value="Open Email App" onclick="return false;" html-data-toggle="modal" html-data-target="#myEmailModal" styleClass="btn-success btn-sm"/> </div> <br/> <!--modal that will be displayed to the user--> <c:modal id="myEmailModal"> <c:panel id="myPanel1" title="Destiny Email App" type="primary" > <apex:outputPanel layout="block" id="MyModalPanel"> <div align="left"> <apex:outputLabel value="Select Contact" for="Contacts"/> <apex:outputPanel layout="block"> <apex:actionRegion > <apex:selectList id="Contacts" size="1" value="{!EmailContact}" title="Type" styleClass="form-control"> <!-- <apex:actionSupport event="onchange" action="{!ProcessData}"/> --> <apex:selectOptions value="{!Contacts}"></apex:selectOptions> </apex:selectList> </apex:actionRegion> <br/> <br/> </apex:outputPanel> <apex:outputLabel value="Select Contact" for="Templates"/> <apex:outputPanel layout="block"> <apex:actionRegion > <apex:selectList id="Templates" size="1" value="{!Template2}" onchange="javascript:MessageRender(this)" title="Type" styleClass="form-control"> <!-- <apex:actionSupport event="onchange" action="{!EncodeEmail}" /> rerender="MyModalPanel,ScriptPanel"--> <apex:selectOptions id="TemplateOptions" value="{!Templates2}"></apex:selectOptions> </apex:selectList> </apex:actionRegion> <br/> <br/> </apex:outputPanel> </div> <br/> <div align="left"> <apex:outputLabel value="Text Message:" for="MessageBody"/> <br/> <apex:inputTextarea rows="4" cols="70" label="Text Message Body: " value="{!MessageBody}" id="MessageBody"/> <br/><!-- styleClass="countable" <apex:actionFunction name="updateState" rerender="ScriptPanel" action="{!EncodeEmail}" /> --> <br/> <apex:outputText value="{!MessageBodyT}" escape="false" id="MessageBodyT"/> </div> <apex:pagemessages /> <apex:outputPanel layout="block" id="Footer" styleClass="modal-footer"> <div align="center"> <!-- rendered="{!NOT(isComplete)}" --> <apex:commandButton value="Send Email" styleClass="btn-success" onclick="$(this).button('loading')" html-data-loading-text="Sending..." action="{!SendEmail}" /> <apex:commandButton value="Close SMS App" styleClass="btn-danger" action="{!CloseApp}" /> <apex:commandButton value="Encode" styleClass="btn-danger" onclick="$(this).button('loading')" html-data-loading-text="Encoding..." action="{!EncodeEmail}" /> <apex:commandButton value="Encode2" styleClass="btn-danger" html-data-loading-text="Encoding..." onclick="EncodeEmail(); $(this).button('loading'); " /> <apex:commandButton value="Encode3" styleClass="btn-warning" action="{!EncodeEmail}" /> <!--<apex:commandButton value="Close SMS App" styleClass="btn-warning" "action="{!CloseApp}" html-data-dismiss="modal"/> --> </div> </apex:outputPanel> <apex:outputPanel rendered="{!isComplete}" id="ScriptPanel" > <script> $('#myEmailModal').modal('hide'); $('#myEmailModal').modal('show'); </script> </apex:outputPanel> </apex:outputPanel> </c:panel> </c:modal> </c:visualstrapblock> </apex:form> </apex:componentBody> </apex:component>



class
public with sharing class DestinyEmailComponent {
    
  public Id AccountId;//Associated Account
  String EmailContact;//String Received from Contact List
  public String Template2 {get;set;}//Template string
  
  String ToEmail {get;set;}//Contact Mobile Number
  public String MessageBody {get;set;}//Text Message Body
  
  String userName = UserInfo.getUserName(); //Query UserName
  User activeUser = [Select Username,Destiny_Office__c, Name, Title, Email_Signature__c From User where Username = : userName]; //Query User Record
  
  String EmailFooterHTML  {get;set;}
  String EmailHeaderHTML  {get;set;}
String EmailParagraphStart  {get;set;}
String EmailParagraphEnd  {get;set;}
  
   public String MessageBodyT {get;set;}//Text Message Body
  
  public Boolean isComplete{get;set;}
  map<id, Contact> ConDataMap = new Map<id, Contact>();
  
  
  public DestinyEmailComponent (){ 
  }
    
  public void setAccountId (Id s) {
    AccountId = s;
  }
    
  public String getAccountId() {
    return AccountId;
  } 
  
  public string getMessageBody (){
    return MessageBody;
    }
    
    public string getMessageBodyT (){  
    return MessageBodyT;
    }
    
        public void setMessageBodyT (string s){
    MessageBodyT=s;            
    }
  public void setMessageBody (string s){
    MessageBody=s;            
    }
       
    
    public List<SelectOption> getContacts() 
       {
       
 List<Contact> Contact=[select id, FirstName, LastName, Name, MobilePhone, Email From Contact where AccountId =: AccountId order by createddate]; //Query Associated Contacts
        
 if(Contact != null && Contact.size() > 0){
for(Contact C:Contact  ){ 
 ConDataMap.put(C.Id, C);
                         }
                                             }
       List<SelectOption> options = new List<SelectOption>();
       options.add(new SelectOption('','Select Contact'));
       for(integer i=0;i< Contact.size();
       i++)
        {
        options.add(new SelectOption(Contact[i].Id,Contact[i].Name+' -('+Contact[i].Email+')'));       
        }
        return options;
        }
               
        
        public List<SelectOption> getTemplates2() 
       {
       
       
       List<SelectOption> options2 = new List<SelectOption>();
       options2.add(new SelectOption('','Select Template'));
              
       String HTMLTest2 = 'Test';
       options2.add(new SelectOption(HTMLTest2,'HTMLTest2'));
       
       String ApplicationSubmitted = EmailHandler.Fin_ApplicationSubmitted;
       options2.add(new SelectOption(ApplicationSubmitted,'Application Submitted'));
       
        String Test  = EmailHandler.Fin_Test;
       options2.add(new SelectOption(Test,'Test'));
       
        return options2;
       
       
       }
        
        
        
 public String getEmailContact() {
            return EmailContact;
        }
        
public void setEmailContact(String EmailContact) {this.EmailContact= EmailContact;}

 public String getTemplate2() {
            return Template2;
        }
        
public void setTemplate2(String Template2) {this.Template2= Template2;}
        
        
        Public void ProcessData(){
        
If(EmailContact != null && ConDataMap.get(EmailContact).Email != null){
ToEmail = ConDataMap.get(EmailContact).Email;
} 
}

Public void EncodeEmail(){
Template2 = null;

  String MessageBodySend = EmailHandler.EmailHeaderHTML+EmailHandler.EmailParagraphStart+MessageBody+EmailHandler.EmailParagraphEnd+EmailHandler.EmailFooterHTML;

  MessageBodySend = MessageBodySend.trim();   
  MessageBodySend   = MessageBodySend.replace('\n','</p><p style="color: #00204e; font-family: Arial, Helvetica, sans-serif; font-size: 12px;">');
   MessageBodySend  = MessageBodySend.replace('  ','&nbsp');
    MessageBodyT = MessageBodySend;
    
    isComplete = true;

}




    //Message Function (Via Email to @sms.exemail.com.au)
  public void SendEmail() {
EncodeEmail();
ProcessData();
  
  try{
   
        EmailHandler.sendDestinyEmail(ToEmail,MessageBodyT);
        ApexPages.Message Successmsg = new ApexPages.Message(ApexPages.severity.confirm,'Your Email is being processed!');
        ApexPages.addMessage(Successmsg);
        
      }
catch(Exception ex){
                    Apexpages.addMessages(ex);

                    }
                   
     isComplete = true;
                                }
                                
                                
                                
 public void CloseApp() {
 
 ToEmail = null;
 MessageBody = null;
 EmailContact = null;
 Template2 = null;
 isComplete = False;
 
 }

    
    
    
    
  
}

 
Hi There,

I am attempting to create a global view of all records in regards to an object. I have made it so that I can render a list of 1000+ records on one page, I have also added the plugin PageBlockTable Enchancer by Avi. This allows me to compress the list into a pageblocktable with search functionality, etc. 

I have attempted to re-create the standard List View filter from salesforce. I have managed to get it working, however it is temperamental to say the least. My first obstacle was clearing the old List of records, as when i changed it, rather than repalcing the records, it was adding the records onto each other. E.G. list of 10 records and a list of 5, as i swapped between them, rather than going from 10 to 5, it went from 10 to 15. I managed to fix this by re-rendering the table.

My issue now is, when I change between the different list views, randomly and without warning it may un-render the results of the old list and never render the new results, leaving me with a blank table. On the other hand, just as many times, it will work perfectly.

Any pointers from people that understand javascript remotign better than I would be much aprpeciated.

Page:
 
<apex:page controller="PBE1KRemoting_Tra" extensions="FileUploader_TraEziDebit"   tabStyle="Transaction__c">
<apex:pageMessages />
    <apex:includeScript value="{!$Resource.JqueryTest}"/>
    <apex:includeScript value="{!$Resource.JsRenderTest}"/>
 <apex:includeScript value="{!$Resource.HighLight}"/>
    <script>
    
    
   
var compiledTemplate;
var NewTemplate;
var EziDebitTest;

            
        function getTransactions(callback){ 
        
         debugger;
            Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.PBE1KRemoting_Tra.getTransactions}',
                ' ORDER BY Date_of_Payment__c Desc limit 10000',
                function(result, event){
                     callback(result);
                      debugger;
                }, 
                {escape: false}
            );
        }
        
    //on document ready call query and render the template
     $j = jQuery.noConflict();
function highlightElem(elem){
$j(elem).parent().parent().parent().find('tr').removeClass('ui-state-highlight');
$j(elem).parent().parent().addClass('ui-state-highlight');
}

        $(function(){
         debugger;
            getTransactions(function(result){
             debugger;             
             //Attempt to convert Date with a helper function
              var html = $("#TransactionTableRowTmpl").render(result);
                //replace the table body with rendered html
                $j("#TransactionTableBody").html(html);   
              initPageBlockTableEnhancerADV();
                
            });
    
        })
        
        
        
   function getTransactionFilter2(TraFilterId) {
     updateState4();
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.PBE1KRemoting_Tra.getTransactions}',
            TraFilterId, 
            
            function(result, event){
            
         if (event.status) {
             // Get DOM IDs for HTML and Visualforce elements like this
                //replace the table body with rendered html 
        NewTemplate = $("#TransactionTableRowTmpl").render(result);
                //replace the table body with rendered html
                $j("#TransactionTableBody").html($("#TransactionTableRowTmpl").render(result));
               initPageBlockTableEnhancerADV();
    } else if (event.type === 'exception') {
                alert(event.message);
                } else {
                   alert(event.message);
                }
            }, 
            {escape: true}
        );
    }     
        

  function bump() {
  debugger;
  $("#TransactionTableBody tbody").html('');
     updateState4();
}

  function bump2(TraId) {
    var counter3 = document.getElementById("{!$Component.form2.counter3}");
     debugger;
    counter3.value = TraId;
     debugger;
    updateState3();
}

  function bump3() {
   debugger;
   initPageBlockTableEnhancerADV();
    debugger;
}

  function bump4(TraFilterId) {
    var counter4 = document.getElementById("{!$Component.form2.counter4}");
    counter4.value = TraFilterId;
}



   function getTransactionFilter(TraFilterId) {
   bump();
   
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.PBE1KRemoting_Tra.getTransactionFilter}',
            TraFilterId, 
            
            function(result, event){
            
         if (event.status) {
             // Get DOM IDs for HTML and Visualforce elements like this
                //replace the table body with rendered html 
                               NewTemplate = $("#TransactionTableRowTmpl").render(result);
                //replace the table body with rendered html
                $j("#TransactionTableBody").html($("#TransactionTableRowTmpl").render(result));
               initPageBlockTableEnhancerADV();
    } else if (event.type === 'exception') {
                alert(event.message);
                } else {
                   alert(event.message);
                }
            }, 
            {escape: true}
        );
    }     
    
    
    
     var newWin=null;
 function openAccountPopup(AccountID)
 {
  var url="/apex/DestinyAccount?id=" + AccountID;
    $jnewWin=window.open(url);
  if (window.focus)
  {
     $jnewWin.focus();
  }
    
     return false;
    }
    
     function openOfficePopup(OfficeID)
 {
  var url="/apex/DestinyOffice?id=" + OfficeID;
    $jnewWin=window.open(url);
  if (window.focus)
  {
     $jnewWin.focus();
  }
    
     return false;
    }
    
    
$.views.converters("Date", function(val) {
  var dt = new Date(val);
  var StringDate = dt.toDateString();
  return StringDate;
});



    </script>
  
    
    <!-- JS Render Template  oncomplete="highlightElem(this);"       <td class="dataCell">{{>Date_of_Payment__c}}</td> -->
    <script id="TransactionTableRowTmpl" type="text/x-jsrender">
        <tr class="dataRow" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">   
  <td class="dataCell"><button rerender="Tradetails" id="Test1"  onclick="bump2('{{>Id}}'); highlightElem(this);" >{{>Name}}</button></td>  
            <td class="dataCell">{{Date:Date_of_Payment__c}}</td> 
           
            <td class="dataCell">{{>Amount__c}}</td>
            <td class="dataCell"><a href="#" onclick="openAccountPopup('{{>Account__c}}'); return false"  >{{>Account__r.Name}}</a></td>
            <td class="dataCell">{{>Method__c}}</td>
             <td class="dataCell">{{>Service_Name__c}}</td>
              <td class="dataCell">{{>Transaction_Type__c}}</td>
               <td class="dataCell"><a href="#" onclick="openOfficePopup('{{>Office__c}}'); return false"  >{{>Office__r.Name}}</a></td>
        </tr>
    </script>
        <script id="TransactionTableRowTmp2" type="text/x-jsrender">
        <tr class="dataRow" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">   
  <td class="dataCell"><button rerender="Tradetails" id="Test1"  onclick="bump2('{{>Id}}'); highlightElem(this);" >{{>Name}}</button></td>  
            <td class="dataCell">{{Date:Date_of_Payment__c}}</td> 
           
            <td class="dataCell">{{>Amount__c}}</td>
            <td class="dataCell"><a href="#" onclick="openAccountPopup('{{>Account__c}}'); return false"  >{{>Account__r.Name}}</a></td>
            <td class="dataCell">{{>Method__c}}</td>
             <td class="dataCell">{{>Service_Name__c}}</td>
              <td class="dataCell">{{>Transaction_Type__c}}</td>
               <td class="dataCell"><a href="#" onclick="openOfficePopup('{{>Office__c}}'); return false"  >{{>Office__r.Name}}</a></td>
        </tr>
    </script>
       
    <c:PageBlockTableEnhancerADV targetPbTableIds="TransactionTable"  pageSizeOptions="5,15,25,50,100,250" defaultPageSize="15" enableExport="False"/>
    <apex:sectionheader title="Global Transactions View" subtitle="Home"></apex:sectionheader>
    
<apex:pageBlock >

<!-- Borrow some styling from Pageblock table -->
<apex:form id="form">
 <apex:panelGrid columns="2">
                    <apex:outputLabel value="View:"/>
<apex:selectList id="TraFilter3" size="1" onchange="getTransactionFilter(this.value); " value="{!TraFilterId}"  >
<apex:selectOptions value="{!TraFilter}"   />
</apex:selectList>
                </apex:panelGrid>
                  </apex:form>
                  
                  
 <apex:outputPanel id="Tradetails2">
        <table class="list" border="0" cellpadding="0" cellspacing="0" id="TransactionTable">
            <thead class="rich-table-thead">
                <tr class="headerRow ">
                    <th class="headerRow">Name</th>
                    <th class="headerRow">Date</th>
                    <th class="headerRow">Amount</th>
                    <th class="headerRow">Account</th>
                    <th class="headerRow">Method</th>
                    <th class="headerRow">Service Name</th>
                    <th class="headerRow">Type</th>
                    <th class="headerRow">Office__c</th>
                </tr>
            </thead>
            <tbody id="TransactionTableBody">
            
            </tbody>     
        </table>
            </apex:outputPanel>
    </apex:pageBlock>
    <apex:form id="form2">
<apex:outputPanel id="Tradetails">
<apex:actionFunction name="updateState3" reRender="Tradetails"/>
<apex:actionFunction name="updateState4" reRender="Tradetails2"/>
<apex:inputHidden id="counter3" value="{!controllerProperty}"/>
<apex:inputHidden id="counter4" value="{!TraFilterId}"/>
<apex:detail id="Test4" subject="{!controllerProperty}" relatedList="True" inlineEdit="True" title="false"/>
</apex:outputPanel>
</apex:form>
<apex:pageBlock id="pageBlock1" rendered="{!($Profile.Name=='Destiny Director')||($Profile.Name=='Financial Controller')||($Profile.Name=='Head Office Support')||($Profile.Name=='System Administrator')}" >

 <apex:form id="form3">
 <apex:pageBlockSection title="Upload EziDebit Records" collapsible="false" >
 </apex:pageBlockSection>

              <center>
               <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> 
              <apex:commandButton action="{!ReadFile}" rendered="{!IF(ISNULL(DocId),True,False)}" value="Upload File" id="theButton" style="width:70px;"/>
            <apex:commandButton rendered="{!IF(ISNULL(DocId),False,True)}" onclick="window.open('https://c.ap1.content.force.com/servlet/servlet.FileDownload?file={!DocId}');" value="Download Errors" />
             </center> 
</apex:form>
</apex:pageBlock>
</apex:page>

and controller:
 
public  with sharing class PBE1KRemoting_Tra {

public static Transaction__c Tra { get; set; }
public string TraId { get; set; }
public Id TraIdInsert { get; set; }

//Filter
Public String TraFilterId;

public String getTraFilterId(){return TraFilterId;}
public void setTraFilterId(String TraFilterId) {this.TraFilterId= TraFilterId;}



    @RemoteAction
    public static List<transaction__c> getTransactions(String TraFilter){
    
  
   List<Transaction__c> Transactions = [SELECT ID, Name, Date_of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, Office__r.Name, CreatedDate,Account__r.Name FROM Transaction__c TraFilter];
return Transactions;
   }
   
    @RemoteAction
    public static List<transaction__c> getTransactionsTest(){
    
  
   List<Transaction__c> TransactionsTest = [SELECT ID, Name, Date_of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, Office__r.Name, CreatedDate,Account__r.Name FROM Transaction__c ORDER BY Date_Of_Payment__c Desc limit 10000];
   
   If(TransactionsTest.size() > 0){
   return TransactionsTest;
   }Else{
   Return null;
   }
   
    }
    
     @RemoteAction
    public static Transaction__c getTransaction(String TraId) {

        // Clean up the Id parameter, in case there are spaces
        // Simple SOQL query to get the warehouse data we need
        Tra = [
            SELECT ID, Name, Date_of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, CreatedDate
            FROM Transaction__c 
            WHERE Id = :TraId]; 
                        
                      

        return(Tra);
    }
    
            @RemoteAction
    public static List<transaction__c> getTransactionFilter2(String TraFilterId) {
       List<Transaction__c> Transactions = [SELECT ID, Name, Date_of_Payment__c, Amount__c, Account__c, Account__r.Name, Method__c, Service_Name__c, Transaction_Type__c, Office__c, Office__r.Name, CreatedDate FROM Transaction__c TraFilterId];  
        return Transactions;  
    }
 
 
 
 
   @RemoteAction
    public static List<transaction__c> getTransactionFilter(String TraFilterId) {
    String Query = 'SELECT ID, Name, Date_of_Payment__c, Amount__c, Account__c, Account__r.Name, Method__c, Service_Name__c, Transaction_Type__c, Office__c, Office__r.Name, CreatedDate FROM Transaction__c';
    String WhereQuery = TraFilterId;
    String Filter = ' ORDER BY Date_of_Payment__c Desc limit 10000';

if(TraFilterId != ''){
        return Database.query(Query+' '+WhereQuery+Filter);
}else{
        return Database.query(Query+Filter);

}
    }
 
 
    
    
   public String controllerProperty {get;set;}
   
    public PBE1KRemoting_Tra () {
        controllerProperty = null;
        TraFilterId = '';
    }
  
    
    public list<selectoption> getTraFilter()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('','All'));
      options.add(new SelectOption('where Method__c=\''+                                 String.escapeSingleQuotes('EZIDEBIT')+'\'','EziDebit Transactions'));
      options.add(new SelectOption('where transaction_type__c=\''+                                 String.escapeSingleQuotes('First Payment')+'\'','First Payments'));
      options.add(new SelectOption('where transaction_type__c=\''+                                 String.escapeSingleQuotes('Part Payment')+'\'','Part Payments'));
      options.add(new SelectOption('where transaction_type__c=\''+                                 String.escapeSingleQuotes('Final Payment')+'\'','Final Payments'));
      options.add(new SelectOption('where transaction_type__c=\''+                                 String.escapeSingleQuotes('Refund')+'\'','Refunds'));
      options.add(new SelectOption('Test1','Test1'));
      

   return options;
 }    

   
    
}

Thank you in advance
 
Hi There,

I am trying to filter my Javascript remoting page. I have the original query and it loads on page load. But then when I attempt to filter, rather than removing the old values, it merely adds the filtered results into the new table.

I need a way of which to clear the old Html from a Jsrender template and then load a new set of records into it. 

Thank you in advance for your time, any tips or points would be much appreciated.
 
<apex:page controller="PBE1KRemoting_Tra"   tabStyle="Transaction__c">
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"/>
    <apex:includeScript value="https://rawgithub.com/BorisMoore/jsrender/master/jsrender.min.js"/>
 
    <script>
    
    
    var DocumentReady = "True";
            
        function getTransactions(callback){  
            Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.PBE1KRemoting_Tra.getTransactions}',
                DocumentReady, 
                function(result, event){
                     callback(result);
                     DocumentReady = "False";
                }, 
                {escape: false}
            );
        }
        
    //on document ready call query and render the template
       var j$ = jQuery.noConflict();
  
   j$(function(){
            getTransactions(function(result){
            
                var html = $("#TransactionTableRowTmpl").render(result);
                //replace the table body with rendered html
                j$("#TransactionTableBody").html(html);        
                initPageBlockTableEnhancerADV();
                
                
            });
        })

        

             

   function getTransaction(TraId) {

        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.PBE1KRemoting_Tra.getTransaction}',
            TraId, 
            function(result, event){
                if (event.status) {
                    // Get DOM IDs for HTML and Visualforce elements like this
                                     document.getElementById('remoteAcctId').innerHTML = result.Name
                    document.getElementById(
                        "{!$Component.block.blockSection.secondItem.acctNumEmployees}"
                        ).innerHTML = result.Account__c;
                                     
                } else if (event.type === 'exception') {
                    document.getElementById("responseErrors").innerHTML = 
                        event.message + "<br/>\n<pre>" + event.where + "</pre>";
                } else {
                    document.getElementById("responseErrors").innerHTML = event.message;
                }
            }, 
            {escape: true}
        );
    }   
    

  function bump2(TraId) {
    var counter3 = document.getElementById("{!$Component.form3.counter3}");
    counter3.value = TraId;
    updateState3();
}




   function getTransactionFilter2(TraFilterId) {
   
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.PBE1KRemoting_Tra.getTransactionFilter}',
            TraFilterId, 
            function(result2, event2){
                if (event2.status) {
                    // Get DOM IDs for HTML and Visualforce elements like this
             $("#TransactionTableRowTmpl").children().remove();
                 var html2 = $("#TransactionTableRowTmpl").render(result2);
                //replace the table body with rendered html              
                j$("#TransactionTableBody").html(html2);    
                  initPageBlockTableEnhancerADV();
                } else if (event2.type === 'exception') {
                    document.getElementById("responseErrors").innerHTML = 
                        event2.message + "<br/>\n<pre>" + event2.where + "</pre>";
                } else {
                    document.getElementById("responseErrors").innerHTML = event2.message;
                }
            }, 
            {escape: true}
        );
    }   


    </script>
  
    
    <!-- JS Render Template -->
    <script id="TransactionTableRowTmpl" type="text/x-jsrender">
        <tr class="dataRow" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">   
  <td class="dataCell"><button rerender="Tradetails" id="Test1"  onclick="bump2('{{>Id}}'); " >{{>Name}}</button></td>  
            <td class="dataCell">{{>Date_of_Payment__c}}</td>
            <td class="dataCell">{{>Amount__c}}</td>
            <td class="dataCell">{{>Account__c}}</td>
            <td class="dataCell">{{>Method__c}}</td>
             <td class="dataCell">{{>Service_Name__c}}</td>
              <td class="dataCell">{{>Transaction_Type__c}}</td>
               <td class="dataCell">{{>Office__c}}</td>
        </tr>
    </script>
    
    
    <c:PageBlockTableEnhancerADV targetPbTableIds="TransactionTable"/>
    <apex:pageBlock >
        <apex:sectionHeader title="Global Transactions View" subtitle="Home"/>
        <!-- Borrow some styling from Pageblock table -->
        <apex:form id="form">
<apex:selectList id="SelectMins" size="1" onchange="getTransactionFilter2(this.value); " value="{!TraFilterId}"  >
<apex:selectOptions value="{!TraFilter}"   />
</apex:selectList>
<button rerender="TransactionTable" id="Test1"  onclick="getTransactions(); " ></button>
</apex:form>
        <table class="list" border="0" cellpadding="0" cellspacing="0" id="TransactionTable">
            <thead class="rich-table-thead">
                <tr class="headerRow ">
                    <th class="headerRow">Name</th>
                    <th class="headerRow">Date</th>
                    <th class="headerRow">Amount</th>
                    <th class="headerRow">Account</th>
                    <th class="headerRow">Method</th>
                    <th class="headerRow">Service Name</th>
                    <th class="headerRow">Type</th>
                    <th class="headerRow">Office__c</th>
                </tr>
            </thead>
            <tbody id="TransactionTableBody">
            
            </tbody>     
        </table>
    </apex:pageBlock>
    




<input id="acctSearch" type="text"/>
    <button onclick="getTransaction()">Get Account</button>
    <div id="responseErrors"></div>

    <apex:pageBlock id="block">
        <apex:pageBlockSection id="blockSection" columns="2">
            <apex:pageBlockSectionItem id="firstItem">
                <span id="remoteAcctId"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem id="secondItem">
                <apex:outputText id="acctNumEmployees"/>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
          
    </apex:pageBlock>
<apex:form id="form3">
<apex:outputPanel id="Tradetails">
<apex:actionFunction name="updateState3" reRender="Tradetails"/>
<apex:inputHidden id="counter3" value="{!controllerProperty}"/>
<apex:inputHidden id="counter4" value="{!DocumentReady}"/>

<apex:detail id="Test4" subject="{!controllerProperty}" relatedList="True" inlineEdit="True" title="false"/>
<span id="Test3"/>

</apex:outputPanel>
</apex:form>
</apex:page>

and
 
public  with sharing class PBE1KRemoting_Tra {

public static Transaction__c Tra { get; set; }
public string TraId { get; set; }
public Id TraIdInsert { get; set; }



//Filter
Public String TraFilterId;

public String getTraFilterId(){return TraFilterId;}
public void setTraFilterId(String TraFilterId) {this.TraFilterId= TraFilterId;}



    @RemoteAction
    public static List<transaction__c> getTransactions(string DocumentReady){
    
    If(DocumentReady == 'True'){
  
   List<Transaction__c> Transactions = [SELECT ID, Name, Date_Of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, CreatedDate FROM Transaction__c ORDER BY Date_Of_Payment__c Desc limit 10000];
   
   If(Transactions.size() > 0){
   DocumentReady = 'False';
   return Transactions;
   }Else{
   Return null;
   }
   }Else{
   return null;
   }
   
    }
    
     @RemoteAction
    public static Transaction__c getTransaction(String TraId) {

        // Clean up the Id parameter, in case there are spaces
        // Simple SOQL query to get the warehouse data we need
        Tra = [
            SELECT ID, Name, Date_Of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, CreatedDate
            FROM Transaction__c 
            WHERE Id = :TraId]; 
                        
                      

        return(Tra);
    }
    
        @RemoteAction
    public static List<transaction__c> getTransactionFilter(String TraFilterId) {
    String Query = 'SELECT ID, Name, Date_Of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, CreatedDate FROM Transaction__c';
    String WhereQuery = TraFilterId;

if(TraFilterId != ''){
        return Database.query(Query+' '+WhereQuery);
}else{
        return Database.query(Query);

}
    }
    
    
   public String controllerProperty {get;set;}
   public string DocumentReady {get;set;}
   
    public PBE1KRemoting_Tra () {
        controllerProperty = null;
        DocumentReady = 'True';
    }
  
  
  String chicken = 'a0HN0000004ncjHMAQ';
    
    public list<selectoption> getTraFilter()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('','All'));
      options.add(new SelectOption('','EziDebit Transactions'));
      options.add(new SelectOption('a0HN0000004ncjHMAQ','Test'));
      options.add(new SelectOption('where id=\''+                                 String.escapeSingleQuotes('a0HN0000004ncjHMAQ')+'\'','Test2'));
      

   return options;
 }    
    
   
    
}

 
Hi There,

I have a page which is designed to render a table of all the records to do with my object known as transactions. I had to go down these javascript remoting path as my previous (controller based) page was beginning to run slower, it also had to paginate in order to fit all the records on the page.

I started recreating my page, but with a combination of two javascript remoting examples that I found. I managed to get the first part of it done and dusted, displaying 2000+ records on one page, but then as I tried to create a functionality similar to that of sending a param via commandlink whcih re-renders an apex detail section.

I got my code to the point where I could input create a commandlink within my table, but upon clicking it, rather than using the Id of whichever row I clciked, it simply uses the first Id of the table. Please help me make it so that, whichever row I click a commandlink, it will display the records information at the bottom of the page.

This is what I have so far

Page:
<apex:page controller="PBE1KRemoting_Tra"   tabStyle="Transaction__c">
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"/>
    <apex:includeScript value="https://rawgithub.com/BorisMoore/jsrender/master/jsrender.min.js"/>
 
    <script>
        
        function getTransactions(callback){
            Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.PBE1KRemoting_Tra.getTransactions}', 
                function(result, event){
                     callback(result);
                }, 
                {escape: false}
            );
        }
 
        
        //on document ready call query and render the template
        $(function(){
            getTransactions(function(result){
                var html = $("#TransactionTableRowTmpl").render(result);
                //replace the table body with rendered html
                $("#TransactionTableBody").html(html);
                initPageBlockTableEnhancerADV();
                
                
            });
        })
        
        
  function getTransaction() {
var TraId = document.getElementById('Test1').value;

        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.PBE1KRemoting_Tra.getTransaction}',
            TraId, 
            function(result, event){
                if (event.status) {
                    // Get DOM IDs for HTML and Visualforce elements like this
                    document.getElementById('remoteAcctId').innerHTML = result.Name
                    document.getElementById(
                        "{!$Component.block.blockSection.secondItem.acctNumEmployees}"
                        ).innerHTML = result.Account__c;
                } else if (event.type === 'exception') {
                    document.getElementById("responseErrors").innerHTML = 
                        event.message + "<br/>\n<pre>" + event.where + "</pre>";
                } else {
                    document.getElementById("responseErrors").innerHTML = event.message;
                }
            }, 
            {escape: true}
        );
    }
    </script>
    
    <!-- JS Render Template -->
    <script id="TransactionTableRowTmpl" type="text/x-jsrender">
        <tr class="dataRow" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
            <td class="dataCell"><output id="Test1" type="text">{{>Id}}</output><button onclick="getTransaction()" >Get Tra</button></td>          
            <td class="dataCell">{{>Date_of_Payment__c}}</td>
            <td class="dataCell">{{>Amount__c}}</td>
            <td class="dataCell">{{>Account__c}}</td>
            <td class="dataCell">{{>Method__c}}</td>
             <td class="dataCell">{{>Service_Name__c}}</td>
              <td class="dataCell">{{>Transaction_Type__c}}</td>
               <td class="dataCell">{{>Office__c}}</td>
        </tr>
    </script>
    
    
    
    <c:PageBlockTableEnhancerADV2 targetPbTableIds="TransactionTable"/>
    <apex:pageBlock >
        <apex:sectionHeader title="Global Transactions View" subtitle="Home"/>
        <!-- Borrow some styling from Pageblock table -->
        <table class="list" border="0" cellpadding="0" cellspacing="0" id="TransactionTable">
            <thead class="rich-table-thead">
                <tr class="headerRow ">
                    <th class="headerRow">Name</th>
                    <th class="headerRow">Date</th>
                    <th class="headerRow">Amount</th>
                    <th class="headerRow">Account</th>
                    <th class="headerRow">Method</th>
                    <th class="headerRow">Service Name</th>
                    <th class="headerRow">Type</th>
                    <th class="headerRow">Office__c</th>
                </tr>
            </thead>
            <tbody id="TransactionTableBody">
            
            </tbody>     
        </table>
    </apex:pageBlock>
    
    <apex:outputPanel id="Tradetails">
<apex:detail subject="{!$CurrentPage.parameters.Tid}" relatedList="True" inlineEdit="True" title="false"/>
</apex:outputPanel>



<input id="acctSearch" type="text"/>
    <button onclick="getTransaction()">Get Account</button>
    <div id="responseErrors"></div>

    <apex:pageBlock id="block">
        <apex:pageBlockSection id="blockSection" columns="2">
            <apex:pageBlockSectionItem id="firstItem">
                <span id="remoteAcctId"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem id="secondItem">
                <apex:outputText id="acctNumEmployees"/>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>

    
</apex:page>



Controller:
public  with sharing class PBE1KRemoting_Tra {

public static Transaction__c Tra { get; set; }
public string TraId { get; set; }

    @RemoteAction
    public static List<transaction__c> getTransactions(){
        return [SELECT ID, Name, Date_Of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, CreatedDate FROM Transaction__c ORDER BY Date_Of_Payment__c Desc limit 10000];
    }
    
     @RemoteAction
    public static Transaction__c getTransaction(String TraId) {

        // Clean up the Id parameter, in case there are spaces

        // Simple SOQL query to get the warehouse data we need
        Tra = [
            SELECT ID, Name, Date_Of_Payment__c, Amount__c, Account__c, Method__c, Service_Name__c, Transaction_Type__c, Office__c, CreatedDate
            FROM Transaction__c 
            WHERE Id = :TraId];

        return(Tra);
    }
}

this is a visualforce example of what I am trying to acheive:
<apex:pageBlockTable id="pbTra" value="{!Transactions}" var="tra" rendered="{!NOT(ISNULL(transactions))}" >
<apex:column headerValue="Transaction"  >
<apex:commandLink rerender="Tradetails" oncomplete="highlightElem(this);"> {!Tra.Name}
<apex:param name="Tid" value="{!Tra.id}"/>
</apex:commandLink>
</apex:column>


<apex:outputPanel id="Tradetails">
<apex:detail subject="{!$CurrentPage.parameters.Tid}" relatedList="True" inlineEdit="True" title="false"/>
</apex:outputPanel>




Thank you for your time.
Hi There,

I have an Account Query Controller, I was wondering if I could get a hand on how to add sorting. This is a subject that has always confused me, I figure if I can deploy and understand (to a point) a controller like this, I should be able to implement acollumn sorting function. Any help or a point in the right direction would be much appreciated.

This is my current controlle query 
 
public with sharing class Account_Query {

  Public String baseQuery = 'select ID, Name, Office__c, Account_active__c, Account_Status__c, Support_expiration__c FROM Account ORDER BY NAME ASC';
  public String AccFilterId {get; set;}
  Public Integer pageSize = 750;
  Public Integer pageNumber = 1;
  Public Integer totalPageNumber = 0;

  public Account_Query (){}

  public ApexPages.StandardSetController AccSetController {
        get{
            if(AccSetController == null){
            AccSetController = new ApexPages.StandardSetController(Database.getQueryLocator(baseQuery));
             // We have to set FilterId after Pagesize, else it will not work
              AccSetController.setPageSize(pageSize);
                if(AccFilterId != null)
                {
                  AccSetController.setFilterId(AccFilterId);
                }
            }
            return AccSetController;
        }set;
    }

  public Account_Query (ApexPages.StandardSetController c) {   }

   //Page Number - added by be   
      public Integer getPageNumber()
    {

     return AccSetController.getPageNumber();
    } 

    //Navigate to first Page
    public void firstPage()
    {
      AccSetController.first();
    }

    //Navigate to last Page
    public void lastPage()
    {
      AccSetController.last();
    }

    //Navigate to Next page
    public void next()
    {
      if(AccSetController.getHasNext())
      {
        AccSetController.next();
      }
    }

    //Navigate to Prev Page
    public void prev()
    {
      if(AccSetController.getHasPrevious())
      {
        AccSetController.previous();
      }
    }

    public List<Account> getAccounts()
    {
      return (List<Account>)AccSetController.getRecords();
    }

    //Get all available list view for Account
    public SelectOption[] getAccountExistingViews(){
        return AccSetController.getListViewOptions();
    }
   
    //Page Number total -

   
    public Integer getTotalPageNumber()
    {
    if (totalPageNumber == 0 && AccSetController.getResultSize() !=null)
    {
    totalPageNumber = AccSetController.getResultSize() / pageSize;
    Integer mod = AccSetController.getResultSize() - (totalPageNumber * pageSize);
    if (mod > 0)
    totalPageNumber++;
    }
    return totalPageNumber;
    } 
    
    
     //Prev Enabled - 
    public Boolean getPreviousButtonEnabled()
    {
    return !(AccSetController.getPageNumber() > 1);
    }
    
     //Next Disabled 
    public Boolean getNextButtonDisabled()
    {
    return ((AccSetController.getPageNumber() * AccSetController.getPageSize()) >= AccSetController.getResultSize());
    }

    /**
    * Reset List View
    */
    public PageReference resetFilter()
    {
      AccSetController = null;
        AccSetController.setPageNumber(1);
        totalPageNumber = 0;
        pageSize = 750;
        return null;
    }

}

 
Hi there,

I have a wrapper class and I am trying to test it. I need 100% as my other code coverage isa  bit lacking, but only have 73%. I am not sure if I have even set this out properly and I dont know how to test for the wrapper parts of my controller. E.G. FinLoanWrapper, any help would be muich appreciated.

Test
@isTest 
private class FinanceNew_Test{
    static testMethod void FinanceCommissionNew() {
    
     PageReference pageRef = Page.DestinyFinanceNew4;
        Test.setCurrentPage(pageRef);
    
    Office__c Office = new Office__c(Name = 'Test Pro Account');
insert Office;
Account Acc = new Account(Name = 'Test Account', office__c = Office.id);
insert Acc;
Finance__c Fin = new Finance__c(Finance_Office__c = office.id, Account__c = Acc.id);
insert Fin;
List<Finance_Loan_Security__c> FLSEC = new List<Finance_Loan_Security__c>{};
for(Integer i = 0; i < 10; i++){
        Finance_Loan_Security__c FLSE = new Finance_Loan_Security__c(Office__c = Office.id, Account__c = acc.id, No_Street__c = 'Test' + i, Finance__c = Fin.id);
        FLSEC.add(FLSE);
    }
List<Finance_Loan_Split__c> FLSPL = new List<Finance_Loan_Split__c>{};
for(Integer i = 0; i < 10; i++){
        Finance_Loan_Split__c FLS = new Finance_Loan_Split__c(Office__c = Office.id, Account__c = acc.id, Account_Number__c = 'Test' + i, Finance__c = Fin.id);
        FLSPL.add(FLS);
    }
    insert FLSPL;
    Insert FLSEC;
    
    ApexPages.currentPage().getParameters().put('FinId', Fin.id);
     ApexPages.currentPage().getParameters().put('OffId', Office.id);
      ApexPages.currentPage().getParameters().put('AccId', Acc.id);


       //this call tests the constructor:
       FinanceNew controller = new FinanceNew();
       
      
       //test building was complete
        System.assert(controller.wrappers.size()==10);
         System.assert(controller.wrappers2.size()==10);
        
        
        //call the pageReference in the class.
        controller.FinLoanCalculate();
        controller.FinSecCalculate();
        System.assert(Fin.Aggregate_Borrowings__c ==0.00);
        
        controller.addRows();
        controller.delWrapper();
        controller.addRows2();
        controller.delWrapper2();
        
        controller.saveStandard();
        controller.Cancel();



    }
}



Class
public class FinanceNew{
    
    public Finance__c Fin { get; set; }
    public Finance_Loan_Security__c LoanSecurity { get; set; }
    public Finance_Loan_Split__c LoanSplit { get; set; }
    
    
    //Wrapper multi add try to implement
     public List<FinLoanSplitWrapper> wrappers {get; set;}
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
       public List<FinLoanSecurityWrapper> wrappers2 {get; set;}
 public static Integer toDelIdent2 {get; set;}
 public static Integer addCount2 {get; set;}
 private Integer nextIdent2=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
  Id FinId = ApexPages.currentPage().getParameters().get('FinId');
   public string delId {get;set;}
 ////////////////test
 

 
 public void FinLoanCalculate()
{
nextIdent=-1;
Integer NoSplits = 0;
Decimal AggBorrowing = 0.00;
  for (FinLoanSplitWrapper wrap : wrappers)
  {
  if(wrap.FinLoanS.Loan_Amount__c == null){
  wrap.FinLoanS.Loan_Amount__c = 0.00;
  }
  AggBorrowing = AggBorrowing + wrap.FinLoanS.Loan_Amount__c;
  NoSplits = NoSplits + 1;
  nextIdent = nextIdent + 1;
  wrap.ident = nextIdent;
  }
  Fin.Number_of_Splits__c = NoSplits;
  Fin.Aggregate_Borrowings__c = AggBorrowing;


}

 public void FinSecCalculate()
{
nextIdent2=-1;
Integer NoSecurities = 0;
Decimal ValTotal = 0.00;
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
  if(wrap.FinSecS.Actual_Value__c== null){
  wrap.FinSecS.Actual_Value__c= 0.00;
  }
  ValTotal = ValTotal  + wrap.FinSecS.Actual_Value__c;
  NoSecurities = NoSecurities + 1;
  nextIdent2 = nextIdent2 + 1;
  wrap.ident2 = nextIdent2;
  }
  Fin.Number_of_Securities__c = NoSecurities;
   Fin.total_security_Value__c= ValTotal;
}



 ////////////////test









////////////////////Delete Rows
//Delete Rows 1 
public void delWrapper()
 {
  Integer toDelPos=-1;
  boolean IsInsertedRow = False;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
    if (wrappers[idx].IsInserted==true){
    IsInsertedRow = true;
    }
  }
   
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
  if(delId != null && IsInsertedRow == True){
  
  Finance_Loan_Split__c[] FLS = [select id from Finance_Loan_Split__c where id =: delId ];
    if(FLS.size() > 0){
  
  delete FLS[0];
  
  }
  }
  delId = null;
  IsInsertedRow = false;
  
 }



//Delete Rows 2
  public void delWrapper2()
 {
  boolean IsInsertedRow = False;
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers2.size(); idx++)
  {
   if (wrappers2[idx].ident2==toDelIdent2)
   {
    toDelPos=idx;
   }
    if (wrappers2[idx].IsInserted==true){
    IsInsertedRow = true;
    }
  }
   
  if (-1!=toDelPos)
  {
   wrappers2.remove(toDelPos);
  }
  if(delId != null && IsInsertedRow == True){
   Finance_Loan_Security__c[] FLSE = [select id from Finance_Loan_Security__c where id =: delId ];
         if(FLSE.size() > 0){
  
  delete FLSE[0];
  
  }
  }
 }







 //////////////////////////Add Rows
 //Add Rows 1
 public void addRows()
 {
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(integer.valueof(Fin.Number_of_Splits__c), null));
  }
 }
//Add Rows 2
 public void addRows2()
 {
  for (Integer idx=0; idx<addCount2; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(integer.valueof(Fin.Number_of_Securities__c),null));
  }
 }
  //////////////////////////Add Rows
 
 

 
 
 ////////////////Wrappers
 public class FinLoanSplitWrapper
 {
  public Finance_Loan_Split__c FinLoanS {get; private set;}
  public Integer ident {get; private set;}
  public boolean IsInserted  {get; set;}
   
  public FinLoanSplitWrapper(Integer inIdent , Finance_Loan_Split__c LoanSplit)
  {
  ident=inident;
 if(LoanSplit != null){
   FinLoans = LoanSplit; 
   IsInserted = true;    
   }else{
   FinLoanS=new Finance_Loan_Split__c(Loan_Split_Number__c=ident);
   IsInserted = false;
   }
  }
 }
  
 public class FinLoanSecurityWrapper
 {
  public Finance_Loan_Security__c FinSecS {get; private set;}
  public Integer ident2 {get; private set;}
  public boolean IsInserted  {get; set;}
   
  public FinLoanSecurityWrapper(Integer inIdent, Finance_Loan_Security__c LoanSecurity )
  {
   ident2=inIdent;
 if(LoanSecurity != null){
     FinSecS = LoanSecurity;
     IsInserted = true;  
     }else{
   FinSecS=new Finance_Loan_Security__c(Loan_Security_Number__c=ident2);
   IsInserted = false;
   }
   
   
  }
 }
  

 public FinanceNew() {
     
     Id FinId = ApexPages.currentPage().getParameters().get('FinId');
     if(FinId != null){
     Fin = [SELECT Id, Application_End_Reason__c, Financier__c, Financier_Reference__c, Application_LVR__c ,
     Total_Security_Value__c, Loan_Information__c , Account__c , Finance_Office__c, Settlement_Due__c, Finance_Clause__c, Number_of_Securities__c,Number_of_Splits__c ,
     Aggregate_Borrowings__c, Total_New_Loans__c, Application_Completed__c ,Application_Submitted__c,Conditional_Approval__c,Valuation_Completed__c,
     Unconditional_Approval__c ,Finance_Documents_Issued__c,Finance_Documents_Executed__c ,Finance_Documents_Submitted__c ,Finance_Certified__c , Finance_Settlement__c ,
     Application_End__c,Upfront_Commission_Paid__c       FROM Finance__c
                   WHERE Id = :ApexPages.currentPage().getParameters().get('FinId') ];
                
 if(wrappers == null) { 
     
      wrappers=new List<FinLoanSplitWrapper>();
      for(Finance_Loan_Split__c LoanSplit:[SELECT Id, Account__c ,Office__c, Loan_Split_Number__c, Loan_Amount__c ,Loan_Type__c,Payment_Type__c,
      Loan_Purpose__c,Comment__c, finance__c, Secondary_Purpose__c, Account_Number__c  FROM Finance_Loan_Split__c
                   WHERE finance__c  = :FinId order by Loan_Split_Number__c asc]){
                   
                   nextIdent = Integer.valueof(LoanSplit.Loan_Split_Number__c);
                   
                 wrappers.add(new FinLoanSplitWrapper(nextIdent,LoanSplit));
                   }
                   }
                  
 if(wrappers2 == null) { 
     
      wrappers2=new List<FinLoanSecurityWrapper>();
      for(Finance_Loan_Security__c LoanSecurity :[SELECT Id, Account__c ,Office__c,Loan_Security_Number__c,New_Existing__c,Estimated_Value__c,No_Street__c,
      Suburb__c,State__c ,Postcode__c ,Actual_Value__c,Valuation_Date__c , Rental_Yield__c,Finance__c,Loan_Priority__c,Title_Owner__c   FROM Finance_Loan_Security__c
                   WHERE finance__c  = :FinId order by Loan_Security_Number__c asc]){
                   
                   nextIdent2 = Integer.valueof(LoanSecurity.Loan_Security_Number__c);
                   
                 wrappers2.add(new FinLoanSecurityWrapper(nextIdent2,LoanSecurity));
                   }
                   }
                
    
     
     }else{
     Fin = new Finance__c (Number_of_Splits__c = 1,Number_of_Securities__c = 1,Aggregate_Borrowings__c = 0.00, Total_New_Loans__c = 0.00, Total_Security_Value__c = 0.00);
     Fin.Finance_Office__c = ApexPages.currentPage().getParameters().get('OffId');
     Fin.Account__c = ApexPages.currentPage().getParameters().get('AccId');
      
      
    //LoanSecurity = new Finance_Loan_Security__c ();
      wrappers=new List<FinLoanSplitWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(nextIdent++, null));
  }
      wrappers2=new List<FinLoanSecurityWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++,null));
  }

}  
      
    }
    
//////////////////////////Save and Cancel\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
    public PageReference saveStandard() {
    
    List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
 Integer SetFLS = -1;
  for (FinLoanSplitWrapper wrap : wrappers)
  {
  SetFLS = SetFLS + 1;
   wrap.FinLoanS.Loan_Split_Number__c = SetFLS;
   FLS.add(wrap.FinLoanS);
  }
  Fin.Number_of_Splits__c = SetFLS+1;

 List<Finance_Loan_Security__c> LoanSecurity =new List<Finance_Loan_Security__c>();
 Integer SetFLSE = -1;
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
   SetFLSE = SetFLSE + 1;
   wrap.FinSecS.Loan_Security_Number__c = SetFLSE;
   LoanSecurity.add(wrap.FinSecS);
  }
  Fin.Number_of_Securities__c= SetFLSE+1;
    
     try {  
      upsert Fin;
        
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        

  
  for (Finance_Loan_Split__c FinLoanSplit: FLS)
  {
  If(FinLoanSplit.Finance__c == null){
    FinLoanSplit.Finance__c = Fin.id;
    }
  If(FinLoanSplit.Account__c == null){
   FinLoanSplit.Account__c = Fin.Account__c;
   }
   If(FinLoanSplit.Office__c == null){
   FinLoanSplit.Office__c = Fin.Finance_Office__c;
   }
  }
  
    for (Finance_Loan_Security__c LoanSec: LoanSecurity)
  {
   If(LoanSec.Finance__c == null){
    LoanSec.Finance__c = Fin.id;
    }
    If(LoanSec.Account__c == null){
   LoanSec.Account__c = Fin.Account__c;
   }
   If(LoanSec.Office__c == null){
   LoanSec.Office__c = Fin.Finance_Office__c;
   }
  }            
        
        try { 
        
        upsert FLS;
        upsert LoanSecurity;
       
       
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+fin.Account__c+'&Sfdc.override=1');
        return pageRef;
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
        
        
        return null;
    
    }
    
      
    public PageReference Cancel() {
   
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+Fin.account__c+'&Sfdc.override=1');
        return pageRef;
     
    }
//////////////////////////Save and Cancel\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
//////////////////////Old Code to keep for Reference - Delete Later\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\   


  /* Remove for now, as it has been made redunant. keep for reference incase soemthing goes wrong
 public PageReference save()
 {
  List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }
   
  insert FLS;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
 */

//////////////////////Old Code to keep for Reference - Delete Later\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
 
    
}

 

Hi There,

I have a wrapper class, it is used to create a finance__c record and multiple children finance loan split and finance Loan securities. This allows me to save at once and they are all joined. 

I am attempting to make it so that the controller can be used to edit the same records. I have a roundabout idea of what I am meant to do....I have evn been able to access the main Fin record, however every attempt I have made at filling the wrapper list when accessing a record (rather than inserting)...I always get no results. Please can someone point me in the right direction of how I might access a list of already created Finance Loan split records and display them in my datatable.

thank you in advance for your time. My controller is below:

 

public class FinanceNew2{
    
    public Finance__c Fin { get; set; }
    public Finance_Loan_Security__c LoanSecurity { get; set; }
    public Finance_Loan_Split__c LoanSplit { get; set; }
    
    
    //Wrapper multi add try to implement
     public List<FinLoanSplitWrapper> wrappers {get; set;}
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
       public List<FinLoanSecurityWrapper> wrappers2 {get; set;}
 public static Integer toDelIdent2 {get; set;}
 public static Integer addCount2 {get; set;}
 private Integer nextIdent2=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
  Id FinId = ApexPages.currentPage().getParameters().get('FinId');
 ////////////////test
 
 public decimal AggregateLoanAmount{get;set;}
 public integer LoanSplitSize{get;set;}
 
 public void calculation()
{
AggregateLoanAmount = 0.00;
LoanSplitSize = 0;
  for (FinLoanSplitWrapper wrap : wrappers)
  {
  if(wrap.FinLoanS.Loan_Amount__c == null){
  wrap.FinLoanS.Loan_Amount__c = 0.00;
  }
   LoanSplitSize = LoanSplitSize + 1;
   AggregateLoanAmount = AggregateLoanAmount + wrap.FinLoanS.Loan_Amount__c;
  }
  Fin.Number_of_Securities__c = LoanSplitSize;

}

 ////////////////test









////////////////////Delete Rows
//Delete Rows 1 
public void delWrapper()
 {
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
  }
   
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
 }



//Delete Rows 2
  public void delWrapper2()
 {
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers2.size(); idx++)
  {
   if (wrappers2[idx].ident2==toDelIdent2)
   {
    toDelPos=idx;
   }
  }
   
  if (-1!=toDelPos)
  {
   wrappers2.remove(toDelPos);
  }
 }







 //////////////////////////Add Rows
 //Add Rows 1
 public void addRows()
 {
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(nextIdent++, null));
  }
 }
//Add Rows 2
 public void addRows2()
 {
  for (Integer idx=0; idx<addCount2; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++));
  }
 }
  //////////////////////////Add Rows
 
 
 
 
 
 
 
 
 
 
 
 ////////////////Wrappers
 public class FinLoanSplitWrapper
 {
  public Finance_Loan_Split__c FinLoanS {get; private set;}
  public Integer ident {get; private set;}
   
  public FinLoanSplitWrapper(Integer inIdent , Finance_Loan_Split__c LoanSplit)
  {
   Id FinId = ApexPages.currentPage().getParameters().get('FinId');
 if(LoanSplit!= null){
   FinLoans = LoanSplit;   
   ident=integer.valueof(LoanSplit.Loan_Split_Number__c);
   }else{
   FinLoanS=new Finance_Loan_Split__c(Loan_Split_Number__c=ident);
   }
   
   
  
  }
 }
  
 public class FinLoanSecurityWrapper
 {
  public Finance_Loan_Security__c FinSecS {get; private set;}
  public Integer ident2 {get; private set;}
   
  public FinLoanSecurityWrapper(Integer inIdent)
  {
   ident2=inIdent;
   FinSecS=new Finance_Loan_Security__c(Loan_Security_Number__c=ident2);
  }
 }
 
  ////////////////Wrappers











     //Wrapper multi add try to implement   
/*
    public List<FinLoanSplitWrapper> getWrappers() {
 Id FinId = ApexPages.currentPage().getParameters().get('FinId');
 if(FinId != null){
 if(wrappers == null) { 
     
      wrappers=new List<FinLoanSplitWrapper>();
      for(Finance_Loan_Split__c LoanSplit:[SELECT Id, Account__c ,Office__c, Loan_Split_Number__c, Loan_Amount__c ,Loan_Type__c,Payment_Type__c,
      Loan_Purpose__c,Comment__c
       FROM Finance_Loan_Split__c
                   WHERE Id = :FinId]){
                   
                 wrappers.add(new FinLoanSplitWrapper((integer.valueof(LoanSplit.Loan_Split_Number__c)),LoanSplit));
                   }
                   }
        
        }
        return wrappers;
    }   
   */ 
  

 public FinanceNew2() {
     
     Id FinId = ApexPages.currentPage().getParameters().get('FinId');
     if(FinId != null){
     Fin = [SELECT Id, Application_End_Reason__c, Financier__c, Financier_Reference__c, Application_LVR__c ,
     Total_Security_Value__c, Loan_Information__c , Account__c , Finance_Office__c, Settlement_Due__c, Finance_Clause__c, Number_of_Securities__c FROM Finance__c
                   WHERE Id = :ApexPages.currentPage().getParameters().get('FinId')];
                
 if(wrappers == null) { 
     
      wrappers=new List<FinLoanSplitWrapper>();
      for(Finance_Loan_Split__c LoanSplit:[SELECT Id, Account__c ,Office__c, Loan_Split_Number__c  FROM Finance_Loan_Split__c
                   WHERE Id = :FinId]){
                   
                 wrappers.add(new FinLoanSplitWrapper(null,LoanSplit));
                   }
                   }
        
        
               
     List<Finance_Loan_Security__c> LoanSecurity = [SELECT Id, Account__c ,Office__c  FROM Finance_Loan_Security__c
                   WHERE Id = :FinId];  
     
 
      wrappers2=new List<FinLoanSecurityWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++));
  }
    
     
     }else{
     Fin = new Finance__c ();
     Fin.Finance_Office__c = ApexPages.currentPage().getParameters().get('OffId');
     Fin.Account__c = ApexPages.currentPage().getParameters().get('AccId');
      
      
    //LoanSecurity = new Finance_Loan_Security__c ();
      wrappers=new List<FinLoanSplitWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(nextIdent++, null));
  }
      wrappers2=new List<FinLoanSecurityWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++));
  }

}  
      
    }
    
//////////////////////////Save and Cancel\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
    public PageReference saveStandard() {
    
    Fin.Aggregate_Borrowings__c = AggregateLoanAmount;
    
    
     try {  
      upsert Fin;
        
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
 List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }

 List<Finance_Loan_Security__c> LoanSecurity =new List<Finance_Loan_Security__c>();
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
   LoanSecurity.add(wrap.FinSecS);
  }
  
  for (Finance_Loan_Split__c FinLoanSplit: FLS)
  {
    FinLoanSplit.Finance__c = Fin.id;
   FinLoanSplit.Account__c = Fin.Account__c;
   FinLoanSplit.Office__c = Fin.Finance_Office__c;
  }
  
    for (Finance_Loan_Security__c LoanSec: LoanSecurity)
  {
    LoanSec.Finance__c = Fin.id;
   LoanSec.Account__c = Fin.Account__c;
   LoanSec.Office__c = Fin.Finance_Office__c;
  }            
        
        try { 
        
        upsert FLS;
        upsert LoanSecurity;
       
       
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+fin.Account__c+'&Sfdc.override=1');
        return pageRef;
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
        
        
        return null;
    
    }
    
      
    public PageReference Cancel() {
   
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+Fin.account__c+'&Sfdc.override=1');
        return pageRef;
     
    }
//////////////////////////Save and Cancel\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
//////////////////////Old Code to keep for Reference - Delete Later\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\   
    /* Remove for now, keep for ref
 public PageReference save2()
 {
  List<Finance_Loan_Security__c> LoanSecurity =new List<Finance_Loan_Security__c>();
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
   LoanSecurity.add(wrap.FinSecS);
  }
   
  insert LoanSecurity;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
*/

  /* Remove for now, as it has been made redunant. keep for reference incase soemthing goes wrong
 public PageReference save()
 {
  List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }
   
  insert FLS;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
 */

//////////////////////Old Code to keep for Reference - Delete Later\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
 
    
}
Hi There,

I am trying to write a test class for my Wrapper Class, unfortunately my overall code coverage pretty much borders around 75%, so I need to get 100% in order to deploy. I Finally just got it to save and pass, after hours of trial and error and it has 80%. Any tips on how to get the remaining 20% would be much appreciated.

Test
@isTest 
private class FinanceCommissionNew_Test{
    static testMethod void FinanceCommissionNew() {
    
    Office__c Office = new Office__c(Name = 'Test Pro Account');
insert Office;
Office_Commission__c OffCom = new Office_Commission__c(Commission_Period_Start__c = date.today(), Office__c = Office.id, Commission_Period_End__c = date.today()+7);
insert OffCom;


       //this call tests the constructor:
       FinanceCommissionNew FinComN = new FinanceCommissionNew();
       
       
        Finance_Commission__c FinCom = new Finance_Commission__c(Office_Name__c = Office.id, Office_Commission__c = OffCom.id, Finance_Commission_Date__c=system.today());
       //test building was complete
        System.assert(FinComN.wrappers.size()==6);
        
        
        //call the pageReference in the class.
        
        FinComN.addRows();
        FinComN.delWrapper();
        FinComN.calculation();
        
        FinComN.saveStandard();
        FinComN.Cancel();



    }
}

Wrapper class
public class FinanceCommissionNew{
    
    public Finance_Commission__c FinCom { get; set; }
   Id OfficeId = ApexPages.currentPage().getParameters().get('OffId'); 
    
    //Wrapper multi add try to implement
     public List<FinComWrapper> wrappers {get; set;}
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=1;
 
 public String FinanceCommissionsDate{get;set;}
 
 public void calculation()
{
If(FinCom.id != null){
if(FinCom.Finance_Commission_Date__c!=null){
FinanceCommissionsDate = String.Valueof(FinCom.Finance_Commission_Date__c);
FinanceCommissionsDate = FinanceCommissionsDate.substring(8, 10)+'/'+FinanceCommissionsDate.substring(5, 7)+'/'+FinanceCommissionsDate.substring(0, 4);
}
}

}
  
  
 public void delWrapper()
 {
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
  }
   
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
 }
 
  
 public void addRows()
 {
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new FinComWrapper(nextIdent++));
  }
 }

  /* Remove for now, as it has been made redunant. keep for reference incase soemthing goes wrong
 public PageReference save()
 {
  List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }
   
  insert FLS;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
 */
  
 public class FinComWrapper
 {
  public Finance_Commission__c FinCom {get; private set;}
  public Integer ident {get; private set;}
   
  public FinComWrapper(Integer inIdent)
  { 
   ident=inIdent;
   FinCom =new Finance_Commission__c(Finance_Commission_GST_Amount__c=ident);
   Id OfficeId = ApexPages.currentPage().getParameters().get('OffId');
   
If(OfficeId != null){  
FinCom.Office_Name__c = OfficeId;
}
If(ident==1){
FinCom.Finance_Commission_Type__c = 'Upfront';
FinCom.Finance_Commission_Institution__c = 'St George';
}
If(ident==2){
FinCom.Finance_Commission_Type__c = 'Upfront';
FinCom.Finance_Commission_Institution__c = 'AFG';
}
If(ident==3){
FinCom.Finance_Commission_Type__c = 'Upfront';
FinCom.Finance_Commission_Institution__c = 'DMS';
}
If(ident==4){
FinCom.Finance_Commission_Type__c = 'Trail';
FinCom.Finance_Commission_Institution__c = 'St George';
}
If(ident==5){
FinCom.Finance_Commission_Type__c = 'Trail';
FinCom.Finance_Commission_Institution__c = 'AFG';
}
If(ident==6){
FinCom.Finance_Commission_Type__c = 'Trail';
FinCom.Finance_Commission_Institution__c = 'DMS';      
}
   
  }
 }
 

     //Wrapper multi add try to implement   

    
    
    
    

 public FinanceCommissionNew() {
 
 
    FinCom = new Finance_Commission__c();
      If(OfficeId != null){
       
      FinCom.Office_Name__c = OfficeId;
      }
      
    //LoanSecurity = new Finance_Loan_Security__c ();
      wrappers=new List<FinComWrapper>();
  for (Integer idx=0; idx<6; idx++)
  {
   wrappers.add(new FinComWrapper(nextIdent++));
  }
      
    }
    
    
    public PageReference saveStandard() {
    

 List<Finance_Commission__c> FinComs =new List<Finance_Commission__c>();
  for (FinComWrapper wrap : wrappers)
  {
   FinComs.add(wrap.FinCom);
  }
  
    for (Finance_Commission__c FinCommissions: FinComs)
  {
  if(FinCom.Finance_Commission_Date__c!=null){
  
    FinCommissions.Finance_Commission_Date__c = FinCom.Finance_Commission_Date__c;
    
            }
  }            




        try { 
        
        upsert FinComs;
       
       
        PageReference pageRef= new PageReference('/apex/DestinyOffice?id='+OfficeId+'&Sfdc.override=1');
        return pageRef;
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
        
        
        return null;
    
    }
    
      
    public PageReference Cancel() {
   
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+OfficeId+'&Sfdc.override=1');
        return pageRef;
     
    }
    


 
 
    
}

 
Hi There,

I have a controller which is for an object, that has many children objects looking it up. The controller wraps the two children into a datatble. So far, everything on the page works, if I am inserting these records. I was wondering, what I would have to change within the controller, so that it can be used for editing records as well.

By editing, I essentially mean displaying the page, with all the inpput fields filled and the datatable full of child objects, how it looked just before save. I think i need to access the Fin record and all loan split and loan security records that look the Fin record up.

I am not sure how to phrase this, a point in the right direction would be much appreciated.

this is my controller:
 
public class FinanceNew{
    
    public Finance__c Fin { get; set; }
    public Finance_Loan_Security__c LoanSecurity { get; set; }
    public Finance_Loan_Split__c LoanSplit { get; set; }
    
    
    //Wrapper multi add try to implement
     public List<FinLoanSplitWrapper> wrappers {get; set;}
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
       public List<FinLoanSecurityWrapper> wrappers2 {get; set;}
 public static Integer toDelIdent2 {get; set;}
 public static Integer addCount2 {get; set;}
 private Integer nextIdent2=0;
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
 
 ////////////////test
 
 public decimal AggregateLoanAmount{get;set;}
 public integer LoanSplitSize{get;set;}
 
 public void calculation()
{
AggregateLoanAmount = 0.00;
LoanSplitSize = 0;
  for (FinLoanSplitWrapper wrap : wrappers)
  {
  if(wrap.FinLoanS.Loan_Amount__c == null){
  wrap.FinLoanS.Loan_Amount__c = 0.00;
  }
   LoanSplitSize = LoanSplitSize + 1;
   AggregateLoanAmount = AggregateLoanAmount + wrap.FinLoanS.Loan_Amount__c;
  }
  

}

 

 
 ////////////////test
 
  
 public void delWrapper()
 {
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
  }
   
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
 }
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 2
  public void delWrapper2()
 {
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers2.size(); idx++)
  {
   if (wrappers2[idx].ident2==toDelIdent2)
   {
    toDelPos=idx;
   }
  }
   
  if (-1!=toDelPos)
  {
   wrappers2.remove(toDelPos);
  }
 }
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 2
  
 public void addRows()
 {
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(nextIdent++));
  }
 }

  /* Remove for now, as it has been made redunant. keep for reference incase soemthing goes wrong
 public PageReference save()
 {
  List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }
   
  insert FLS;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
 */
  
 public class FinLoanSplitWrapper
 {
  public Finance_Loan_Split__c FinLoanS {get; private set;}
  public Integer ident {get; private set;}
   
  public FinLoanSplitWrapper(Integer inIdent)
  {
   ident=inIdent;
   FinLoanS=new Finance_Loan_Split__c(Loan_Split_Number__c=ident);
  }
 }
 
  //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 3
 public void addRows2()
 {
  for (Integer idx=0; idx<addCount2; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++));
  }
 }
 
 
/* Remove for now, keep for ref
 public PageReference save2()
 {
  List<Finance_Loan_Security__c> LoanSecurity =new List<Finance_Loan_Security__c>();
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
   LoanSecurity.add(wrap.FinSecS);
  }
   
  insert LoanSecurity;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
*/
  
 public class FinLoanSecurityWrapper
 {
  public Finance_Loan_Security__c FinSecS {get; private set;}
  public Integer ident2 {get; private set;}
   
  public FinLoanSecurityWrapper(Integer inIdent)
  {
   ident2=inIdent;
   FinSecS=new Finance_Loan_Security__c(Loan_Security_Number__c=ident2);
  }
 }
  //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 3
     //Wrapper multi add try to implement   

    
    
    
    

 public FinanceNew() {
    Fin = new Finance__c ();
    
     Fin.Finance_Office__c = ApexPages.currentPage().getParameters().get('OffId');
     Fin.Account__c = ApexPages.currentPage().getParameters().get('AccId');
    
    LoanSecurity = new Finance_Loan_Security__c ();
      wrappers=new List<FinLoanSplitWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(nextIdent++));
  }
      wrappers2=new List<FinLoanSecurityWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++));
  }


      
    }
    
    
    public PageReference saveStandard() {
    
    Fin.Aggregate_Borrowings__c = AggregateLoanAmount;
    
    
     try {  
      upsert Fin;
        
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
 List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }

 List<Finance_Loan_Security__c> LoanSecurity =new List<Finance_Loan_Security__c>();
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
   LoanSecurity.add(wrap.FinSecS);
  }
  
  for (Finance_Loan_Split__c FinLoanSplit: FLS)
  {
    FinLoanSplit.Finance__c = Fin.id;
   FinLoanSplit.Account__c = Fin.Account__c;
   FinLoanSplit.Office__c = Fin.Finance_Office__c;
  }
  
    for (Finance_Loan_Security__c LoanSec: LoanSecurity)
  {
    LoanSec.Finance__c = Fin.id;
   LoanSec.Account__c = Fin.Account__c;
   LoanSec.Office__c = Fin.Finance_Office__c;
  }            
        
        try { 
        
        upsert FLS;
        upsert LoanSecurity;
       
       
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+fin.Account__c+'&Sfdc.override=1');
        return pageRef;
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
        
        
        return null;
    
    }
    
      
    public PageReference Cancel() {
   
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+Fin.account__c+'&Sfdc.override=1');
        return pageRef;
     
    }

 
 
    
}

thank you in advance!
Hi there,

I have created a visualforce home page component. This works well, except for the odd computer screen, where the right hand side of the component is cut off. In order to see the full component, the sidebar has to be minimised. How do I make it so that the component will resize properly so that it fits fully onto the page when i extend or reduce the sidebar.

Please help, any help or tips would be very much appreciated. Visualforce page below:
 
<apex:page sidebar="true" docType="html-5.0" controller="HomePageAccountView" tabStyle="account" >  

    <script>
    $j = jQuery.noConflict();
 var newWin=null;
 function openLookupPopup(AccountID)
 {
  var url="/apex/DestinyAccount?id=" + AccountID;
    $jnewWin=window.open(url);
  if (window.focus)
  {
     $jnewWin.focus();
  }
    
     return false;
    }
      
</script>

<style>  
     .glow{  
        animation: flashBg 0.9s;  
        -webkit-animation: flashBg 0.9s alternate infinite;  
     }  
     @keyframes flashBg  
     {  
       from {  
           border: 3px solid #ff6161;  
          }  
       to {  
           border: 3px solid #ffd324;  
         }  
     }  
     @-webkit-keyframes flashBg /* Safari and Chrome */  
     {  
       from {  
           border: 3px solid #ff6161;  
          }  
       to {  
           border: 3px solid #ffd324;  
           box-shadow: 0px 0px 50px 3px #e14f1c;  
         }  
     }  
   </style>  
   <style>
.activeTab {background-color: #892034; color:White;
background-image:none;font-size:160%;border-radius:20px;}
.inactiveTab { background-color: #428BCA; color:white;
background-image:none;font-size:160%;border-radius:20px;}
.background { background-color: white; }
.rich-tabhdr-side-border { background-image: none; }
.rich-tabhdr-side-cell { border-top: none; }
.inner {
    height:160px;
    overflow:auto;
}
.header {
    position:absolute;
    top:0;
    left:0;
    overflow:hidden;
}
</style>


 <vs:importvisualstrap />  
<vs:visualstrapblock >  
<apex:tabPanel switchType="client" 
id="AccountTabPanel" tabClass="activeTab"
inactiveTabClass="inactiveTab" > 



<apex:tab labelWidth="%" style="background-color:white;border-bottom: none;border-left: none;border-right: none;" label="Prospective Client Summary" name="SummaryDetails" id="tabSummary" >
<vs:panel title="Prospective Client Summary" type="primary">  
<vs:row >  

<vs:column type="col-md-4"> 
<div style="block"  class="{!if(AccountsInquiry.size>5,"glow","none")}"   id="contentToToggle" ><vs:well style="text-align:center;">  
<vs:glyph icon="phone-alt" style="font-size:40px"/>&nbsp;
<span style="font-size:54px">
{!AccountsInquiry.size}
</span>  
<p class="text-muted">Outstanding Inquiry</p>  
</vs:well>  
</div>
</vs:column>  

 
<vs:column type="col-md-4">  
 <div style="block"     id="Glow2" >
<vs:well style="text-align:center;">  
<vs:glyph icon="book" style="font-size:40px"/>&nbsp;<span style="font-size:54px">{!AccountsPresentation.size}</span>  
<p class="text-muted">Presentation Booked</p>  
</vs:well> 
</div>
</vs:column>  

<vs:column type="col-md-4"> 
<div  id="Glow3">     
<vs:well style="text-align:center;">  
<vs:glyph icon="earphone" style="font-size:40px"/>&nbsp;
<span style="font-size:54px">{!AccountsFollowUp.size}</span>  
<p class="text-muted">Service Decision Follow-Up</p>  
 </vs:well>  
 </div>  
</vs:column>  
 
 <!--
<vs:column type="col-md-3">  
 <div style="block"  class="{!if(AccountsPresentation.size>5,"glow","none")}"   id="Glow2" >
<vs:well style="text-align:center;">  
<vs:glyph icon="book" style="font-size:40px"/>&nbsp;<span style="font-size:54px">{!AccountsPresentation.size}</span>  
<p class="text-muted">New Account List</p>  
</vs:well> 
</div>
</vs:column>  
-->


</vs:row> 
 </vs:panel> 
</apex:tab>

<apex:tab labelWidth="25%" style="background-color:white;border-bottom: none;border-left: none;border-right: none;" label="Outstanding Inquiry" name="EnquiryDetails" id="tabdetails" >
<vs:panel title="Outstanding Inquiry" type="primary">  
<div  class="{!if(AccountsInquiry.size>5,"inner","none")}"   id="FixedHeader">  
<apex:dataTable value="{!AccountsInquiry}" var="AccInqu" headerClass="Header" styleClass="table table-condensed table-hover table-bordered"  > 
<apex:column headerValue="Name"  >  
<a href="#" onclick="openLookupPopup('{!AccInqu.Id}'); return false" >{!AccInqu.name}</a>
</apex:column>  
<apex:column value="{!AccInqu.Account_Status__c }" headerValue="Status" />  
<apex:column value="{!AccInqu.Account_Inquiry_Date__c}"  headerValue="Inquiry Date" headerClass="clsCenter"/>  
<apex:column value="{!AccInqu.Initial_ContactSource__c}"  headerValue="Contact Source"/>  
<apex:column value="{!AccInqu.Initial_Destiny_Lead_Rating_c__c}"  headerValue="Lead Rating" />  
<apex:column value="{!AccInqu.Office__c}" rendered="{!($Profile.Name=='Destiny Director')||($Profile.Name=='Financial Controller')||($Profile.Name=='Head Office Support')||($Profile.Name=='System Administrator')}" headerValue="Office"/> 
</apex:dataTable> 
</div>   
<vs:alert rendered="{!AccountsInquiry.empty}" type="warning" style="text-align:center">  
<vs:glyph icon="exclamation-sign"/> No records to display  
</vs:alert>  
</vs:panel> 
</apex:tab>


<apex:tab labelWidth="25%" style="background-color:white;border-bottom: none;border-left: none;border-right: none;" label="Presentation Booked" name="Presentation Booked" id="tabPresentationBooked" >
<vs:panel title="Presentation Booked" type="primary">
<div class="{!if(AccountsPresentation.size>5,"inner","none")}"   id="FixedHeader">  
 <apex:dataTable value="{!AccountsPresentation}" var="accPres" styleClass="table table-condensed table-hover table-bordered" >  
<apex:column headerValue="Name">  
<a href="#" onclick="openLookupPopup('{!accPres.Id}'); return false" >{!accPres.name}</a>
</apex:column>  
<apex:column value="{!accPres.Account_Status__c}" headerValue="Status"/> 
<apex:column value="{!accPres.Initial_Presentation_Date__c}" headerValue="Initial Appointment Start"/>  
<apex:column value="{!accPres.Account_Inquiry_Date__c}" headerValue="Inquiry Date"/>  
<apex:column value="{!accPres.Office__c}" rendered="{!($Profile.Name=='Destiny Director')||($Profile.Name=='Financial Controller')||($Profile.Name=='Head Office Support')||($Profile.Name=='System Administrator')}" headerValue="Office"/>   
</apex:dataTable> 
</div>   
<!--
<apex:pageblock> 
<apex:pageblockTable value="{!AccountsPresentation}" var="accPres" styleClass="table table-condensed table-hover table-bordered" >  
<apex:column headerValue="Name">  
<a href="#" onclick="openLookupPopup('{!accPres.Id}'); return false" >{!accPres.name}</a>
</apex:column>  
<apex:column value="{!accPres.Account_Status__c}" headerValue="Status"/> 
<apex:column value="{!accPres.Account_Inquiry_Date__c}" headerValue="Enquired"/>  
<apex:column value="{!accPres.Office__c}" headerValue="Office"/>   
</apex:pageblockTable>
</apex:pageblock> 
-->
<vs:alert rendered="{!AccountsPresentation.empty}" type="warning" style="text-align:center">  
<vs:glyph icon="exclamation-sign"/> No records to display  
</vs:alert>      
</vs:panel> 
</apex:tab>


<apex:tab labelWidth="25%" label="Service Decision Follow-Up" style="background-color:white;border-bottom: none;border-left: none;border-right: none;" name="Account Follow-Up" id="tabAccountFollow" >
<vs:panel title="Service Decision Follow-Up" type="primary"> 
<div class="{!if(AccountsFollowUp.size>5,"inner","none")}"   id="FixedHeader">  
<apex:dataTable value="{!AccountsFollowUp}" var="AccFol" styleClass="table table-condensed table-hover table-bordered">  
<apex:column headerValue="Name">  
<a href="#" onclick="openLookupPopup('{!AccFol.Id}'); return false" >{!AccFol.name}</a>
</apex:column>  
<apex:column value="{!AccFol.Account_Status__c}" headerValue="Status"/>  
 <apex:column value="{!AccFol.Initial_Presentation_Date__c}" headerValue="Initial Appointment Start"/>  
 <!--
  <apex:column value="{!AccFol.Account_Inquiry_Date__c}" headerValue="Follow Up Date"/>  
  -->
<apex:column value="{!AccFol.Office__c}" rendered="{!($Profile.Name=='Destiny Director')||($Profile.Name=='Financial Controller')||($Profile.Name=='Head Office Support')||($Profile.Name=='System Administrator')}" headerValue="Office"/> 
</apex:dataTable>  
</div>  
<vs:alert rendered="{!AccountsFollowUp.empty}" type="warning" style="text-align:center">  
<vs:glyph icon="exclamation-sign"/> No records to display  
</vs:alert>  
</vs:panel>  
</apex:tab>



</apex:tabPanel>  
</vs:visualstrapblock>  
</apex:page>

 
Hi there,

I have a flashing .glow style. I am trying to add criteria which will make it only render when the list sizes in question are greater than 5. I have tried long and hard to find a solution to this on the internet. I was wondering if this was even possible?

I am trying to make it so that if the list, for example AccountsEnquiry was greater than 5 it would trigger the .glow style, if not then it would remain normal.

Thank you in advance for anyone that can point me in the right direction.

This is my visualforce page:

<apex:page sidebar="False" docType="html-5.0" controller="VSDashBoard2" tabStyle="account" >  
<!--


-->


    
    <script>
    $j = jQuery.noConflict();
 var newWin=null;
 function openLookupPopup(AccountID)
 {
  var url="/apex/DestinyAccount?id=" + AccountID;
    $jnewWin=window.open(url);
  if (window.focus)
  {
     $jnewWin.focus();
  }
    
     return false;
    }
      
</script>

<style>  
     .glow{  
        animation: flashBg 0.9s;  
        -webkit-animation: flashBg 0.9s alternate infinite;  
     }  
     @keyframes flashBg  
     {  
       from {  
           border: 3px solid #ff6161;  
          }  
       to {  
           border: 3px solid #ffd324;  
         }  
     }  
     @-webkit-keyframes flashBg /* Safari and Chrome */  
     {  
       from {  
           border: 3px solid #ff6161;  
          }  
       to {  
           border: 3px solid #ffd324;  
           box-shadow: 0px 0px 50px 3px #e14f1c;  
         }  
     }  
   </style>  
   <style>
.activeTab {background-color: #892034; color:White;
background-image:none;font-size:200%;border-radius:30px;}
.inactiveTab { background-color: #00204E; color:white;
background-image:none;font-size:160%;border-radius:30px;}
.rich-tabhdr-side-border { background-image: none; }
.rich-tabhdr-side-cell { border-top: none; }
</style>




   <vs:importvisualstrap />  
   
  
   <vs:visualstrapblock >  
  <apex:tabPanel switchType="client" 
id="AccountTabPanel" tabClass="activeTab"
inactiveTabClass="inactiveTab"> 
<apex:tab label="Enquiry" name="EnquiryDetails" id="tabdetails" >
 <vs:row >  
     
       <vs:column type="col-md-6"> 
         
                <vs:panel title="Accounts Enquiry" type="info">  
                <span style="color:blue" rendered="{!AccountsEnquiry.size > 3}">
          
           <vs:well style="text-align:center;">  
              <vs:glyph icon="phone-alt" style="font-size:40px"/>&nbsp;<span style="font-size:54px">{!AccountsEnquiry.size}</span>  
              <p class="text-muted">Outstand Enquiry Accounts</p>  
           </vs:well>  
            
           </span>
           <apex:dataTable value="{!AccountsEnquiry}" var="AccEnqu" styleClass="table table-condensed table-hover table-bordered" rows="3">  
                         <apex:column headerValue="Name">  
                 <a href="#" onclick="openLookupPopup('{!AccEnqu.Id}'); return false" >{!AccEnqu.name}</a>
              
             </apex:column>  
             <apex:column value="{!AccEnqu.Account_Status__c }" headerValue="Status"/>  
             <apex:column value="{!AccEnqu.Account_Inquiry_Date__c}" headerValue="Enquired"/>  
             <apex:column value="{!AccEnqu.Office__c}" headerValue="Office"/>  
           </apex:dataTable>  
           <vs:alert rendered="{!AccountsEnquiry.empty}" type="warning" style="text-align:center">  
             <vs:glyph icon="exclamation-sign"/> No records to display  
           </vs:alert>  
         </vs:panel>  
         
       
       </vs:column>  
 
       <vs:column type="col-md-6">  
   
  <vs:panel title="Accounts Presentation Booked" type="primary">
   <div class="glow" rendered="{!AccountsPresentation.size!=0}"> 
         <vs:well style="text-align:center;">  
              <vs:glyph icon="book" style="font-size:40px"/>&nbsp;<span style="font-size:54px">{!AccountsPresentation.size}</span>  
              <p class="text-muted">Outstand Enquiry Accounts</p>  
           </vs:well> 
              </div>   
           <apex:dataTable value="{!AccountsPresentation}" var="accPres" styleClass="table table-condensed table-hover table-bordered" >  

           
           
             <apex:column headerValue="Name">  
                 <a href="#" onclick="openLookupPopup('{!accPres.Id}'); return false" >{!accPres.name}</a>
              
             </apex:column>  
             <apex:column value="{!accPres.Account_Status__c}" headerValue="Status"/> 
                          <apex:column value="{!accPres.Account_Inquiry_Date__c}" headerValue="Enquired"/>  
             <apex:column value="{!accPres.Office__c}" headerValue="Office"/>   
           </apex:dataTable>  
           <vs:alert rendered="{!AccountsPresentation.empty}" type="warning" style="text-align:center">  
             <vs:glyph icon="exclamation-sign"/> No records to display  
           </vs:alert>      
        
         </vs:panel> 
               
       </vs:column>  
            </vs:row>  

</apex:tab>
<apex:tab label="Presentation booked" name="Account Presentation" id="tabDestinyPresentation" >
    
        <vs:row >  
       <vs:column type="col-md-6">  
    
         
       <vs:panel title="Accounts FollowUp" type="primary"> 
     <div class="glow" rendered="{!AccountsFollowUp.empty}">     
 <vs:well style="text-align:center;">  
 
               
  <vs:glyph icon="earphone" style="font-size:40px"/>&nbsp;
  <span style="font-size:54px">{!AccountsFollowUp.size}</span>  
              <p class="text-muted">Outstand Enquiry Accounts</p>  
           
           
           </vs:well>  
             </div>  

           
           <apex:dataTable value="{!AccountsFollowUp}" var="AccFol" styleClass="table table-condensed table-hover table-bordered" rows="3">  
             <apex:column headerValue="Name">  
                 <a href="#" onclick="openLookupPopup('{!AccFol.Id}'); return false" >{!AccFol.name}</a>
              

             </apex:column>  
             <apex:column value="{!AccFol.Account_Status__c}" headerValue="Status"/>  
                          <apex:column value="{!AccFol.Account_Inquiry_Date__c}" headerValue="Enquired"/>  
             <apex:column value="{!AccFol.Office__c}" headerValue="Office"/>  
           </apex:dataTable>  
           <vs:alert rendered="{!AccountsFollowUp.empty}" type="warning" style="text-align:center">  
             <vs:glyph icon="exclamation-sign"/> No records to display  
           </vs:alert>  
         </vs:panel>  
                  
              

       </vs:column> 
       
        <vs:column type="col-md-6">  
       
       <vs:panel title="Accounts FollowUp" type="primary"> 

 <vs:well style="text-align:center;">  
              <vs:glyph icon="earphone" style="font-size:40px"/>&nbsp;<span style="font-size:54px">{!AccountsFollowUp.size}</span>  
              <p class="text-muted">Outstand Enquiry Accounts</p>  
           </vs:well>  
           <apex:dataTable value="{!AccountsFollowUp}" var="AccFol" styleClass="table table-condensed table-hover table-bordered" rows="3">  
             <apex:column headerValue="Name">  
                 <a href="#" onclick="openLookupPopup('{!AccFol.Id}'); return false" >{!AccFol.name}</a>
              

             </apex:column>  
             <apex:column value="{!AccFol.Account_Status__c}" headerValue="Status"/>  
                          <apex:column value="{!AccFol.Account_Inquiry_Date__c}" headerValue="Enquired"/>  
             <apex:column value="{!AccFol.Office__c}" headerValue="Office"/>  
           </apex:dataTable>  
           <vs:alert rendered="{!AccountsFollowUp.empty}" type="warning" style="text-align:center">  
             <vs:glyph icon="exclamation-sign"/> No records to display  
           </vs:alert>  
         </vs:panel>  
       
              

       </vs:column>               
     </vs:row>  
     </apex:tab>
    <!-- 
     <vs:row >  
     
       <vs:column type="col-md-6">  
                <vs:panel title="Tasks" type="primary">  
           <vs:well style="text-align:center;">  
              <vs:glyph icon="tasks" style="font-size:40px"/> &nbsp;<span style="font-size:54px">{!Tasks.size}</span>  
              <p class="text-muted">Tasks due for Today</p>  
           </vs:well>  
           <apex:dataTable value="{!Tasks}" var="task" styleClass="table table-condensed table-hover table-bordered" rows="3">  
             <apex:column headerValue="Subject">  
               <apex:outputLink value="/{!task.Id}">{!task.Subject}</apex:outputLink>  
             </apex:column>  
             <apex:column value="{!task.Status}" headerValue="Status"/>  
             <apex:column value="{!task.ActivityDate}" headerValue="Due Date"/>  
           </apex:dataTable>  
           <vs:alert rendered="{!Tasks.empty}" type="success" style="text-align:center">  
             <vs:glyph icon="ok-sign"/> No records to display  
           </vs:alert>  
         </vs:panel>  
       </vs:column>  
       
       <vs:column type="col-md-6">  
                <vs:panel title="Events" type="primary">  
           <vs:well style="text-align:center;">  
              <vs:glyph icon="briefcase" style="font-size:40px"/>&nbsp;<span style="font-size:54px">{!Events.size}</span>  
              <p class="text-muted">Future Office Events</p>  
           </vs:well>  
           <apex:dataTable value="{!Events}" var="Event" styleClass="table table-condensed table-hover table-bordered" rows="3">  
             <apex:column headerValue="Event">  
               <apex:outputLink value="/{!Event.Id}">test</apex:outputLink>  
             </apex:column>  
             <apex:column value="{!Event.subject}" headerValue="Subject"/>  
             <apex:column value="{!Event.ActivityDate}" headerValue="Date"/>  
           </apex:dataTable>  
           <vs:alert rendered="{!Events.empty}" type="warning" style="text-align:center">  
             <vs:glyph icon="exclamation-sign"/> No records to display  
           </vs:alert>  
         </vs:panel>  
       
       </vs:column> 
       
      
     </vs:row>  
      -->
     </apex:tabPanel>  
   </vs:visualstrapblock>  
 
   <!--
   <iframe id="iframeID" src="/01Z90000000AWM8"/>
   
   -->
 </apex:page>

Hi Guys and girls,

I have recently written my very first scheduled apex class. This is my first one ever, so far it seems to work. I am trying to write a test class, but I am coming with issues, mainly with code coverage. I cannot write  a test capable of passing or if it does pass, it will only test like 24%. 

I was hoping to maybe get some tips on:

* My class, any issues that might present themselves

*Perhaps a method of only adding records that have been changed by class to list for update? or does it not matter really?

*Help to write my test class so that it passes atleast 75%

Please any help would be very much appreciated. Thank you in advance.

This is my scheduled apex class:

 

**
* To schedule the Daily reconciliation:
*    NOTE: It should run at midnight every day on it's own, but if you make
*    changes and need to requeue run the command below from the developer's console
*
*    scheduledMonthly.scheduleIt();
*    NOTE: This class is designed to replace the ServiceSupportReview Time based workflows.
*/
 
global class scheduledDaily_ServiceSupportReviews implements Schedulable {
  public static String CRON_EXP = '0 0 15 * * ? *';

    
    global static String scheduleIt() {
        scheduledDaily_ServiceSupportReviews  sm = new scheduledDaily_ServiceSupportReviews ();
        return System.schedule('Daily Reconciliation', CRON_EXP, sm);
    }

    
    global void execute(SchedulableContext sc) {
        //Code goes here
        
         List<Service__c> Servs = new List<Service__c>();
         
         Date TodayDate = date.today();

         

    for(Service__c S : [SELECT id, Service_Name__c, End_of_Service_Support__c, X30Days_Review__c, X60Days_Review__c, X40DaysBefore_Review__c, X270Days_Review__c, X180Days_Review__c, X90Days_Review__c,  Start_of_Service__c, Account__c FROM Service__c where service_active__c = true]){
    
    If(S.Service_Name__c == 'Intensive Property Coaching'){
     //30 Days support Review boolean
      if ((S.End_of_Service_Support__c).addDays(-335) == date.today() && S.X30Days_Review__c == false) {
        S.X30Days_Review__c = true;
      
    //60 Days support Review boolean  
      } else if ((S.End_of_Service_Support__c).addDays(-305) == date.today() && S.X60Days_Review__c == false) {
        S.X60Days_Review__c = True;
    
    }
    }
    
    If(S.Service_Name__c != 'Essential Property Education Only'){
    //90 Days support Review boolean
      if ((S.End_of_Service_Support__c).addDays(-275) == date.today() && S.X90Days_Review__c == false) {
        S.X90Days_Review__c = true;
      
    //180 Days support Review boolean  
      } else if ((S.End_of_Service_Support__c).addDays(-185) == date.today() && S.X180Days_Review__c == false) {
        S.X180Days_Review__c = True;
        
    //270 Days support Review boolean   
      } else if ((S.End_of_Service_Support__c).addDays(-95) == date.today() && S.X270Days_Review__c == false) {
        S.X270Days_Review__c = true;
    
    //40 Days before end of support
     } else if ((S.End_of_Service_Support__c).addDays(-40) == date.today() && S.X40DaysBefore_Review__c == false) {
        S.X40DaysBefore_Review__c = true;
 
      }
      }
      
      //Add altered services to a list
      
    
      Servs.add(S);
     
    }
    
    
    if (!Servs.isEmpty()) {   
    update Servs;
 }
    
    
    
}
}
 



This is my attempt at a test:
(Currently getting error - System.AsyncException: Based on configured schedule, the given trigger will never fire.

@isTest
                                
private class TestSchedulableClass {

   // CRON expression: midnight on March 15.
   // Because this is a test, job executes
   // immediately after Test.stopTest().
   public static String CRON_EXP = '0 0 15 15 03 ? 2015';

   static testmethod void test() {
   
   Account acc = new Account(Name = 'Test Schedule Account');
    insert acc;
   Service__c serTest = new Service__c(Account__c = acc.id);
      Test.startTest();

      // Schedule the test job
      String jobId = System.schedule('ScheduleApexClassTest',
                        CRON_EXP, 
                        new scheduledDaily_ServiceSupportReviews());
         
      // Get the information from the CronTrigger API object
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, 
         NextFireTime
         FROM CronTrigger WHERE id = :jobId];

      // Verify the expressions are the same
      System.assertEquals(CRON_EXP, 
         ct.CronExpression);

      // Verify the job has not run
      System.assertEquals(0, ct.TimesTriggered);

      // Verify the next time the job will run
      System.assertEquals('2015-03-15 15:00:00', 
         String.valueOf(ct.NextFireTime));
      // Verify the scheduled job hasn't run yet.
      Service__c [] S = [SELECT id, Service_Name__c, End_of_Service_Support__c, X30Days_Review__c, X60Days_Review__c, X40DaysBefore_Review__c, X270Days_Review__c, X180Days_Review__c, X90Days_Review__c,  Start_of_Service__c, Account__c FROM Service__c where service_active__c = true];
      System.assertEquals(S.size(),0);
      Test.stopTest();

      // Now that the scheduled job has executed after Test.stopTest(),
      //   fetch the new merchandise that got added.
     // System.assertEquals(ml.size(), 1);

   }
   
   }
 



 

Hi there,

I am (trying) to create a trigger which will create support review tasks for users. The support review tasks are created when checkboxes are set to true. These checkboxes are set to true via a timebased trigger. 


I was hoping to get some people with more experience than myself to look at my code and offer their tips. The main thing I am worried about it, is tasks being set multiple times. As the criteria will be 90day review = true, etc. Will my trigger create a task for all those set as true? Or will it only create the tasks as the checkboxes are set to true. 

any help or tips would be very much appreciated. Thank you so much for your time.

 

Schema.DescribeSObjectResult d = Task.sObjectType.getDescribe();
        Map<String,Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();
        Schema.RecordTypeInfo recordType =  rtMapByName.get('Arrange Support Review');
        Id ArrangeRecId = recordType.getRecordTypeId();
        
        List<Task> TaskToInsert = new List<Task>();

    Set<Id> TaskaccountIds = new Set<Id>();
    for (Service__c Ser : trigger.new) {
    if(Ser.Start_of_Service__c != null){
        TaskaccountIds.add(Ser.Account__c);
}
}
 /*
    List<Account> Seraccounts = [SELECT Id, (SELECT Id from Service__c) FROM Account WHERE Id IN :TaskaccountIds ];
    Map<Id, List<Service__c>> SeraccountMap = new Map<Id, List<Service__c>>();
    for (Account acct : Seraccounts) {
        List<Service__c> Services = new List<Service__c>();
        for (Service__c S : acct.Services) {
            contacts.add(S);
        }
        SeraccountMap.put(acct.Id, Services );
    }*/

    
   for (Service__c Ser : trigger.new) {
If(Trigger.oldmap.get(ser.id).X160Days_Review__c != ser.X160Days_Review__c || Trigger.oldmap.get(ser.id).X180Days_Review__c != ser.X180Days_Review__c || Trigger.oldmap.get(ser.id).X270Days_Review__c != ser.X270Days_Review__c || Trigger.oldmap.get(ser.id).X30Days_Review__c != ser.X30Days_Review__c || Trigger.oldmap.get(ser.id).X320Days_Review__c != ser.X320Days_Review__c || Trigger.oldmap.get(ser.id).X60Days_Review__c != ser.X60Days_Review__c || Trigger.oldmap.get(ser.id).X90Days_Review__c != ser.X90Days_Review__c ){
if(Ser.Start_of_Service__c != null){

 Task task = new task ();
 Task.RecordTypeID = ArrangeRecId;
 task.WhatId = Ser.Account__c;
 Task.IsReminderSet = True;
 Task.ReminderDateTime = system.now();
 Task.Priority = 'Normal';
 Task.Type = 'Call';
 Task.Status = 'Not Started';


           //30 Day Review
          If(Trigger.oldmap.get(ser.id).X30Days_Review__c != ser.X30Days_Review__c && Ser.X30Days_Review__c == True){  
           task.ActivityDate = Ser.Start_of_Service__c.AddDays(35);
           task.Subject = 'Arrange Support Review30Days';
            }
            
           //60 Day Review
          else If(Trigger.oldmap.get(ser.id).X60Days_Review__c != ser.X60Days_Review__c && Ser.X60Days_Review__c == True){ 
           task.ActivityDate = Ser.Start_of_Service__c.AddDays(65);
           task.Subject = 'Arrange Support Review60Days';
            }
            //90 Day Review
            else If(Trigger.oldmap.get(ser.id).X90Days_Review__c != ser.X90Days_Review__c && Ser.X90Days_Review__c == True){ 
            task.ActivityDate = Ser.Start_of_Service__c.AddDays(95);
           task.Subject = 'Arrange Support Review90Days';
            }
            //160 Day Review
             else If(Trigger.oldmap.get(ser.id).X160Days_Review__c != ser.X160Days_Review__c && Ser.X160Days_Review__c == True){ 
            task.ActivityDate = Ser.Start_of_Service__c.AddDays(165);
           task.Subject = 'Arrange Support Review160Days';
            }
            //180 Day Review
             else If(Trigger.oldmap.get(ser.id).X180Days_Review__c != ser.X180Days_Review__c && Ser.X180Days_Review__c == True){ 
            task.ActivityDate = Ser.Start_of_Service__c.AddDays(185);
           task.Subject = 'Arrange Support Review180Days';
            }
             //270 Day Review
             else If(Trigger.oldmap.get(ser.id).X270Days_Review__c != ser.X270Days_Review__c && Ser.X270Days_Review__c == True){ 
            task.ActivityDate = Ser.Start_of_Service__c.AddDays(275);
           task.Subject = 'Arrange Support Review270Days';
            }
             //320 Day Review
             else If(Trigger.oldmap.get(ser.id).X320Days_Review__c != ser.X320Days_Review__c && Ser.X320Days_Review__c == True){ 
            task.ActivityDate = Ser.Start_of_Service__c.AddDays(325);
           task.Subject = 'Arrange Support Review320Days';
            }
           
     task.ActivityDate = date.today()+2;
     task.Subject = 'Call Prospective Client';
     

     taskToInsert.add(task);
    }//end Finance Only If
    
    }
    
   
   }//end for o
  
  
  
  
   try {
    insert taskToInsert;
   }
   catch (system.Dmlexception e) {
    system.debug (e);
   }

Hi There, 

I have an issue, I have a timebased workflow which is designed to create tasks at certain periods of time within a 12 month period for the account owner, this is based on a clients support expiration. I came into an issue when it started creating multiple versions of the same task, not just for the account owner but for other users(users that do not even have access to the accounts that they have had tasks created for). 

 

I submitted a case and was told that the issue is more than likely within my task trigger, obviously this wasnt very helpful. This is an annoying bug as my users are constantly getting notifications for accounts that they cannot even access, this looks bad on me. I do not see how my code could be creating multiple tasks, I feel like it is a brush off.

This is my task trigger, the only bit that pertains to the created tasks records appears in the before insert trigger, it records the task.whatid as it is originally created from the service object, it reassigns it to account.

Please help, I am so lost. Any help would be much appreciated.


 

trigger TaskTrigger on Task(before update,before insert, before delete, after update, after insert, after delete) {



//Create Lists
List<Account_Status__c> AccSt = new List<Account_Status__c>();
List<Account_Status__c> updatedAccSt = new List<Account_Status__c>();

List<Service__c> SerList = new List<Service__c>();
List<Task> TaskUpdate = new List<Task>();
List<Id> Serids = new List<Id>();

List<Id> accIds = new List<Id>();
//Account list for adding associated contacts
List<Id> AccountIds = new List<Id>();
List<Task> TaskToInsert = new List<Task>();
//Map Record Types
Schema.DescribeSObjectResult d = Task.sObjectType.getDescribe();
Map<String,Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();

//Upload Authority Form Map
Schema.RecordTypeInfo UploadRecType =  rtMapByName.get('Upload Authority Form');
Id UploadRecId = UploadRecType.getRecordTypeId();

//Initial Contact Prospective Client Map
Schema.RecordTypeInfo ContactRecType =  rtMapByName.get('Initial Contact Prospective Client');
Id InitialRecId = ContactRecType.getRecordTypeId();

//Initial Contact Prospective Client - Follow Up Map
Schema.RecordTypeInfo ContactFollowRecType =  rtMapByName.get('Initial Contact Prospective Client - Follow Up');
Id InitialFollowRecId = ContactRecType.getRecordTypeId();

//Arrange Support Review Map
Schema.RecordTypeInfo ReviewRecType =  rtMapByName.get('Arrange Support Review');
Id ReviewRecId = ReviewRecType.getRecordTypeId();

if(trigger.isbefore){
if(trigger.isdelete){

//Delete prevention
 String ProfileId = UserInfo.getProfileId();  
   List<Profile> profiles=[select id from Profile where name='System Administrator'];
   

   if (1!=profiles.size())
   {
      // unable to get the profiles - handle error
   }
   else
   {
       for (Task a : Trigger.old)      
       {            
          if ( profileId!=profiles[0].id )
          {
          
          
           a.addError('You do not have the level of access to delete this Activity Record. Please contact your system Administrator or set the Task to "Completed"');
          }
       }            
   }



}
if(trigger.isinsert){
//before insert logic




//Upload Authority Form Record RecordType field set
for (Task Tas: trigger.new){


//Call Prospective Client RecordSet
if (Tas.Subject == 'Call Prospective Client') {
Tas.RecordTypeID = InitialRecId;
Tas.Type = 'Call';
Tas.Status = 'Not Started';
if (Tas.Priority == 'High') {
Tas.Assigned_to__c = True;
}
tas.IsReminderSet = True;
tas.ReminderDateTime = system.now();


}

//Arrange Support Review RecordSet
if((Tas.Subject == 'Arrange Support Review'||Tas.Subject == 'Arrange Support Review90Days'||Tas.Subject == 'Arrange Support Review180Days'||Tas.Subject == 'Arrange Support Review270Days'||Tas.Subject == 'Arrange Support Review30Days'||Tas.Subject == 'Arrange Support Review60Days')&&Tas.Priority == 'Normal') {
SerIds.add(tas.whatId);

}
//Upload Authoirty Form RecordSet Support Continuation
if(tas.WhatId != null && Tas.Subject == 'Upload Authority Form_Continuation') {
Tas.RecordTypeID = UploadRecId;
Tas.Type = 'Document Upload';
Tas.Status = 'Awaiting Form';
tas.IsReminderSet = True;
tas.ReminderDateTime = system.now();

}
//Upload Authority Form RecordSet
if(tas.WhatId != null && Tas.Subject == 'Upload Authority Form') {
Tas.RecordTypeID = UploadRecId;
Tas.Type = 'Document Upload';
Tas.Status = 'Awaiting Form';
tas.IsReminderSet = True;
tas.ReminderDateTime = system.now();
accIds.add(tas.whatId);
}


}
//Find related Account Status record
AccSt = [Select Id,Account_Status__c from Account_Status__c WHERE Account__c in :accIds];
SerList = [select id, Account__c from Service__c where id in :SerIds];

for (Task Tas: trigger.new){
for(Service__c Ser : SerList ){
if ((Tas.Subject == 'Arrange Support Review'||Tas.Subject == 'Arrange Support Review90Days'||Tas.Subject == 'Arrange Support Review180Days'||Tas.Subject == 'Arrange Support Review270Days'||Tas.Subject == 'Arrange Support Review30Days'||Tas.Subject == 'Arrange Support Review60Days')&&Tas.Priority == 'Normal') {
Tas.RecordTypeID = ReviewRecId;
Tas.Type = 'Call';
Tas.Status = 'Not Started';
tas.IsReminderSet = True;
tas.ReminderDateTime = system.now();
Tas.Whatid = Ser.Account__c;
}
}
}

for(Account_Status__c a : AccSt)
{
//Set Account Status and input Date
a.Account_Status__c = 'Service Decision Yes: Awaiting Authority Form';
a.Decision_Yes_Awaiting_Authority_Form__c =  date.today();
updatedAccSt.add(a);
}




//Check that Account Status List has been altered and update
if(updatedAccSt.size()>0)
{
update updatedAccSt;
}
}



else if(trigger.isupdate){

//before update logic
for (Task  tas: trigger.new) {
if(tas.WhatId != null && (Tas.Subject == 'Call Prospective Client'||Tas.subject == 'Call Prospective Client - Follow Up')) {
accIds.add(tas.whatId);
}
if(tas.WhatId != null && Tas.Subject == 'Upload Authority Form') {
accIds.add(tas.whatId);
}
if(tas.WhatId != null && Tas.Subject == 'Destiny Presentation Follow Up') {
accIds.add(tas.whatId);
}
}
//Find related Account Status record
AccSt = [Select Id,Account_Status__c from Account_Status__c WHERE Account__c in :accIds];
for(Account_Status__c a : AccSt)
{
for (Task  tas: trigger.new) {
if(Tas.Appointment_Decision__c == 'No' && Tas.Status == 'Completed') {
a.Account_Status__c = 'Enquiry Contacted by Office: No Presentation';
a.Enquiry_Contacted_No_Presentation__c =  date.today();
}
if(Tas.Appointment_Decision__c == 'Maybe'  && Tas.Status == 'Completed') {
Datetime dt = Tas.Follow_Up_Datetime__c;

a.Account_Status__c = 'Enquiry Contacted by Office: Awaiting Follow up';
a.Enquiry_Contacted_by_Office_Maybe__c =  date.today();

 //Create Follow Up Task
       Task Task = new Task();
       Task.RecordTypeID = InitialFollowRecId;
       Task.subject = 'Call Prospective Client - Follow Up';
       Task.Type = 'Call';
       Task.Status = 'Not Started';
       Task.ActivityDate = Tas.Follow_Up_Datetime__c.date();
       Task.Follow_Up_Datetime__c = Tas.Follow_Up_Datetime__c;
       Task.WhatId = Tas.WhatId;
       Task.OwnerId = Tas.OwnerId;
       If(Tas.WhoID != null){
       Task.Whoid = Tas.whoid;
       task.IsReminderSet = True;
       task.ReminderDateTime = system.now();
       }
       taskToInsert.add(Task);

}
if(Tas.Appointment_Decision__c == 'Yes'  && Tas.Status == 'Completed') {
a.Account_Status__c = 'Presentation Decision - Yes: Awaiting Booking';
a.Presentation_Decision_Yes_Awaiting_Book__c =  date.today();
}
if(Tas.Status == 'Document Uploaded') {
a.Account_Status__c = 'Authority Form received Office: Uploaded to Account';
a.Authority_Form_received_Office_Uploaded__c =  date.today();
}
If(Tas.Status == 'Not Proceeding'){
a.Account_Status__c = 'Destiny Presentation: Service Decision - No';
a.Destiny_Presentation_Service_Decision_N0__c = date.today();

}
if(Tas.Destiny_Service_Decision__c == 'No' && Tas.Subject == 'Destiny Presentation Follow Up'  && Tas.Status == 'Completed') {
       a.Account_Status__c = 'Destiny Presentation Follow-up: Service Decision - No';
       a.Destiny_Presentation_Service_Decision_N0__c = date.today();
       } 
}
updatedAccSt.add(a);

}
if(updatedAccSt.size()>0){

update updatedAccSt;
}
insert taskToInsert;
}
}

else if(trigger.isafter){
if(trigger.isinsert){
//after Insert logic


    }

}

}

Hi There,

I have an extension and a test class. I have always managed to just scrape by with my tests, despite not always reaching 100%. This extension I have created, I recently added the ability to add an event in a different timezone, however upon testing it, it only passes at 54%. I have tested all the major page references, but I think it is failing as I am not sure how to set the strings and all the gets. This is just hypothesis. Any help would be much appreciated in completing my test class.

 

static testMethod void TestExtSaveEveButton(){


Profile Profile1 = [select id from profile where name='System Administrator'];
Account acc = new Account(Name = 'Test Eve Account');
insert acc;

User use = new User(alias = 'ceo', email='admin@testorg.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', 
        timezonesidkey='America/Los_Angeles', username='adminEve@testorg.com', profileid = Profile1.Id);
insert use;

//Now lets create Destiny Products record that will be reference for the Standard Account
        Event EveTest = new Event (WhatId = acc.id, OwnerId = use.id, subject = 'call', StartDateTime = System.now(), TimeZone_Different__c = False, EndDateTime = System.now()+3);
        Event entTest = new Event (WhatId = acc.id, OwnerId = use.id, subject = 'call', TimeZone_Different__c = True, Contact_TimeZone__c = 'Australia/Brisbane', StartDateTime = System.now(), EndDateTime = System.now()+3);
        
        //call the apepages stad controller
        Apexpages.Standardcontroller stdEve = new Apexpages.Standardcontroller(EveTest);
        ApexPages.currentPage().getParameters().put('clone', '1');

//now call the class and reference the standardcontroller in the class.
        ExtSaveEveButton extEve = new ExtSaveEveButton(stdEve);

//call the pageReference in the class.
        extEve.eve.IsReminderSet = true;
        string hours = '11';
        
        extEve.getTimes();
        extEve.getHours();
        extEve.getMins();
        extEve.getAMPM();
        
        extEve.getStartTime();
        extEve.getStartHours();
        extEve.getStartMins();
        extEve.getStartAMPM();
        extEve.getStartDate();
        extEve.getEndTime();
        extEve.getEndHours();
        extEve.getEndMins();
        extEve.getEndAMPM();
        extEve.getEndDate();
        extEve.getReminderTime();
        extEve.getReminderHours();
        extEve.getReminderMins();
        extEve.getReminderAMPM();
        extEve.getReminderDate();
        extEve.saveDestinyEvent();
        extEve.cancelDestinyEvent();
        extEve.saveSendFollowUpConfirmEmail();
        extEve.saveSendAppConfirmEmail();
        extEve.saveSendAppConfirmEmailVirtual();
        extEve.saveSerDecisionYesEPE();
        extEve.saveSendServiceDecisionNoEmail();
         extEve.saveNewDestinyEvent();
         extEve.saveSendEmail();
    

       
        
        Apexpages.Standardcontroller stdent = new Apexpages.Standardcontroller(entTest);
         extSaveEveButton extent = new extSaveEveButton (stdent);
         extent.eve.IsReminderSet = true;
                 extEve.getTimes();
        extent.getHours();
        extent.getMins();
        extent.getAMPM();
        extent.getStartTime();
        extent.getStartHours();
        extent.getStartMins();
        extent.getStartAMPM();
        extent.getStartDate();
        extent.getEndTime();
        extent.getEndHours();
        extent.getEndMins();
        extent.getEndAMPM();
        extent.getEndDate();
        extent.getReminderTime();
        extent.getReminderHours();
        extent.getReminderMins();
        extent.getReminderAMPM();
        extent.getReminderDate();
        extent.saveDestinyEvent();
        extent.cancelDestinyEvent();
         extent.saveNewDestinyEvent();
         extent.saveSendEmail();
         extent.saveSendAppConfirmEmail();
         extent.saveSendAppConfirmEmailVirtual();
         extent.saveSendFollowUpConfirmEmail();
          extent.saveSendServiceDecisionNoEmail();
          extent.saveSerDecisionYesEPE();
     
}

and my extension in the next post
 
Hi THere,

I was hoping to get a hand, I have workflow rules, one which creates a task at certain times throughout a users support and the other that sends them survey emails throughout their support. My isssues,

The task is set to be assigned to the account owner, however multiple tasks are created for a variety of users when it occurs.

The other segment is to update a picklist, this picklist sends out a different email depending on the value. These are two separate rules, but this also seems to be triggering multiple times, as clients are receiving 5 emails.

Please help me to solve this problem, it looks really bad on me as the developer and I have tried everything, I have even attached a boolean to the email trigger, which is set to true by the workflow and false by the trigger.

What can i do?
Hi Guys,

I have attempted to make a tool which converts a datetime based on timezone. I had an diea, but I have reached a few snags, I was hoping I could get a hand. 

Problem 1. I have tried Adding this to my event extension class (code 1), except whenever I load the Page it says invalid runtime error between Event and user. I am not sure if I need to access User in order to create the timezone picklist. Is there a way to get this picklist on an event page, without having to access the User object?

Problem 2: I figure the best method is to find your own timezone offset, remove your offset from the time and then add the offset of the timezone you select from the timezone picklist. Sounds simple enough in theory, but actually implementing it is hard. Please any advice or help in solving this problem would eb appreciated.

Goal:  Have picklist on event page, picklist will render when a checkbox (Different_Timezone__c) is checked, this will also be the criteria which will fill another two datetime fields which are the converted times of the start and end date time.

CODE 1
 
Public class extSaveEveButton {


public Event Eve {get;set;}

Datetime mydate = System.now();

String S = mydate.format('dd/MM/yyyy');
String T = mydate.format(' hh:mm aa');
String H = T.substring(1, 3);
String M = T.substring(4, 6);
String AMPM = T.substring(7, 9);


//Introduce strings and set format
//Start
String st = T;
String sh = H;
String sm = M;
String sAMPM = AMPM;
String sd = S;
//End
String et = T;
String eh = H;
String em = M;
String eAMPM = AMPM;
String ed = S;
//Reminder
String rt = T;
String rh = H;
String rm = M;
String rAMPM = AMPM;
String rd = S;
//Follow-Up
String ft = T;
String fh = H;
String fm = M;
String fAMPM = AMPM;
String fd = S;

//Sets Standard Controller
public extSaveEveButton (ApexPages.StandardController controller) {
this.Eve = (Event)controller.getRecord();


}

//Retrieve instance of strings within VF page
//Start
//Time
//Hours
public String getStartHours(){return sh;}
public void setStartHours(String sh) {this.sh = sh;}
//Mins
public String getStartMins(){return sm;}
public void setStartMins(String sm) {this.sm = sm;}
//AMPM
public String getStartAMPM(){return sAMPM;}
public void setStartAMPM(String sAMPM) {this.sAMPM = sAMPM;}
//Time
public String getStartTime(){return st;}
public void setStartTime(String st) {this.st = st;}
//Date
public String getStartDate() {return sd;}
public void setStartDate(String sd) {this.sd = sd;}

//End
//Hours
public String getEndHours(){return eh;}
public void setEndHours(String eh) {this.eh = eh;}
//Mins
public String getEndMins(){return em;}
public void setEndMins(String em) {this.em = em;}
//AMPM
public String getEndAMPM(){return eAMPM;}
public void setEndAMPM(String eAMPM) {this.eAMPM = eAMPM;}
//Time
public String getEndTime(){return et;}
public void setEndTime(String et) {this.et = et;}
//Date
public String getEndDate() {return ed;}
public void setEndDate(String ed) {this.ed = ed;}

//Reminder
//Hours
public String getReminderHours(){return rh;}
public void setReminderHours(String rh) {this.rh = rh;}
//Mins
public String getReminderMins(){return rm;}
public void setReminderMins(String rm) {this.rm = rm;}
//AMPM
public String getReminderAMPM(){return rAMPM;}
public void setReminderAMPM(String rAMPM) {this.rAMPM = rAMPM;}
//Time
public String getReminderTime(){return rt;}
public void setReminderTime(String rt) {this.rt = rt;}
//Date
public String getReminderDate() {return rd;}
public void setReminderDate(String rd) {this.rd = rd;}

//Follow Up
//Hours
public String getFollowHours(){return fh;}
public void setFollowHours(String fh) {this.fh = fh;}
//Mins
public String getFollowMins(){return fm;}
public void setFollowMins(String fm) {this.fm = fm;}
//AMPM
public String getFollowAMPM(){return fAMPM;}
public void setFollowAMPM(String fAMPM) {this.fAMPM = fAMPM;}
//Time
public String getFollowTime(){return ft;}
public void setFollowTime(String ft) {this.ft = ft;}
//Date
public String getFollowDate() {return fd;}
public void setFollowDate(String fd) {this.fd = fd;}

//Save Button
Public PageReference saveDestinyEvent(){

//Clone Situation
if(System.currentPageReference().getParameters().get('clone') == '1'){
//Set record id to null
Eve.Id = null;
}


//Set Start and End Datetime
if(Eve.StartDateTime == null){
String S = sd+' '+this.sh+':'+this.sm+' '+this.sAMPM;
Eve.StartDateTime = DateTime.parse(S);
}
if(Eve.EndDateTime == null){
String EdEt = ed+' '+this.eh+':'+this.em+' '+this.eAMPM;
Eve.EndDateTime = DateTime.parse(EdEt);
}
if((Eve.IsReminderSet == true)&&(Eve.ReminderDateTime == null)){
String R = this.rd+' '+this.rh+':'+this.rm+' '+this.rAMPM;
Eve.ReminderDateTime= DateTime.parse(R);
}
if(Eve.Destiny_Service_Decision__c=='Follow Up'){
String F = this.fd+' '+this.fh+':'+this.fm+' '+this.fAMPM;
String FoD = this.fd;
Eve.Follow_Up_DateTime__c = DateTime.parse(F);
Eve.Follow_Up_Date__c = Date.parse(FoD);
Eve.Follow_Up_Time__c = this.ft;
}

try {     
Upsert Eve;
// Send the user to the detail page for the new account.
PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+Eve.whatid+'&Sfdc.override=1');
pageRef.getParameters().put('tab','Activities');
return pageRef;
 } catch (Exception e) {     
      
             ApexPages.addMessages(e);      
        }
        return null;

}

//Save and New Button
Public PageReference saveNewDestinyEvent(){

//Set Start and End Datetime
if(Eve.StartDateTime == null){
String S = sd+' '+this.sh+':'+this.sm+' '+this.sAMPM;
Eve.StartDateTime = DateTime.parse(S);
}
if(Eve.EndDateTime == null){
String EdEt = ed+' '+this.eh+':'+this.em+' '+this.eAMPM;
Eve.EndDateTime = DateTime.parse(EdEt);
}
if((Eve.IsReminderSet == true)&&(Eve.ReminderDateTime == null)){
String R = this.rd+' '+this.rh+':'+this.rm+' '+this.rAMPM;
Eve.ReminderDateTime= DateTime.parse(R);
}
if(Eve.Destiny_Service_Decision__c=='Follow Up'){
String F = this.fd+' '+this.fh+':'+this.fm+' '+this.fAMPM;
String FoD = this.fd;
Eve.Follow_Up_DateTime__c = DateTime.parse(F);
Eve.Follow_Up_Date__c = Date.parse(FoD);
Eve.Follow_Up_Time__c = this.ft;
}


try { 
Upsert Eve;
// Send the user to the detail page for the new account.
PageReference pageRef= new PageReference('/00T/e');
return pageRef;
 } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        return null;

}

//Cancel Button
Public PageReference cancelDestinyEvent(){
PageReference pageRef = new PageReference('/apex/DestinyAccount?id='+Eve.whatid+'&Sfdc.override=1');
pageRef.getParameters().put('tab','Activities');
return pageRef;

}

   
///////////////////////////////////////////////////Time tool\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Time SelectList
public list<selectoption> getTimes()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption(T,T));
      options.add(new SelectOption('12:00 PM','12:00 PM'));
      options.add(new SelectOption('1:00 PM','1:00 PM'));
      options.add(new SelectOption('2:00 PM','2:00 PM'));
      options.add(new SelectOption('3:00 PM','3:00 PM'));
      options.add(new SelectOption('4:00 PM','4:00 PM'));
      options.add(new SelectOption('5:00 PM','5:00 PM'));
      options.add(new SelectOption('6:00 PM','6:00 PM'));
      options.add(new SelectOption('7:00 PM','7:00 PM'));
      options.add(new SelectOption('8:00 PM','8:00 PM'));
      options.add(new SelectOption('9:00 PM','9:00 PM'));
      options.add(new SelectOption('10:00 PM','10:00 PM'));
      options.add(new SelectOption('11:00 PM','11:00 PM'));
      options.add(new SelectOption('12:00 AM','12:00 AM'));
      options.add(new SelectOption('1:00 AM','1:00 AM'));
      options.add(new SelectOption('2:00 AM','2:00 AM'));
      options.add(new SelectOption('3:00 AM','3:00 AM'));
      options.add(new SelectOption('4:00 AM','4:00 AM'));
      options.add(new SelectOption('5:00 AM','5:00 AM'));
      options.add(new SelectOption('6:00 AM','6:00 AM'));
      options.add(new SelectOption('7:00 AM','7:00 AM'));
      options.add(new SelectOption('8:00 AM','8:00 AM'));
      options.add(new SelectOption('9:00 AM','9:00 AM'));
      options.add(new SelectOption('10:00 AM','10:00 AM'));
      options.add(new SelectOption('11:00 AM','11:00 AM'));
      options.add(new SelectOption('12:00 AM','12:00 AM'));

   return options;
 }
 
 public list<selectoption> getHours()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption(H,H));
      options.add(new SelectOption('12','12'));
      options.add(new SelectOption('1','1'));
      options.add(new SelectOption('2','2'));
      options.add(new SelectOption('3','3'));
      options.add(new SelectOption('4','4'));
      options.add(new SelectOption('5','5'));
      options.add(new SelectOption('6','6'));
      options.add(new SelectOption('7','7'));
      options.add(new SelectOption('8','8'));
      options.add(new SelectOption('9','9'));
      options.add(new SelectOption('10','10'));
      options.add(new SelectOption('11','11'));
   return options;
 }  
 
 public list<selectoption> getMins()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('00','00'));
      options.add(new SelectOption('00','00'));
      options.add(new SelectOption('05','05'));
      options.add(new SelectOption('10','10'));
      options.add(new SelectOption('15','15'));
      options.add(new SelectOption('20','20'));
      options.add(new SelectOption('25','25'));
      options.add(new SelectOption('30','30'));
      options.add(new SelectOption('30','30'));
      options.add(new SelectOption('35','35'));
      options.add(new SelectOption('40','40'));
      options.add(new SelectOption('45','45'));
      options.add(new SelectOption('50','50'));
      options.add(new SelectOption('55','55'));
   
   return options;
 }    
 
  public list<selectoption> getAMPM()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('PM','PM'));
      options.add(new SelectOption('AM','AM')); 
   return options;
 } 
///////////////////////////////////////////////////Time tool\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 

}



CODE 2
<apex:page standardController="User" extensions="Sample2">

    <apex:sectionHeader title="Visualforce Sample" subtitle="Describe for Picklist Values" help="/help/doc/user_ed.jsp?loc=help"></apex:sectionHeader>
    <apex:form >
    
    
        <apex:pageBlock title="Criteria" mode="edit">
            <apex:pageBlockSection title="Information" columns="1">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Time Zones" for="time_zones"></apex:outputLabel>
                    <apex:actionRegion > 
                    <apex:selectList id="time_zones" size="1" value="{!TimeZoneUser}" title="Time Zones">
                        <apex:selectOptions value="{!TimeZones}"></apex:selectOptions>
                        <apex:actionSupport event="onchange" reRender="ajaxrequest1" />
                    </apex:selectList>
                        </apex:actionRegion>
</apex:pageBlockSectionItem>


            </apex:pageBlockSection>
            <apex:outputpanel id="ajaxrequest1" > 
            
            <!---->  

              <apex:pageBlockSection columns="1">
      {!LocalOffset}



            </apex:pageBlockSection>
                    <apex:pageBlockSection columns="1">

     {!TimeZoneUser}
 

            </apex:pageBlockSection>
                    <apex:pageBlockSection columns="1">

     {!OffsetString}


            </apex:pageBlockSection>
                                <apex:pageBlockSection columns="1">

     {!CurrentTime}
     {!CurrentTime2}


            </apex:pageBlockSection>
                                            <apex:pageBlockSection columns="1">

     {!TimeZoneTime}


            </apex:pageBlockSection>
                                <apex:pageBlockSection columns="1">

     {!Offset}


            </apex:pageBlockSection>
            
          </apex:outputpanel> 
        
        </apex:pageBlock>
    </apex:form>
</apex:page>
Code 3
 
public with sharing class Sample2{
    private String first_picklist_option = '- All -'; //first value to display in picklist
    private final User user_object; //User sobject
    TimeZone UserTz = UserInfo.getTimeZone();
    TimeZone ClientTz = UserTz;
    String TimeZoneString = string.valueof(UserTz);
    public Integer iTz2;
    public Integer iTz3;
 
   
    Datetime mydate = System.now();
        integer test = UserTz.getOffset(mydate);

    
    public integer LocalOffset {get;set;}
    
    String eh = TimeZoneString;
    
    
    public String getTimeZoneUser(){return eh;}
public void setTimeZoneUser(String eh) {this.eh = eh;}

public string getOffsetString(){ 
return eh.substring(4,10);

}

public integer getOffset(){
if(eh == 'Pacific/Chatham'){
return 0;
}else{ 
String Tz1 = eh.substring(4,5);
String Tz2 = eh.substring(5,6);
String Tz3 = eh.substring(6,7);
String Tz4 = eh.substring(8,9);
String Tz5 = eh.substring(9,10);
return integer.valueof(Tz2+Tz3+Tz4+Tz5);
}



}

public datetime getCurrentTime(){ 
return mydate;

}

public Date getCurrentTime2(){ 
DateTime myDateTime = DateTime.newInstance(2006, 3, 16, 23, 0, 0);
Date myDate2 = myDateTime.dateGMT();
return myDate2;

}

public datetime getTimeZoneTime(){
if(eh == 'Australia/Brisbane'){
return mydate;
}else{ 
String Tz1 = eh.substring(4,5);
String Tz2 = eh.substring(5,6);
String Tz3 = eh.substring(6,7);
String Tz4 = eh.substring(8,9);
String Tz5 = eh.substring(9,10);
//Integer Hours = integer.valueof(Tz2+Tz3);
//Integer Minutes = integer.valueof(Tz4+Tz5);

if(Tz1 == '+'){
return mydate.addHours(integer.valueof(Tz2+Tz3)).addminutes(integer.valueof(Tz4+Tz5));
}else if(Tz1 == '-'){
return mydate.addHours(-(integer.valueof(Tz2+Tz3))).addminutes(-(integer.valueof(Tz4+Tz5)));
}else{
return null;
}

}
}

    
    public Sample2(ApexPages.StandardController stdController) {
        this.user_object = (User)stdController.getRecord();
        LocalOffset = Test;
         String TimeZoneString = '0';
         integer Offset = 0;

    }
    
    //builds a picklist of values based upon the passed information
    public List<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) {
        List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
        if ( first_val != null ) { //if there is a first value being provided
            options.add(new selectOption(first_val,first_val)); //add the first option
        }
        Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
            options.add(new selectOption(a.getLabel(), a.getValue()));  //add the value and label to our final list
        }
        return options; //return the List
    }
    
    
    //return the picklist options for User.TimeZoneSidKey
    public List<selectOption> getTimeZones() {
        return getPickValues(user_object, 'TimeZoneSidKey', first_picklist_option);
    }


}


 
Hey there,

I am trying to write some code which will update a related object of account. The code works perfectly normally, except i have re-qwritten it using criteria from a look-up related record.

Basiccally, the model goes:

Account - user adds a service (which is a child to account) and selects service_name and service_type.

Then a user adds a transaction when the client wishes to pay off the service.

When the transaction (which is also a child to account) is added, the transaction_type is set to 'First Payment' and the service lookup field is filled with a service that has its service_name as 'Essential property education only' and its service_type as 'New client'.

The first thing, is that the code works normally, with normal criteria. This is my attempt and it does not work:

trigger ClientPath_Transaction on Transaction__c (before insert) {
List<Account_Status__c> AccSt = new List<Account_Status__c>();
List<Account_Status__c> updatedAccSt = new List<Account_Status__c>();
List<Id> accIds = new List<Id>();


for (Transaction__c Tra: trigger.new) {
       if(Tra.Account__c != null && Tra.Transaction_Type__c == 'First Payment' && Tra.Destiny_Service_No__r != null) {
       accIds.add(Tra.Account__c);
       }
       }
  AccSt = [Select Id,Account_Status__c from Account_Status__c WHERE Account__c in :accIds];
  for(Account_Status__c a : AccSt)
  {
  

  
for (Transaction__c Tra: trigger.new) {   
if(Tra.Destiny_Service_No__r.Service_Name__c == 'Essential Property Education Only') {
       a.Account_Status__c = 'EPE Course Only';
       a.EPE_Course_Only__c = date.today();
    }

    
    
    }
       updatedAccSt.add(a);
       
}
if(updatedAccSt.size()>0)
{
update updatedAccSt;
}

}


Please help and thank you in advance for your time!
Hey there,

I have a trigger. This trigger works fine although i have read in many places that it is in ones best interest to bulkify trigger to prevent it from affecting your system in the long run. i was hoping that I may be able to get a hand in bulkifying my trigger.

I was also hoping someone could assist me in adding some extra functionality to the trigger. The activity with subject 'Upload Authoirty form' 'will awlays be related to an account, I was wondering how I could go about adding lines which will update a picklist field inside a custom object (account status) which is in a one to one relationship with account (account being the master)? 

Any advised steps I should take as well would be appreciated. E.G. Adding fields to lock in one to one relationship, changing picklist to formula field, etc. I currently have a trigger which creates the Account status record and associates it with the account upon Account record creation.

This is my trigger:

Trigger updateFields on Task(before insert){
  for (Task Tas: trigger.new){
  if (Tas.Subject == 'Upload Authority Form') {
    Tas.RecordTypeID = '012N00000008eow';
    Tas.Type = 'Document Upload';
    Tas.Status = 'Awaiting Form';
  }
}
}

Thank you so much ina advance for any help that you may be able to provide me.

Kind regards,

Michael
Hey there,

I have a tabbed Visualforce page, i will post the important section of the tab below. On my new record page, should the picklist field payment method be selected as 'Commission Deduction', a lookup field will render (will also post below). This all works perfectly, My question is:

Is it possible to make it so that my Tabbed visualforce detail page, can be altered to have a ajax re-rendering attribute similar to my New record page but through inline editing. E.G. Someone changes field payment method to 'Commission Deduction' and the lookup field will render.

Here is my new record page with Re-rendering code bolded:

<apex:page standardController="Office_Invoice__c" extensions="extSaveOffInvButton">
<apex:sectionHeader title="New Office Invoice" subtitle="{!Office_Invoice__c.name}"/>
<apex:form >
<apex:pageBlock title="New Office Invoice" mode="Detail">
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Save" action="{!SaveOfficeInvoice}"/>
<apex:commandButton value="Save&New" action="{!saveNewOfficeInvoice}"/>
<apex:commandButton value="Cancel" rendered="{!Office_Invoice__c.Office_Name__c != Null}" action="{!cancelOfficeInvoice}"/>
<apex:commandButton value="Cancel" rendered="{!Office_Invoice__c.Office_Name__c == Null}" immediate="true" action="{!cancel}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Office Invoices Information" columns="2">
<apex:inputField value="{!Office_Invoice__c.Office_Invoice_Amount__c}"/>
<apex:inputField value="{!Office_Invoice__c.Office_Invoice_GST_Amount__c}"/>
<apex:inputField value="{!Office_Invoice__c.Office_Invoice_Description__c}"/>
<apex:inputField value="{!Office_Invoice__c.Office_Invoice_Type__c}"/>
<apex:inputField value="{!Office_Invoice__c.Office_Name__c}"/>
<apex:inputField value="{!Office_Invoice__c.Office_Invoice_Date__c}"/>
</apex:pageBlockSection>

<apex:pageBlockSection title="Office Invoice Payment" columns="2">        
<apex:inputField value="{!Office_Invoice__c.Payment_Date__c}"/>
<apex:PageBlockSectionItem >
<apex:outputLabel value="Payment Method"/>
<apex:actionRegion >
<apex:inputField label="Payment Method" value="{!Office_Invoice__c.Payment_Method__c}">
<apex:actionSupport event="onchange" reRender="ajaxrequest" />
</apex:inputField>
</apex:actionRegion>
</apex:PageBlockSectionItem>
</apex:PageblockSection>
<apex:outputPanel id="ajaxrequest">
<apex:pageBlockSection rendered="{!Office_Invoice__c.Payment_Method__c=='Commission Deduction'}" title="Office Commission" >
<apex:inputField value="{!Office_Invoice__c.Office_Commission__c}"/>
</apex:pageBlockSection>
</apex:outputPanel>

</apex:pageBlock>


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


Here is my section of my Tabbed visualforce page:

apex:tab label="Office Invoice" rendered="{!$ObjectType.Office_Invoice__c.Accessible}" name="Office Invoice" id="tabOfficeInvoice" >
<apex:pageBlock title="Office Invoices" >
<apex:form >
<div align="Left">
<apex:commandbutton value="New Office Invoice" onclick="window.location='/a0P/e?CF00N90000008oaTS={!Office__c.name}&CF00N90000008oaTS_lkid= {!Office__c.id}'; return false;"/>
</div>

<apex:pageBlockTable value="{!Office__c.Office_Invoices__r}" var="OffInv" cellPadding="4"  border="4">



<apex:column headerValue="Office Invoices"  >
<apex:commandLink rerender="OffInvdetails" oncomplete="highlightElem(this);"> {!OffInv.Name}
<apex:param name="Invid" value="{!OffInv.id}"/>
</apex:commandLink>
</apex:column>
<apex:column value="{!OffInv.Office_Invoice_Amount__c}"  />
<apex:column value="{!OffInv.Office_Invoice_Date__c}" />

<apex:column value="{!OffInv.Office_Invoice_Type__c}" />
<apex:column value="{!OffInv.Office_Invoice_GST_Amount__c}" />
</apex:pageBlockTable>
</apex:form>
</apex:pageBlock>
<apex:outputPanel id="OffInvdetails">
<apex:detail subject="{!$CurrentPage.parameters.Invid}" relatedList="False" inlineEdit="True" title="false"/>
</apex:outputPanel>
</apex:tab>

Thank you in advance for any help or advice you can give to me
Hey there,

I have a tabbed account Visualforce page. One of the tabs of this page is transactions (which is a child object of Account). Transactions has multiple record types with specific stages and fields for each record type. There is a link to a create New transaction page on the tab which leads to the create New Transaction VF page I have created as I need to extend the functionality so i can re-direct back to my accounts tabbed VF page, etc. 

My questions are:

Is it possible to still allow the user to select the record type through this method?

If so, how would I go about doing ?

Thank you so mcuh in advance for your time

Hey there,

 

I have created a VF page with extension that will re-direct the user to a visualforce page with the correct tab open after creating a new record. I tried putting that same page onto the clone button and although it autofilled the correct fields, upon attempting to save I was left with this:

 

System.DmlException: Insert failed. First exception on row 0 with id a0LN0000000OsBEMA0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Error is in expression '{!SaveFactFinder}' in component <apex:commandButton> in page factfinderext

 

 

Class.extSaveButton.saveFactFinder: line 11, column 1

 

 

Am I able to do it like this or do I have to create an entirely different VF page and extension?

 

Thank you,

 

Mikie

Hi 

We have custom Participant object and custom timezone field(pick list - cetral , eastern arizona and pacific ). for each particiipat , particiipant address (state and zip code) is stored in child object called participantdetail. 
when new participnat is created , how do i populate the time zone  field with thier timezone ( i have  the zip code in address  and is it possible to populate the timezone field using the zip code  ) or any other way.  . 
  • November 14, 2017
  • Like
  • 0
Hi All,
I am looking to integrate 2 Salesforce Orgs using rest API - I am completely new to coding and apex - I have managed to integrate org 1 and org 2 for the account object but I now want to do the same for opportunity. Below is the code I have used for the account object which works - when creating an account in 1 org it automatically creates in org 2. How do i do the same for Opportunity?

APEX CLASS

public class SendAccount {
private final String clientId = '********';
private final String clientSecret = '****';
private final String username = '***';
private final String password = '*****';
public class deserializeResponse
{
public String id;
public String access_token;
}
public String ReturnAccessToken (SendAccount acount)
{
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://*****/services/oauth2/token');
HttpResponse res = h.send(req);
deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
return resp1.access_token;
}
@future(callout=true)
public static void createAccount(String accName, String accPhone, String accWebsite, String accType, String accIndustry, String accSource, String accDescription, String accNotes, String accAddress, String accId)
{
SendAccount acount = new SendAccount();
String accessToken = acount.ReturnAccessToken (acount);
if(accessToken != null)
{
String endPoint = 'https://********/services/data/v32.0/sobjects/Account/';
String jsonstr = '{"Name" : "' + accName + '","Phone" : "' + accPhone + '","Website" : "' + accWebsite + '","Type" : "' + accType + '","Industry" : "' + accIndustry + '","Source__c" : "' + accSource + '","Description__c" : "' + accDescription + '","Notes__c" : "' + accNotes + '","Address__c" : "' + accAddress + '"}';
Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);
deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(res1.getbody(),deserializeResponse.class);
Account a = [SELECT Phone, Website, Type, Industry, Source__c, Description__c, Notes__c, Address__c, Id FROM Account WHERE Id = :accId];
a.externalid__c = resp2.id;
update a;
}
}
}


APEX TRIGGER

trigger SendAccount on Account (after insert) {
for(Account a:Trigger.new){
SendAccount.createAccount(a.name, a.Phone, a.Website, a.Type, a.Industry, a.Source__c, a.Description__c, a.Notes__c, a.Address__c, a.Id);
}
}
 
Hello All,

I'm new to Salesforce Apex coding and undergoing some training and classes in Apex. I noticed that we cannot give any condition in List FOR loop. For example, lets say I've a list of 1000 Contacts in myContactList. I need to loop myContactList for one particular account instead of running all the records one by one and check inside the loop if the account name is what am expecting. I've seen we can use SOQL for this. But my question is can we not use the local list variable to have filter and loop only the records which I want to?

Something similar to below code for reference:
for (Contacts myContact : myContactList.Where(Account.Name = 'Acme')){

}

Let me know if there are any way I can achieve this using myContactList instead of having SOQL call.

Thanks.

Regards,
Mohan Babu
This is my first Apex Trigger and I realize it will make most of you cringe your teeth!  It is a simple trigger that will update the lead 'status' field to 'contacted' when the following criteria are met:

1- its 'lead rating' is either D1,D2,D3, or D4
2- the current lead 'status' is "open"
3- the lead has a related task containing "Message Sent:" in the subject 

Can anyone please help me bulkify this?  




trigger dleadstatus on Lead (before insert, before update) {



    for (Lead l : Trigger.new) {
    if((l.Eloqua_Lead_Rating__c =='D1' || l.Eloqua_Lead_Rating__c =='D2'|| l.Eloqua_Lead_Rating__c =='D3'|| l.Eloqua_Lead_Rating__c =='D4')&& l.Status =='Open') {
    List<Task> sentemails = [SELECT Id FROM Task WHERE Subject LIKE '%Message Sent:%'];
    
    if(sentemails.size() > 0) {
    l.Status = 'Contacted';}
    else {l.Status = 'Open';}}}

}
I've read the documentation, but I wasn't entirely clear on a few things with "Sharing Sets" in Communities

1) Do they only apply to High Volume Portal Users, or all Communities users with the right Profile
2) If somebody is granted access to a record via a Sharing Set and then go to a VF Page with a "With Sharing" controller, will that Sharing Set be taken into account?

It seems like a major difference between Community and Community Plus licences in the documentation is that plus licences respect Sharing. However, Sharing Sets seem to then someway negate that advantage, if you can use them with standard Community licences and apex "with sharing".

Does anybody happen to know the details on this? Thanks!

Hi Guys,

I cant figure out how to pass my integration class. Please help, any help would be much appreciated.

 

public class Integration {

    // The ExternalOrder class holds a string and integer
    // received from the external fulfillment system.

    public class ExternalOrder {
        public String id {
            get;
            set;
        }
        public String result {
            get;
            set;
        }
    }

    //  Functionally, the method 1) prepares
    // JSON-formatted data to send to the remote service, 2) makes an HTTP call
    // to send the prepared data to the remote service, and then 3) processes
    // any JSON-formatted data returned by the remote service to update the
    // local Invoices with the corresponding external IDs in the remote system.

    @future(callout = true) // indicates that this is an asynchronous call
    public static void postOrder(List < Id > AccountIds, boolean isScheduleExpiry) {

        //Call Accounts associated to Id List
        List < Account > Accounts = [SELECT Id, DestinyLive_Email_Username__c, Support_Expiration__c, Receiving_Support__c, DestinyLive_Premium_Membership_Expiry__c FROM Account WHERE Id IN: AccountIds];
        
        // Create a JSON generator object
        JSONGenerator gen = JSON.createGenerator(true);
        // open the JSON generator
        gen.writeStartArray();
        // iterate through the list of invoices passed in to the call
        // writing each Account ID to the array
        for (Account Acc: Accounts) {
        Datetime ExpiryDate = Acc.DestinyLive_Premium_Membership_Expiry__c;
        String myDatetimeStr = ExpiryDate.format('dd/MM/YYYY');
            gen.writeStartObject();
            gen.writeStringField('id', Acc.Id);
            if(Acc.DestinyLive_Email_Username__c != null && Acc.DestinyLive_Email_Username__c != ''){
            gen.writeStringField('DestinyLive_UserName', Acc.DestinyLive_Email_Username__c);
            }else{
            gen.writeStringField('DestinyLive_UserName', 'NA');
            }
            
            //Set Destiny Client to false as isScheduleExpiry == true because the class is scheduled to run 15 minutes before expiry
            if(isScheduleExpiry == true){
            gen.writeBooleanField('DestinyClient', false);
            }else{
            gen.writeBooleanField('DestinyClient', Acc.Receiving_Support__c);
            }
            gen.writeStringField('Expiry', myDatetimeStr);
            gen.writeEndObject();
        }
        // close the JSON generator
        gen.writeEndArray();
        // create a string from the JSON generator
        String jsonOrders = gen.getAsString();
        // debugging call, which you can check in debug logs
        System.debug('jsonOrders: ' + jsonOrders);

        // create an HTTPrequest object    
        HttpRequest req = new HttpRequest();
        // set up the HTTP request with a method, endpoint, header, and body
        req.setMethod('POST');
        // DON'T FORGET TO UPDATE THE FOLLOWING LINE WITH YOUR APP NAME
        req.setEndpoint('http://requestb.in/1n6j75u1');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(jsonOrders);
        // create a new HTTP object
        Http http = new Http();
        // create a new HTTP response for receiving the remote response
        // then use it to send the configured HTTPrequest
        HTTPResponse res = http.send(req);
        // debugging call, which you can check in debug logs
        System.debug('Fulfillment service returned ' + res.getBody());

        // 3) see above

        // Examine the status code from the HTTPResponse
        // If status code != 200, write debugging information, done
        if (res.getStatusCode() != 200) {
            System.debug('Error from ' + req.getEndpoint() + ' : ' + res.getStatusCode() + ' ' + res.getStatus());
        }
        // If status code = 200, update each Account
        // with the external ID returned by the fulfillment service.
        else {

            // Create a list of external orders by deserializing the
            // JSON data returned by the fulfillment service.
            List < ExternalOrder > orders = (List < ExternalOrder > ) JSON.deserialize(res.getBody(),
            List < ExternalOrder > .class);
            // Create a map of Invoice IDs from the retrieved
            Map < Id, Account > AccMap = new Map < Id, Account > (Accounts);
            // Update the order numbers in the invoices
            for (ExternalOrder order: orders) {
            
            if(order.result == 'Success'){
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= False;
                Acc.DestinyLive_Integration_Status__c = 'Completed - Success';
            }else if(order.result == 'NA'){
                
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= true;
                Acc.DestinyLive_Integration_Status__c = 'Completed - User Not Found';
            }else if(order.result == 'Failure'){
                Account Acc = AccMap.get(order.id);
                Acc.DestinyLive_Premium_Membership__c= true;
                Acc.DestinyLive_Integration_Status__c = 'Completed - Failure';
           }
            }

            update Accounts;
        }
    }
}

current test 
 
@isTest 
private class Integration_Test{
    static testMethod void IntegrationTest() {
    
  List<Id> AccountIds = new List<Id>();           

  List<Account> AccountList = new List<Account>{};
for(Integer i = 0; i < 200; i++){
        Account Accs = new Account( Name = 'Test' + i, DestinyLive_Premium_Membership_Expiry__c = date.today().adddays(40), DestinyLive_Email_Username__c = 'Success22@knmfld.fdfdf', Receiving_Support__c = true, Support_Expiration__c = date.today().adddays(40), Support_Start__c = date.today().adddays(-40));
        AccountList.add(Accs);
    }
    
   insert AccountList;
    
    
    for ( Account Acc : AccountList) {
    AccountIds.add(Acc.Id);
    }
  
    Test.startTest();
     If(!Test.isRunningTest()){
    Integration.postOrder(AccountIds, True);
    }
    Test.stopTest();


}

}

 
I am attempting to center the contents of an outputfield which I am placing into a datatable's column. I can't find an attribute for the datatable which can do this. The closest I can find is an attribute which will center the datatable itself, but I don't want that. 

Here is an example of the code : 
 
<apex:dataTable value="{!Vendor_Product_Review__c}" var="pitem" border="4"  align="left" cellpadding="10" rowClasses="rowWithBorder"> 
                          
                            
                      <apex:column headerValue="" >
                                 <apex:outputLabel >Credit   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Liquidity   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Transaction   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Foreign Exchange   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Interest Rate   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Reputation   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Operational   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Price   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Compliance   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Strategic   </apex:outputLabel><br></br>
                                 <apex:outputLabel >Financial  </apex:outputLabel><br></br>
                                 <apex:outputLabel >Other   </apex:outputLabel><br></br>
                             </apex:column>
                         
                             <apex:column headerValue="Probability" >
                                 <apex:outputfield value="{!pitem.CreditRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.LiquidityRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.TransactionRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.ForeignExchangeRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.InterestRateRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.ReputationRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.OperationalRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.PriceRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.ComplianceRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.StrategicRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.FinancialRiskProbability__c}"/><br></br>
                                 <apex:outputfield value="{!pitem.OtherRiskProbability__c}"/><br></br>
                             </apex:column>

I would like the outputlabels to be centered within their column as well. 

Anybody got an idea on this ? 

Thank you.
 
  • November 19, 2015
  • Like
  • 0
Hi there,

I have a wrapper class and I am trying to test it. I need 100% as my other code coverage isa  bit lacking, but only have 73%. I am not sure if I have even set this out properly and I dont know how to test for the wrapper parts of my controller. E.G. FinLoanWrapper, any help would be muich appreciated.

Test
@isTest 
private class FinanceNew_Test{
    static testMethod void FinanceCommissionNew() {
    
     PageReference pageRef = Page.DestinyFinanceNew4;
        Test.setCurrentPage(pageRef);
    
    Office__c Office = new Office__c(Name = 'Test Pro Account');
insert Office;
Account Acc = new Account(Name = 'Test Account', office__c = Office.id);
insert Acc;
Finance__c Fin = new Finance__c(Finance_Office__c = office.id, Account__c = Acc.id);
insert Fin;
List<Finance_Loan_Security__c> FLSEC = new List<Finance_Loan_Security__c>{};
for(Integer i = 0; i < 10; i++){
        Finance_Loan_Security__c FLSE = new Finance_Loan_Security__c(Office__c = Office.id, Account__c = acc.id, No_Street__c = 'Test' + i, Finance__c = Fin.id);
        FLSEC.add(FLSE);
    }
List<Finance_Loan_Split__c> FLSPL = new List<Finance_Loan_Split__c>{};
for(Integer i = 0; i < 10; i++){
        Finance_Loan_Split__c FLS = new Finance_Loan_Split__c(Office__c = Office.id, Account__c = acc.id, Account_Number__c = 'Test' + i, Finance__c = Fin.id);
        FLSPL.add(FLS);
    }
    insert FLSPL;
    Insert FLSEC;
    
    ApexPages.currentPage().getParameters().put('FinId', Fin.id);
     ApexPages.currentPage().getParameters().put('OffId', Office.id);
      ApexPages.currentPage().getParameters().put('AccId', Acc.id);


       //this call tests the constructor:
       FinanceNew controller = new FinanceNew();
       
      
       //test building was complete
        System.assert(controller.wrappers.size()==10);
         System.assert(controller.wrappers2.size()==10);
        
        
        //call the pageReference in the class.
        controller.FinLoanCalculate();
        controller.FinSecCalculate();
        System.assert(Fin.Aggregate_Borrowings__c ==0.00);
        
        controller.addRows();
        controller.delWrapper();
        controller.addRows2();
        controller.delWrapper2();
        
        controller.saveStandard();
        controller.Cancel();



    }
}



Class
public class FinanceNew{
    
    public Finance__c Fin { get; set; }
    public Finance_Loan_Security__c LoanSecurity { get; set; }
    public Finance_Loan_Split__c LoanSplit { get; set; }
    
    
    //Wrapper multi add try to implement
     public List<FinLoanSplitWrapper> wrappers {get; set;}
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
       public List<FinLoanSecurityWrapper> wrappers2 {get; set;}
 public static Integer toDelIdent2 {get; set;}
 public static Integer addCount2 {get; set;}
 private Integer nextIdent2=0;
 
 //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\Wrapper 2 identical - 1
  Id FinId = ApexPages.currentPage().getParameters().get('FinId');
   public string delId {get;set;}
 ////////////////test
 

 
 public void FinLoanCalculate()
{
nextIdent=-1;
Integer NoSplits = 0;
Decimal AggBorrowing = 0.00;
  for (FinLoanSplitWrapper wrap : wrappers)
  {
  if(wrap.FinLoanS.Loan_Amount__c == null){
  wrap.FinLoanS.Loan_Amount__c = 0.00;
  }
  AggBorrowing = AggBorrowing + wrap.FinLoanS.Loan_Amount__c;
  NoSplits = NoSplits + 1;
  nextIdent = nextIdent + 1;
  wrap.ident = nextIdent;
  }
  Fin.Number_of_Splits__c = NoSplits;
  Fin.Aggregate_Borrowings__c = AggBorrowing;


}

 public void FinSecCalculate()
{
nextIdent2=-1;
Integer NoSecurities = 0;
Decimal ValTotal = 0.00;
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
  if(wrap.FinSecS.Actual_Value__c== null){
  wrap.FinSecS.Actual_Value__c= 0.00;
  }
  ValTotal = ValTotal  + wrap.FinSecS.Actual_Value__c;
  NoSecurities = NoSecurities + 1;
  nextIdent2 = nextIdent2 + 1;
  wrap.ident2 = nextIdent2;
  }
  Fin.Number_of_Securities__c = NoSecurities;
   Fin.total_security_Value__c= ValTotal;
}



 ////////////////test









////////////////////Delete Rows
//Delete Rows 1 
public void delWrapper()
 {
  Integer toDelPos=-1;
  boolean IsInsertedRow = False;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
    if (wrappers[idx].IsInserted==true){
    IsInsertedRow = true;
    }
  }
   
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
  if(delId != null && IsInsertedRow == True){
  
  Finance_Loan_Split__c[] FLS = [select id from Finance_Loan_Split__c where id =: delId ];
    if(FLS.size() > 0){
  
  delete FLS[0];
  
  }
  }
  delId = null;
  IsInsertedRow = false;
  
 }



//Delete Rows 2
  public void delWrapper2()
 {
  boolean IsInsertedRow = False;
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers2.size(); idx++)
  {
   if (wrappers2[idx].ident2==toDelIdent2)
   {
    toDelPos=idx;
   }
    if (wrappers2[idx].IsInserted==true){
    IsInsertedRow = true;
    }
  }
   
  if (-1!=toDelPos)
  {
   wrappers2.remove(toDelPos);
  }
  if(delId != null && IsInsertedRow == True){
   Finance_Loan_Security__c[] FLSE = [select id from Finance_Loan_Security__c where id =: delId ];
         if(FLSE.size() > 0){
  
  delete FLSE[0];
  
  }
  }
 }







 //////////////////////////Add Rows
 //Add Rows 1
 public void addRows()
 {
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(integer.valueof(Fin.Number_of_Splits__c), null));
  }
 }
//Add Rows 2
 public void addRows2()
 {
  for (Integer idx=0; idx<addCount2; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(integer.valueof(Fin.Number_of_Securities__c),null));
  }
 }
  //////////////////////////Add Rows
 
 

 
 
 ////////////////Wrappers
 public class FinLoanSplitWrapper
 {
  public Finance_Loan_Split__c FinLoanS {get; private set;}
  public Integer ident {get; private set;}
  public boolean IsInserted  {get; set;}
   
  public FinLoanSplitWrapper(Integer inIdent , Finance_Loan_Split__c LoanSplit)
  {
  ident=inident;
 if(LoanSplit != null){
   FinLoans = LoanSplit; 
   IsInserted = true;    
   }else{
   FinLoanS=new Finance_Loan_Split__c(Loan_Split_Number__c=ident);
   IsInserted = false;
   }
  }
 }
  
 public class FinLoanSecurityWrapper
 {
  public Finance_Loan_Security__c FinSecS {get; private set;}
  public Integer ident2 {get; private set;}
  public boolean IsInserted  {get; set;}
   
  public FinLoanSecurityWrapper(Integer inIdent, Finance_Loan_Security__c LoanSecurity )
  {
   ident2=inIdent;
 if(LoanSecurity != null){
     FinSecS = LoanSecurity;
     IsInserted = true;  
     }else{
   FinSecS=new Finance_Loan_Security__c(Loan_Security_Number__c=ident2);
   IsInserted = false;
   }
   
   
  }
 }
  

 public FinanceNew() {
     
     Id FinId = ApexPages.currentPage().getParameters().get('FinId');
     if(FinId != null){
     Fin = [SELECT Id, Application_End_Reason__c, Financier__c, Financier_Reference__c, Application_LVR__c ,
     Total_Security_Value__c, Loan_Information__c , Account__c , Finance_Office__c, Settlement_Due__c, Finance_Clause__c, Number_of_Securities__c,Number_of_Splits__c ,
     Aggregate_Borrowings__c, Total_New_Loans__c, Application_Completed__c ,Application_Submitted__c,Conditional_Approval__c,Valuation_Completed__c,
     Unconditional_Approval__c ,Finance_Documents_Issued__c,Finance_Documents_Executed__c ,Finance_Documents_Submitted__c ,Finance_Certified__c , Finance_Settlement__c ,
     Application_End__c,Upfront_Commission_Paid__c       FROM Finance__c
                   WHERE Id = :ApexPages.currentPage().getParameters().get('FinId') ];
                
 if(wrappers == null) { 
     
      wrappers=new List<FinLoanSplitWrapper>();
      for(Finance_Loan_Split__c LoanSplit:[SELECT Id, Account__c ,Office__c, Loan_Split_Number__c, Loan_Amount__c ,Loan_Type__c,Payment_Type__c,
      Loan_Purpose__c,Comment__c, finance__c, Secondary_Purpose__c, Account_Number__c  FROM Finance_Loan_Split__c
                   WHERE finance__c  = :FinId order by Loan_Split_Number__c asc]){
                   
                   nextIdent = Integer.valueof(LoanSplit.Loan_Split_Number__c);
                   
                 wrappers.add(new FinLoanSplitWrapper(nextIdent,LoanSplit));
                   }
                   }
                  
 if(wrappers2 == null) { 
     
      wrappers2=new List<FinLoanSecurityWrapper>();
      for(Finance_Loan_Security__c LoanSecurity :[SELECT Id, Account__c ,Office__c,Loan_Security_Number__c,New_Existing__c,Estimated_Value__c,No_Street__c,
      Suburb__c,State__c ,Postcode__c ,Actual_Value__c,Valuation_Date__c , Rental_Yield__c,Finance__c,Loan_Priority__c,Title_Owner__c   FROM Finance_Loan_Security__c
                   WHERE finance__c  = :FinId order by Loan_Security_Number__c asc]){
                   
                   nextIdent2 = Integer.valueof(LoanSecurity.Loan_Security_Number__c);
                   
                 wrappers2.add(new FinLoanSecurityWrapper(nextIdent2,LoanSecurity));
                   }
                   }
                
    
     
     }else{
     Fin = new Finance__c (Number_of_Splits__c = 1,Number_of_Securities__c = 1,Aggregate_Borrowings__c = 0.00, Total_New_Loans__c = 0.00, Total_Security_Value__c = 0.00);
     Fin.Finance_Office__c = ApexPages.currentPage().getParameters().get('OffId');
     Fin.Account__c = ApexPages.currentPage().getParameters().get('AccId');
      
      
    //LoanSecurity = new Finance_Loan_Security__c ();
      wrappers=new List<FinLoanSplitWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers.add(new FinLoanSplitWrapper(nextIdent++, null));
  }
      wrappers2=new List<FinLoanSecurityWrapper>();
  for (Integer idx=0; idx<1; idx++)
  {
   wrappers2.add(new FinLoanSecurityWrapper(nextIdent2++,null));
  }

}  
      
    }
    
//////////////////////////Save and Cancel\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
    public PageReference saveStandard() {
    
    List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
 Integer SetFLS = -1;
  for (FinLoanSplitWrapper wrap : wrappers)
  {
  SetFLS = SetFLS + 1;
   wrap.FinLoanS.Loan_Split_Number__c = SetFLS;
   FLS.add(wrap.FinLoanS);
  }
  Fin.Number_of_Splits__c = SetFLS+1;

 List<Finance_Loan_Security__c> LoanSecurity =new List<Finance_Loan_Security__c>();
 Integer SetFLSE = -1;
  for (FinLoanSecurityWrapper wrap : wrappers2)
  {
   SetFLSE = SetFLSE + 1;
   wrap.FinSecS.Loan_Security_Number__c = SetFLSE;
   LoanSecurity.add(wrap.FinSecS);
  }
  Fin.Number_of_Securities__c= SetFLSE+1;
    
     try {  
      upsert Fin;
        
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        

  
  for (Finance_Loan_Split__c FinLoanSplit: FLS)
  {
  If(FinLoanSplit.Finance__c == null){
    FinLoanSplit.Finance__c = Fin.id;
    }
  If(FinLoanSplit.Account__c == null){
   FinLoanSplit.Account__c = Fin.Account__c;
   }
   If(FinLoanSplit.Office__c == null){
   FinLoanSplit.Office__c = Fin.Finance_Office__c;
   }
  }
  
    for (Finance_Loan_Security__c LoanSec: LoanSecurity)
  {
   If(LoanSec.Finance__c == null){
    LoanSec.Finance__c = Fin.id;
    }
    If(LoanSec.Account__c == null){
   LoanSec.Account__c = Fin.Account__c;
   }
   If(LoanSec.Office__c == null){
   LoanSec.Office__c = Fin.Finance_Office__c;
   }
  }            
        
        try { 
        
        upsert FLS;
        upsert LoanSecurity;
       
       
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+fin.Account__c+'&Sfdc.override=1');
        return pageRef;
        } catch (Exception e) {     
      
             ApexPages.addMessages(e);         
        }
        
        
        
        return null;
    
    }
    
      
    public PageReference Cancel() {
   
        PageReference pageRef= new PageReference('/apex/DestinyAccount?id='+Fin.account__c+'&Sfdc.override=1');
        return pageRef;
     
    }
//////////////////////////Save and Cancel\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
//////////////////////Old Code to keep for Reference - Delete Later\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\   


  /* Remove for now, as it has been made redunant. keep for reference incase soemthing goes wrong
 public PageReference save()
 {
  List<Finance_Loan_Split__c> FLS =new List<Finance_Loan_Split__c>();
  for (FinLoanSplitWrapper wrap : wrappers)
  {
   FLS.add(wrap.FinLoanS);
  }
   
  insert FLS;
   
  return new PageReference('/' + Schema.getGlobalDescribe().get('Finance_Loan_Split__c').getDescribe().getKeyPrefix() + '/o');
 }
 */

//////////////////////Old Code to keep for Reference - Delete Later\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\    
 
    
}

 

Hey there,

 

I am not even sure this is possible, but I need some advice. Basically, I have a tabbed VF page for my account and all of its related lists and child objects have their own tab. These tabs are lists of all the records associated with that account and should the user click on one of the links, the bottom half of that tab will re-render with the information. Essentially, it is all the information on one page.

 

This all works perfectly, except what i need to do is to make it so that should the user wish to create a new record, upon saving they will be re-directed to the tab of the object they had jsut created the record in. I have searched and searched and searched for a solution, many people have theories on how to do this...maybe some people have even done this (by searching for a reference for each tab or naming each tab in the code), however it is a bit beyond my coding skill.

 

My question is...Would it be possible to have a link which will re-render the bottom half of the tab..into a create new record VF page...which upon saving will once again re-render to the record... What are your thoughts people?

 

Mikie 

I have a client who is experiencing the following error on a custom controller and we can't find any solutions. 

 

It's just a selectList with a value tied to a String.

 

"j_id0:theForm:j_id2:j_id13:j_id14:j_id16:mySolutionOption: Validation Error: Value is not valid"

 

Any ideas?

 

Thanks,

Jon