• anja
  • NEWBIE
  • 50 Points
  • Member since 2011

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 11
    Replies

http://wiki.developerforce.com/page/Sorting_Tables - this is some code developed by someone else - I found it online - I made very few changes and cannot get more that 61% coverage (with this or original) - it is failing at lines 17,18,21,22,23,42,43,46,47,49,50,52,74,75,77,78

 

I am not sure what to add to the tests in order to get the coverage up:

 

 

public class superSort {

 

    /*This method takes 3 arguments, the List of objects to sort, the field to sort,

    and the order, asc or desc*/

   

    public static void sortList(List<sObject> items, String sortField, String order){

        /*I must give credit where it is due as the sorting algorithm I am using is the

        one supplied by Andrew Waite here: http://blog.sforce.com/sforce/2008/09/sorting-collect.html */

       

        Boolean isSortFieldReference = false;

        Map<Id,String> referenceName;

        

        /*Determine the type of the field that needs to be sorted, if it is a

        reference we will want sort by the name of the related object, not the

        ID itself*/

        if(items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getType().Name() == 'REFERENCE'){

            isSortFieldReference = true;

            referenceName = new Map<Id,String>();

           

            /*Determine the type of this object and populate the Id to Name map*/

            Set<Id> referenceIds = new Set<Id>();

            for(sObject s : items){

               referenceIds.add((Id)s.get(sortField));

            }

           

            // DevAngel - EDIT - Because you may not have a value for the reference field in the first record

            // in the table you are sorting, this approach will fail on the substring method.  Below is

            // is a more reliable method using describe calls

            /*

            String objectID = (String)items[0].get(sortField);

            String prefix = objectID.substring(0,3);

            String objectType;

            Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

            for(Schema.SObjectType s : gd.values()){

                if(prefix == s.getDescribe().getKeyPrefix()){

                    objectType = s.getDescribe().Name;

                }

            }

            */

 

            // DevAngel - EDIT - New approach...

            List<Schema.Sobjecttype> objType = items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getReferenceTo();

            String objectType = objType[0].getDescribe().getName();

 

            //Query the related objects for the name and populate the Id -> Name map

            String queryString = 'select Id, Name from ' + objectType + ' where ID IN :referenceIDs';

            for(sObject s : Database.query(queryString )){

                // DevAngel - EDIT - if the reference field is null then we will not have a result, so we need to "create one"

                if (s.get('Name') == null) {

                    referenceName.put((Id)s.get('Id'), 'n/a');

                } else {

                    referenceName.put((Id)s.get('Id'),(String)s.get('Name'));

                }

            }

        }

               

        /*Declare a list that will contain the sorted results. I think this is one of the

        coolest parts of this method as the system will not let you declare a list of

        sObjects (List<sObject> objects = new List<sObjects>();) but using a

        wrapper class you can bypass this system limitation to create this type of list */

        List<cObject> resultList = new List<cObject>();

   

        //Create a map that can be used for sorting

        Map<object, List<cObject>> objectMap = new Map<object, List<cObject>>();

       

        for(sObject ob : items){

            if(isSortFieldReference == false){

                if(objectMap.get(ob.get(sortField)) == null){

                    objectMap.put(ob.get(sortField), new List<cObject>());

                }

                cObject o = new cObject(ob);

                objectMap.get(ob.get(sortField)).add(o);

            }else{

                if(objectMap.get(referenceName.get((Id)ob.get(sortField))) == null){

                    objectMap.put(referenceName.get((Id)ob.get(sortField)), new List<cObject>());

                }

                cObject o = new cObject(ob);

                objectMap.get(referenceName.get((Id)ob.get(sortField))).add(o);

            }

        }

       

        //Sort the keys

        List<object> keys = new List<object>(objectMap.keySet());

        keys.sort();

       

        for(object key : keys){

            resultList.addAll(objectMap.get(key));

        }

       

        //Apply the sorted values to the source list

        items.clear();

        if(order.toLowerCase() == 'asc'){

            for(cObject ob : resultList){

                items.add(ob.obj); 

            }

        }else if(order.toLowerCase() == 'desc'){

            for(integer i = resultList.size()-1; i >= 0; i--){

                items.add(resultList[i].obj);  

            }

        }

    }

   

    public class cObject{

        sObject obj {get; set;}

       

