function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhishek RayAbhishek Ray 

Apex trigger: Auto populating a field



I have created a trigger tfor custom object to auto populate the owner name (lookup) in another field under same object,


Here is the code:


trigger setOwnerName on Partnership__c (before insert) {
Map<Id,String> userMap = new Map<Id, String>();     
for (User u : [Select Id, Name From User]) 
userMap.put(u.Id, u.Name);  
for (Partnership__c a : Trigger.New)
 if(a.Account__c == 'AAA Drawloop Testing')
 a.Owner_Name__c = userMap.get(a.OwnerId);   



I created a test trigger but I am getting error : System.StringException: Invalid id: AAA Drawloop Testing


private class setOwnerNameTest{
    public static TestMethod void OwnerNameinsert(){
           Partnership__c acc = new Partnership__c();
           acc.Account__c = 'AAA Drawloop Testing';
           insert acc;
           Partnership__c accNew = new Partnership__c(); 
           accNew.Account__c = 'AAA Drawloop Testing';
           insert accNew; 
           system.assert( == null); 


What I am doing wrong. Please help?


First, here is a small rewrite of the trigger to optimize it:


trigger setOwnerName on Partnership__c (before insert) {

Map<Id,User> userMap = new Map<Id, User>([Select Id, Name From User Where ID IN (Select OwnerID From Partnership__c Where ID IN]);     

for (Partnership__c a : Trigger.New)
 if(a.Account__c == 'ACCTID')
        a.Owner_Name__c = userMap.get(a.OwnerId).Name;   





In the test class you need to create the account, then put that ID in Account__c


private class setOwnerNameTest{
    public static TestMethod void OwnerNameinsert(){
           Partnership__c acc = new Partnership__c();
           Account acct = New Account(
              Name = 'Test Account',
            Insert acct; 
          acc.Account__c = acct.ID;
           insert acc;
           Partnership__c accNew = new Partnership__c(); 
           accNew.Account__c = acctID;
           insert accNew; 
           system.assert( == null);