• DevGarethmd
  • NEWBIE
  • 100 Points
  • Member since 2008

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

And I though test classes were easy....

 

I am writing a Test Class for a Trigger which updates the count of a child object in the parent object. Except the Test Class does not seem to pass.

 

The parent and child are both Accounts, where the child record is identified by a lookup field to the parent record. When I change an Account to be a child of another Account, the trigger fires an update of the count in the parent record.

 

The test class runs a very simple test, which creates two Accounts (A and B), then updates the lookup in B to point to A. This should cause the Trigger to run, which would update the count on the parent Account, A.

 

However, the test class fails, as the count on the parent is still NULL.

 

I have performed the same test manually and it works - the count on the parent Account is definitely increased.

 

So why does the Test Class fail??

 

Here is the class:

@isTest
private class TestDepartmentCountChange {

static testMethod void testCountChange() {

Account companya = new Account(Name = 'Company A', RecordTypeId = '01220000000Dqq7');
insert companya;

Account companyb = new Account(Name = 'Company B', RecordTypeId = '01220000000Dqq7', Department__c = TRUE, Parent_Company__c = companya.id);
insert companyb;

//system.assert(companya.No_of_Departments__c == NULL);

//companyb.Department__c = TRUE;
//companyb.Parent_Company__c = companya.id;
//update companyb;

system.assert(companya.No_of_Departments__c == 1);

companyb.Department__c = FALSE;
companyb.Parent_Company__c = NULL;
update companyb;

system.assert(companya.No_of_Departments__c == NULL);

}
}

 And here is the Trigger:

trigger DepartmentSumTrigger2 on Account (after delete, after insert, after undelete,
after update) {

    // When deleting a Department use the previous values
    Account[] dept;
    if (Trigger.isDelete){
        dept = Trigger.old;
    }
  
    else
        dept = Trigger.new;
    

   
    // Get a list of all Accounts that are Parent Companies
    Set<ID> acctIds = new Set<ID>();
    for (Account dep :dept) {
        acctIds.add(dep.Parent_Company__c);
    }
    
    // Fill a Map with a list of all Departments
    Map<ID, Account> departmentsForAccounts = 
    new Map<ID, Account>([SELECT Id, Parent_Company__c FROM Account WHERE Department__c = TRUE AND Parent_Company__c IN :acctIds]);
    
    // Fill a map with a list of all Parent Companies
    Map<ID, Account> acctsToUpdate = 
    new Map<ID, Account>([SELECT Id, No_of_Departments__c FROM Account WHERE Id IN :acctIds]);
    
    // For all Parent Companies            
    for (Account acct : acctsToUpdate.values()) {
        Set<ID> depIds = new Set<ID>();
        for (Account dep : departmentsForAccounts.values()) {
            if (dep.Parent_Company__c == acct.Id)
                depIds.add(dep.Id);
        }
        if (acct.No_of_Departments__c != depIds.size())
            acct.No_of_Departments__c = depIds.size();
    }

    update acctsToUpdate.values();

}



I have two page layouts (standard detail pages, not Visualforce) for Case. The user by default gets the first page layout when he clicks on a case number. The first page layout has very few fields (max 10). A button on the detail page should take him to the second page layout where there many more fields from the Case object (~50). Is there any way this can be achieved using minimal coding? Here are the options I have already explored

- Changing record type on th case record on click of the button [Unnecessary update on the record]