        public cObject(sObject obj){

            this.obj = obj;

        }

    }

   

    /*Some test methods that provide 100% coverage */

   

public static testMethod void sortAscendingTest(){

       

        List<Account> accs = new List<Account>();

        for(integer i = 0; i<1000; i++){

            accs.add(new Account(Name = 'test' + i, Annualized_Revenue__c = 1000 * Math.random()));

        }

       

        Test.startTest();

        Long start = system.currentTimeMillis();

        sortList(accs,'Annualized_Revenue__c','asc');

        system.debug(system.currentTimeMillis() - start);

        Test.stopTest();

       

        //Assert the list was sorted correctly

        Decimal assertValue = -1;

        for(Account a : accs) {

            System.debug('Acc value: ' + a.Annualized_Revenue__c);

            System.assert(assertValue <= a.Annualized_Revenue__c);

            assertValue = a.Annualized_Revenue__c;

        } 

    }

  

   

public static testMethod void sortDescendingTest(){

       

       

        List<Account> accs = new List<Account>();

        for(integer i = 0; i<1000; i++){

            accs.add(new Account(Name = 'test' + i, Annualized_Revenue__c = 1000 * Math.random()));

        }

       

        Test.startTest();

        sortList(accs,'Annualized_Revenue__c','desc');

        Test.stopTest();

       

        //Assert the list was sorted correctly

        Decimal assertValue = 1001;

        for(Account a : accs) {

            System.debug('Opp value: ' + a.Annualized_Revenue__c);

            System.assert(assertValue >= a.Annualized_Revenue__c);

            assertValue = a.Annualized_Revenue__c;

        } 

    }

}

 

 

  • November 17, 2011
  • Like
  • 0

While at DF2011 I got some cool apex code for creating a VF page that creates a searchable account list and this was one of the controllers for that page - 

 

 

public AccountListController() {

        // TODO: call the parent class constructor with a base query

        super('select Id, BillingCity, BillingState, RecordTypeId, Owner__c, Name from Account');

 

pageSize = 50;   

 

I am wondering if there is a way to add a "where" clause to the above. I have tried several difffent ways to limit the query but have not been successful.

 

here is the ending of the code:

 

}

// cast the resultset

    public List<Account> getAccounts() {

        // TODO: cast returned records into list of Accounts

        return (List<Account>) getRecords();

    }

  • October 03, 2011
  • Like
  • 0

When someone goes to add a new Account, Contact or Lead, they go to the associated Tab and click “New” and then choose a record type and click “Continue”


I overrode the “New” button in salesforce so that the person gets redirected to the SearchFirst screen after they select the Record Type and click “Continue”.

The difficulty is that when you now click “New” in this app (after you have successfully completed your search) it returns you back to this page - because the source code for SearchFirst uses the "new" method standard in Salesforce - which I just overrode. I get a loop. 

 

Has anyone come across a way to create a custom button in this app to redirect you to the actual page where you add the new contact, lead, or account?

 
  • September 27, 2011
  • Like
  • 0

Hello,

 

I have a trigger that inserts a new Opportunity whenever a campaign member is selected for a certain campaign type. The difficulty I am having is in getting the Account name into the Account field on Opportunity. I can seem to only get the ID option to work correctly, but that is not what I want - here is the code: 

 

trigger createOpportunityCampaignMember on CampaignMember (after insert)

{

    date myDate =

     date.today();

    date newDate = mydate.addDays(180);

 

    List<Opportunity> op = new List<Opportunity>();

        for (CampaignMember newCampaignMember: Trigger.New)

         if (newCampaignMember.RecordTypeID == '01250000000Dtga')//record type for marketing campaign member

           

         {

            op.add (

                    new Opportunity

                        (

                            AccountId = newCampaignMember.Contact.AccountId,

                            Name = newCampaignMember.Contact.AccountId + ' Marketing Lead',

                            RecordTypeID = '01250000000DcJk', //BDS Leads

                            StageName = 'Submit Lead for Verification',

                            CloseDate = newDate,

                            Campaign = newCampaignMember.Campaign

            

                        )

                    );

                    

            insert op;

         }

        

        

 

  • September 22, 2011
  • Like
  • 0

is it possible to use a trigger/apex to create an opportunity automatically from a contact once a contact is created?

  • September 16, 2011
  • Like
  • 0

Hello, I am new to writing tests - working off of the template in how to write good unit tests. This is my effort but I get the error Invalid id value for this SObject type:

 

public class ActiveAffiliationsTriggerTest

static testMethod void ActiveAffiliationsTest() 

{     
    // Set up the Contact record.   

Contact c = new Contact(FirstName='Test Contact', LastName ='Test Last');   

insert c;


   // Verify that the initial state is as expected.   

c = [SELECT DVA_Affiliation_MDA_and_Active__c          

FROM Contact          

WHERE Id = :c.Id];   

System.assertEquals(null, c.DVA_Affiliation_MDA_and_Active__c);


   // Set up the Affiliation record.   

String affiliationName = 'Test Affiliation';   

Affiliation__c a = new Affiliation__c(Id=c.Id,                                     

Active__c=TRUE);


   // Insert Affiliation.   

insert a;    


   // Verify that the results are as expected.   

c = [SELECT FirstName, LastName, DVA_Affiliation_MDA_and_Active__c          

FROM Contact        

 WHERE Id = :c.Id];     

}

}

 

contact is contact

Affliliation__c is a related object where Contact is the master - contact can have more than one Affiliation record

DVA_Affiliation_MDA_and_Active__c is a number field the trigger fills in calulating on the Contact record how many affiliations the contact has

 

  • July 28, 2011
  • Like
  • 0

I have a parent object "admission form"

it has two related lists:

"survey 1"

"survey 2"

 

we would like to add a single field on survey 1 that concatenates 14 fields from survey 2

 

my difficulty is in accessing the data from survey 2

 

tried using a formula field but ran into difficulty with # of unique relationships per object (vlookup)

 

now trying visualforce, possibly with controller

any ideas?

  • July 14, 2011
  • Like
  • 0

is there a solution out there to convert Street to St., and Saint to St. as a user enters address information? Thanks

  • July 11, 2011
  • Like
  • 0