- Tried changing profile of the logged in user [Apex exception - cannot change logged in user's profile id]

- Creating one of the page layouts as a visual force page [Code maintenance cost is high]

 

Are there any other ideas with minimal coding that can be explored?

  • July 19, 2011
  • Like
  • 0

I have a trigger which is meant to update a field in a Case based on the Role or Type of the NEW owner when the case is transferred in ownership. However, it appears to be updating the field with the OLD owner's information. The end result is that the case will be transferred to the new user, but the role/type of the old user gets written to the updated field.

 

Clearly this means I'm doing something out of order, but I'm at the point now where I'm so frazzled I'm not going to figure it out until someone points out what I'm doing wrong. Any help is greatly appreciated.

 

Here's the code:



trigger getCaseOwner on Case (before update, before insert) {
    Case oldCase = trigger.old[0];
    Case newCase = trigger.new[0];
    String newOwnerId = newCase.OwnerId;
    String oldOwnerId = oldCase.OwnerId;
    
    String newOwnerRole = '';
    String newOwnerType;
    
    newOwnerType = [select owner.type from case where id = :newCase.Id].owner.type;
    
    if ( newOwnerType == 'User' ) {
        newOwnerRole = [select u.UserRole.Name from User u where u.Id = :newOwnerId limit 1].UserRole.Name;
    } else if ( newOwnerType == 'Queue' ) {
        newOwnerRole = newCase.owner.name + ' Queue';
    }
    
    newCase.Case_Owner_Role__c = newOwnerType;
}

 

I have a custom object Deal__c and a standard object Contact.  The I created a custom lookup field Contact in the Deal__c object (related to Contact object).  Then I went to Deal__c page layout and added Contact to Selected Relationship Fields.
 
At this point I would like to display all contacts that are related to a particular Deal.
 
<apex:page standardController="Deal__c">
   <apex:pageBlock title="Hello {!$User.FirstName}!">
      You are viewing the {!Deal__c.name} deal.
   </apex:pageBlock>
   <apex:pageBlock title="Contacts">
      <apex:pageBlockTable value="{!Deal__c.Contact}" var="contact">
         <apex:column value="{!contact.Name}"/>
         <apex:column value="{!contact.MailingCity}"/>
         <apex:column value="{!contact.Phone}"/>
      </apex:pageBlockTable>
   </apex:pageBlock>
</apex:page>
 
As a result I get an error message: 
Error: Invalid field Contact for SObject Deal__c
 
If I change {!Deal__c.Contact} to {!Deal__c.Contact__c} then I get a different error message: 
Error: Unknown property 'String.Name'
 
Where am I going wrong here?
 
Appreciate any suggestions
 
  • October 17, 2008
  • Like
  • 0

I have an issue with using subqueries and am trying to establish whether this is a bug or not. Basically if I have a subquery then I can't directly access the list if the subquery contains more than 200 records a QueryException is thrown (Aggregate query has too many rows for direct assignment use for loop). If there are less than 200 records everything works fine. To illustrate the point the following code will fail when acct.contacts.size() is called

 

Account accToTest = new Account(name = 'testAccount');
insert accToTest;

list<Contact> contacts = new list<Contact>();

for(integer x=0;x<200;x++){
contacts.add(new Contact(AccountId = accToTest.id,
firstName = 'test' + x.format(),
lastName = 'name'));
}
insert contacts;

Test.StartTest();

for(Account acct : [select id,
name,
(select firstName from Contacts)
from Account
where id =: accToTest.id]){
system.debug(acct.contacts.size());
}

Test.StopTest();

I know that there are workarounds by iterating through the contacts list but this seems to be more expensive generating additional script statements. I have also seen a  Post from earlier in the year that described a similar problem, but was isolated to batch classes, whereas this appears to be more general.

 

Can anyone tell me if this is designed behaviour or if this is a bug in the platform.

 

Thanks

Gareth

I've been able to get the pagination to work with a custom controller, however there seem to be some limitations that restrict its use that i wanted to check to make sure that i am correct.

Firstly, pagination only works if you instantiate the setController from a query locator using Database.getQueryLocator. If you instantiate using a list of sObjects then the pagination is ignored and the whole recordset is returned. This is kind of a shame as the getQueryLocator does not accept dynamic SOQL, so if you want to build a fairly sophisticated search facility with paginated results then it does not appear to be possible using this method.

Secondly, you are also not able to use lists of wrapper classes that contain results sets. For example if you wanted to allow the user to select multiple records from a search result my understanding is that the only way to do this is to construct a wrapper class that contains both the sobject and a boolean field to indicate whether the record has been selected. Since a StandardSetController can only be instantiated using Sobjects, pagination again does not appear possible.

Can anyone confirm if my understanding is correct and if it is, then how would i go about developing a paginated solution for these scenarios?

Thanks
Gareth

Hi,

  I have a Inline VF Page from an Object. when i want to view a record(detail page), i want to update a field in other Object. Is this possible? becoz i have been trying and if i have a update statemnet in the method the InLine Vf Page content is not displaying. The error is Content cannot be displayed: DML currently not allowed . Any idea about this?

 

 

Cheers

 

Bramha

 

And I though test classes were easy....

 

I am writing a Test Class for a Trigger which updates the count of a child object in the parent object. Except the Test Class does not seem to pass.

 

The parent and child are both Accounts, where the child record is identified by a lookup field to the parent record. When I change an Account to be a child of another Account, the trigger fires an update of the count in the parent record.

 

The test class runs a very simple test, which creates two Accounts (A and B), then updates the lookup in B to point to A. This should cause the Trigger to run, which would update the count on the parent Account, A.

 

However, the test class fails, as the count on the parent is still NULL.

 

I have performed the same test manually and it works - the count on the parent Account is definitely increased.

 

So why does the Test Class fail??

 

Here is the class:

@isTest
private class TestDepartmentCountChange {

static testMethod void testCountChange() {

Account companya = new Account(Name = 'Company A', RecordTypeId = '01220000000Dqq7');
insert companya;

Account companyb = new Account(Name = 'Company B', RecordTypeId = '01220000000Dqq7', Department__c = TRUE, Parent_Company__c = companya.id);
insert companyb;

//system.assert(companya.No_of_Departments__c == NULL);

//companyb.Department__c = TRUE;
//companyb.Parent_Company__c = companya.id;
//update companyb;

system.assert(companya.No_of_Departments__c == 1);

companyb.Department__c = FALSE;
companyb.Parent_Company__c = NULL;
update companyb;

system.assert(companya.No_of_Departments__c == NULL);

}
}

 And here is the Trigger:

trigger DepartmentSumTrigger2 on Account (after delete, after insert, after undelete,
after update) {

    // When deleting a Department use the previous values
    Account[] dept;
    if (Trigger.isDelete){
        dept = Trigger.old;
    }
  
    else
        dept = Trigger.new;
    

   
    // Get a list of all Accounts that are Parent Companies
    Set<ID> acctIds = new Set<ID>();
    for (Account dep :dept) {
        acctIds.add(dep.Parent_Company__c);
    }
    
    // Fill a Map with a list of all Departments
    Map<ID, Account> departmentsForAccounts = 
    new Map<ID, Account>([SELECT Id, Parent_Company__c FROM Account WHERE Department__c = TRUE AND Parent_Company__c IN :acctIds]);
    
    // Fill a map with a list of all Parent Companies
    Map<ID, Account> acctsToUpdate = 
    new Map<ID, Account>([SELECT Id, No_of_Departments__c FROM Account WHERE Id IN :acctIds]);
    
    // For all Parent Companies            
    for (Account acct : acctsToUpdate.values()) {
        Set<ID> depIds = new Set<ID>();
        for (Account dep : departmentsForAccounts.values()) {
            if (dep.Parent_Company__c == acct.Id)
                depIds.add(dep.Id);
        }
        if (acct.No_of_Departments__c != depIds.size())
            acct.No_of_Departments__c = depIds.size();
    }

    update acctsToUpdate.values();

}



Currently examining an update that we want to make to our system where daily, our system checks the date of particular items, and if they're past the current date, an action is ran. I've been looking into batch apex and some other features of SF trying to determine what may be the best route for this, and was curious as to whether batch apex would be the best route for this? Can anyone shine some possible light on what the best instances are to use batch apex?

 

Thanks!

I have two page layouts (standard detail pages, not Visualforce) for Case. The user by default gets the first page layout when he clicks on a case number. The first page layout has very few fields (max 10). A button on the detail page should take him to the second page layout where there many more fields from the Case object (~50). Is there any way this can be achieved using minimal coding? Here are the options I have already explored

- Changing record type on th case record on click of the button [Unnecessary update on the record]

- Tried changing profile of the logged in user [Apex exception - cannot change logged in user's profile id]

- Creating one of the page layouts as a visual force page [Code maintenance cost is high]

 

Are there any other ideas with minimal coding that can be explored?

  • July 19, 2011
  • Like
  • 0

I have a trigger which is meant to update a field in a Case based on the Role or Type of the NEW owner when the case is transferred in ownership. However, it appears to be updating the field with the OLD owner's information. The end result is that the case will be transferred to the new user, but the role/type of the old user gets written to the updated field.

 

Clearly this means I'm doing something out of order, but I'm at the point now where I'm so frazzled I'm not going to figure it out until someone points out what I'm doing wrong. Any help is greatly appreciated.

 

Here's the code:



trigger getCaseOwner on Case (before update, before insert) {
    Case oldCase = trigger.old[0];
    Case newCase = trigger.new[0];
    String newOwnerId = newCase.OwnerId;
    String oldOwnerId = oldCase.OwnerId;
    
    String newOwnerRole = '';
    String newOwnerType;
    
    newOwnerType = [select owner.type from case where id = :newCase.Id].owner.type;
    
    if ( newOwnerType == 'User' ) {
        newOwnerRole = [select u.UserRole.Name from User u where u.Id = :newOwnerId limit 1].UserRole.Name;
    } else if ( newOwnerType == 'Queue' ) {
        newOwnerRole = newCase.owner.name + ' Queue';
    }
    
    newCase.Case_Owner_Role__c = newOwnerType;
}

 

I have a custom object Deal__c and a standard object Contact.  The I created a custom lookup field Contact in the Deal__c object (related to Contact object).  Then I went to Deal__c page layout and added Contact to Selected Relationship Fields.
 
At this point I would like to display all contacts that are related to a particular Deal.
 
<apex:page standardController="Deal__c">
   <apex:pageBlock title="Hello {!$User.FirstName}!">
      You are viewing the {!Deal__c.name} deal.
   </apex:pageBlock>
   <apex:pageBlock title="Contacts">
      <apex:pageBlockTable value="{!Deal__c.Contact}" var="contact">
         <apex:column value="{!contact.Name}"/>
         <apex:column value="{!contact.MailingCity}"/>
         <apex:column value="{!contact.Phone}"/>
      </apex:pageBlockTable>
   </apex:pageBlock>
</apex:page>
 
As a result I get an error message: 
Error: Invalid field Contact for SObject Deal__c
 
If I change {!Deal__c.Contact} to {!Deal__c.Contact__c} then I get a different error message: 
Error: Unknown property 'String.Name'
 
Where am I going wrong here?
 
Appreciate any suggestions
 
  • October 17, 2008
  • Like
  • 0
I would like to know if it's possible to put a visual force page in the dashboard.

Thank you.
To whom it may concern
 
Is it possible to have mutli tabs in a single visualforce page
  • October 16, 2008
  • Like
  • 0
We have a custom object that maintains a one-to-one relationship with the Contact object for contacts of a certain RecordType.  For these special contacts, we want to display the related custom object record as another detail section right below the Contact detail section.  We do not want to override the Contact page for all contacts, just for this one record type.  Unfortunately, there is no way to override View/Edit/etc for a specific record type, but Winter '09 does give us the ability to embed a Visualforce page within a page section on a standard page layout.  So, I created a page layout for our special record type and got busy...
 
Unfortunately, there is no way to make the page section expand to accomodate the contents -- you can give 100% width, but you have to provide a static height in pixels...... but that's another story, and not my current problem.
 
The problem is that, while the embedded custom detail section displays okay in View mode, when you click the embedded Edit button, another copy of the Salesforce header and sidebar are displayed in the page section, so you now have nested headers and sidebars.  Ah, but you immediately think you can get around this by replacing the custom object's default Edit button with a custom one that turns off the header and sidebar... no dice.  In fact, in this case if you don't turn off the header and sidebar you end up with an additional nest resulting in a total of three headers and sidebars.
 
Then I tried overriding the custom object's Edit with a simple Visualforce page that turns off the header and sidebar... but the page comes up in View mode unless you populate the <apex: page action="{!edit}"> attribute.  What *this* does is put you in an endless loop of calling the VF page and placing it in Edit mode over and over.
 
Tried every combination I can think of.  Doesn't play nice.  Does anyone know how to embed a Visualforce page in a page layout section that allows Edit without the extra header and sidebar?
 
Or even better, is there in fact a way to override View/Edit for a certain record type?  Then I could totally customize my page without all this fixed-height-embedding crap. :-)