I am trying to figure out how to get my controller to retrieve the current record ID from the page (it is a sales order, the code below is to create an array out of its line items. Thanks if you can help!!

 

Here is the code (bold is where I have the problem):

 

 

public with sharing class SOL { 
    
    public SOL(ApexPages.StandardController controller) {
                        
    }
    
    Public List<PBSI__PBSI_Sales_Order_Line__c> getCustomObjs() {
        list<PBSI__PBSI_Sales_Order_Line__c> Arr_custom_obj=[select id, Name, PBSI__Quantity__c from PBSI__PBSI_Sales_Order_Line__c where PBSI__Sales_Order__c = 'a0aT0000004C1Em' ];
        return Arr_custom_obj;
    }

 

  • February 05, 2011
  • Like
  • 0

I have a custom object Test__c

 

I have a few custom fields as well that I put into a visualforce page to create a custom dropdown list. I then added the vf page to the object. What I am trying to do is to make a clone of this page to include the vf portion - the standard clone button does not clone the entire page w/ visualforce included:

 

**************************************************************************************************************************

 

 

<apex:page standardController="Test__c">
<style type="text/css"/>
  <apex:form >
    <apex:pageBlock title="Machine">
      
          <apex:commandButton value="Save" action="{!quickSave}" status="status"/>               <br></br>
          <p/>
          
          <h>Head 1: </h>
          <apex:inputField value="{!Test__c.test1__c}"/>
          <apex:inputField value="{!Test__c.TestA__c}"/>      
          <br></br>
          <p/>
      
          <h>Head 2: </h>
          <apex:inputField value="{!Test__c.test2__c}"/>
          <apex:inputField value="{!Test__c.TestB__c}"/>      
          <br></br>
          <p/> 
          
          <h>Head 3: </h>
          <apex:inputField value="{!Test__c.test2__c}"/>
          <apex:inputField value="{!Test__c.TestC__c}"/>      
          <br></br>
          <p/>
    
          </apex:pageBlock>
              
*************************************************************************************************************************** 
test pic
Is there a way to clone the entire thing?
 

 

  • January 19, 2011
  • Like
  • 0

http://wiki.developerforce.com/page/Sorting_Tables - this is some code developed by someone else - I found it online - I made very few changes and cannot get more that 61% coverage (with this or original) - it is failing at lines 17,18,21,22,23,42,43,46,47,49,50,52,74,75,77,78

 

I am not sure what to add to the tests in order to get the coverage up:

 

 

public class superSort {

 

    /*This method takes 3 arguments, the List of objects to sort, the field to sort,

    and the order, asc or desc*/

   

    public static void sortList(List<sObject> items, String sortField, String order){

        /*I must give credit where it is due as the sorting algorithm I am using is the

        one supplied by Andrew Waite here: http://blog.sforce.com/sforce/2008/09/sorting-collect.html */

       

        Boolean isSortFieldReference = false;

        Map<Id,String> referenceName;

        

        /*Determine the type of the field that needs to be sorted, if it is a

        reference we will want sort by the name of the related object, not the

        ID itself*/

        if(items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getType().Name() == 'REFERENCE'){

            isSortFieldReference = true;

            referenceName = new Map<Id,String>();

           

            /*Determine the type of this object and populate the Id to Name map*/

            Set<Id> referenceIds = new Set<Id>();

            for(sObject s : items){

               referenceIds.add((Id)s.get(sortField));

            }

           

            // DevAngel - EDIT - Because you may not have a value for the reference field in the first record

            // in the table you are sorting, this approach will fail on the substring method.  Below is

            // is a more reliable method using describe calls

            /*

            String objectID = (String)items[0].get(sortField);

            String prefix = objectID.substring(0,3);

            String objectType;

            Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

            for(Schema.SObjectType s : gd.values()){

                if(prefix == s.getDescribe().getKeyPrefix()){

                    objectType = s.getDescribe().Name;

                }

            }

            */

 

            // DevAngel - EDIT - New approach...

            List<Schema.Sobjecttype> objType = items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getReferenceTo();

            String objectType = objType[0].getDescribe().getName();

 

            //Query the related objects for the name and populate the Id -> Name map

            String queryString = 'select Id, Name from ' + objectType + ' where ID IN :referenceIDs';

            for(sObject s : Database.query(queryString )){

                // DevAngel - EDIT - if the reference field is null then we will not have a result, so we need to "create one"

                if (s.get('Name') == null) {

                    referenceName.put((Id)s.get('Id'), 'n/a');

                } else {

                    referenceName.put((Id)s.get('Id'),(String)s.get('Name'));

                }

            }

        }

               

        /*Declare a list that will contain the sorted results. I think this is one of the

        coolest parts of this method as the system will not let you declare a list of

        sObjects (List<sObject> objects = new List<sObjects>();) but using a

        wrapper class you can bypass this system limitation to create this type of list */

        List<cObject> resultList = new List<cObject>();

   

        //Create a map that can be used for sorting

        Map<object, List<cObject>> objectMap = new Map<object, List<cObject>>();

       

        for(sObject ob : items){

            if(isSortFieldReference == false){

                if(objectMap.get(ob.get(sortField)) == null){

                    objectMap.put(ob.get(sortField), new List<cObject>());

                }

                cObject o = new cObject(ob);

                objectMap.get(ob.get(sortField)).add(o);

            }else{

                if(objectMap.get(referenceName.get((Id)ob.get(sortField))) == null){

                    objectMap.put(referenceName.get((Id)ob.get(sortField)), new List<cObject>());

                }

                cObject o = new cObject(ob);

                objectMap.get(referenceName.get((Id)ob.get(sortField))).add(o);

            }

        }

       

        //Sort the keys

        List<object> keys = new List<object>(objectMap.keySet());

        keys.sort();

       

        for(object key : keys){

            resultList.addAll(objectMap.get(key));

        }

       

        //Apply the sorted values to the source list

        items.clear();

        if(order.toLowerCase() == 'asc'){

            for(cObject ob : resultList){

                items.add(ob.obj); 

            }

        }else if(order.toLowerCase() == 'desc'){

            for(integer i = resultList.size()-1; i >= 0; i--){

                items.add(resultList[i].obj);  

            }

        }

    }

   

    public class cObject{

        sObject obj {get; set;}

       

        public cObject(sObject obj){

            this.obj = obj;

        }

    }

   

    /*Some test methods that provide 100% coverage */

   

public static testMethod void sortAscendingTest(){

       

        List<Account> accs = new List<Account>();

        for(integer i = 0; i<1000; i++){

            accs.add(new Account(Name = 'test' + i, Annualized_Revenue__c = 1000 * Math.random()));

        }

       

        Test.startTest();

        Long start = system.currentTimeMillis();

        sortList(accs,'Annualized_Revenue__c','asc');

        system.debug(system.currentTimeMillis() - start);

        Test.stopTest();

       

        //Assert the list was sorted correctly

        Decimal assertValue = -1;

        for(Account a : accs) {

            System.debug('Acc value: ' + a.Annualized_Revenue__c);

            System.assert(assertValue <= a.Annualized_Revenue__c);

            assertValue = a.Annualized_Revenue__c;

        } 

    }

  

   

public static testMethod void sortDescendingTest(){

       

       

        List<Account> accs = new List<Account>();

        for(integer i = 0; i<1000; i++){

            accs.add(new Account(Name = 'test' + i, Annualized_Revenue__c = 1000 * Math.random()));

        }

       

        Test.startTest();

        sortList(accs,'Annualized_Revenue__c','desc');

        Test.stopTest();

       

        //Assert the list was sorted correctly

        Decimal assertValue = 1001;

        for(Account a : accs) {

            System.debug('Opp value: ' + a.Annualized_Revenue__c);

            System.assert(assertValue >= a.Annualized_Revenue__c);

            assertValue = a.Annualized_Revenue__c;

        } 

    }

}

 

 

  • November 17, 2011
  • Like
  • 0

Hello,

 

I have a trigger that inserts a new Opportunity whenever a campaign member is selected for a certain campaign type. The difficulty I am having is in getting the Account name into the Account field on Opportunity. I can seem to only get the ID option to work correctly, but that is not what I want - here is the code: 

 

trigger createOpportunityCampaignMember on CampaignMember (after insert)

{

    date myDate =

     date.today();

    date newDate = mydate.addDays(180);

 

    List<Opportunity> op = new List<Opportunity>();

        for (CampaignMember newCampaignMember: Trigger.New)

         if (newCampaignMember.RecordTypeID == '01250000000Dtga')//record type for marketing campaign member

           

         {

            op.add (

                    new Opportunity

                        (

                            AccountId = newCampaignMember.Contact.AccountId,

                            Name = newCampaignMember.Contact.AccountId + ' Marketing Lead',

                            RecordTypeID = '01250000000DcJk', //BDS Leads

                            StageName = 'Submit Lead for Verification',

                            CloseDate = newDate,

                            Campaign = newCampaignMember.Campaign

            

                        )

                    );

                    

            insert op;

         }

        

        

 

  • September 22, 2011
  • Like
  • 0

is it possible to use a trigger/apex to create an opportunity automatically from a contact once a contact is created?

  • September 16, 2011
  • Like
  • 0

I have a parent object "admission form"

it has two related lists:

"survey 1"

"survey 2"

 

we would like to add a single field on survey 1 that concatenates 14 fields from survey 2

 

my difficulty is in accessing the data from survey 2

 

tried using a formula field but ran into difficulty with # of unique relationships per object (vlookup)

 

now trying visualforce, possibly with controller

any ideas?

  • July 14, 2011
  • Like
  • 0

is there a solution out there to convert Street to St., and Saint to St. as a user enters address information? Thanks

  • July 11, 2011
  • Like
  • 0

I am trying to figure out how to get my controller to retrieve the current record ID from the page (it is a sales order, the code below is to create an array out of its line items. Thanks if you can help!!

 

Here is the code (bold is where I have the problem):

 

 

public with sharing class SOL { 
    
    public SOL(ApexPages.StandardController controller) {
                        
    }
    
    Public List<PBSI__PBSI_Sales_Order_Line__c> getCustomObjs() {
        list<PBSI__PBSI_Sales_Order_Line__c> Arr_custom_obj=[select id, Name, PBSI__Quantity__c from PBSI__PBSI_Sales_Order_Line__c where PBSI__Sales_Order__c = 'a0aT0000004C1Em' ];
        return Arr_custom_obj;
    }

 

  • February 05, 2011
  • Like
  • 0

Hello all,

 

I am a newbie SFDC developer and desperately trying to learn Apex and Visualforce programming.

Is there any book for those new to this field?

 

Any suggestions on where to get this is much appreciated.

 

Thanks a lot,

VK86 

  • February 02, 2010
  • Like
  • 0