• Learning Apex (OOP)
  • NEWBIE
  • 50 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 26
    Replies
Could someone please explain how the .split method works in a String?

I am facing this line in a code:
String domain = myContact.Email.split('@').get(1);
I believe it is trying to capture the domain of an email address (and assign it to the variable domain), so if the email address is, for example: firstName.LastName@salesforce.com, the above line of code is probably capturing the domain 'salesforce.com' and assigns it to the variable.

But how does it do it? How does this .split method works= I do not understand this bit: .split('@').get(1);

When looking at Salesforce String methods here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm , and searching by .split, I find the following method/description:

User-added image
so, even if I do not understand how could this method possibly return a "list", I sort of guess that it returns a substring that is terminated by a regular expression that, in my line of code would be '@' ? But, this does not make sense in my line of code as the substring in it that terminates with '@' would in fact be firstName.LastName (not salesforce.com). 

Also, what is the .get(1) doing in this line of code?

Thank you very much.
Hello, I need to understand WHY my first code below (b) does NOT work.

(a) Here is the functional requirement: when creating a new Case, I want the related Contact (parent) to have its Owner updated with the Case's CreatedBy user, in other words, the Case's CreatedBy will be used to update the Contact's Owner.

(b) Here is the code that does NOT work
trigger CaseContactOwner on Case (after insert){
    for(Case myCase:Trigger.new){
        if(myCase.ContactId != null){
            myCase.Contact.OwnerId = myCase.CreatedById;
        }
    } 
}

(c) Here is the solution (the code that DOES works fine):
trigger CaseContactOwner on Case (after insert) {
    for(Case myCase:Trigger.new){
        // Make sure the Case has an Contact
        if(myCase.ContactId != null){
            // Find the contact for updating
            Contact myContact = [SELECT Id
                                   FROM Contact
                                   WHERE Id = :myCase.ContactId];
            // Update the Contact
            myContact.OwnerId = myCase.CreatedById;
        }
    }
}

My question is:

As the trigger is an "after insert" trigger, I would have thought that Line 4 (of my first code b) would work fine:
myCase.Contact.OwnerId = myCase.CreatedById;
//this would assign the value in CreatedById on my new Case to the Owner of the associated Contact of my Case.

But that does NOT work and I do not understand why.

The solution seem to be (c) where I have to query on the table Contact and store the resulting record on a SObject variable (myContact) which I eventually use to reference the Owner of the Contact.
Is it really necessary to do all this query?

Thank you very much.
Hello,

I am getting the following error message when detonating this trigger below:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger OpportunityTeamMembers caused an unexpected exception, contact your administrator: OpportunityTeamMembers: execution of BeforeInsert caused by: System.ListException: Before Insert or Upsert list must not have two identically equal elements: Trigger.OpportunityTeamMembers: line 28, column 1​
 
trigger OpportunityTeamMembers on Opportunity (before insert) {
    List<OpportunityTeamMember> myOpptyTeamMembers = new List <OpportunityTeamMember>();
    for(Opportunity myOpp : Trigger.new){
        //Create an Oppty Team Member
        OpportunityTeamMember otm = new OpportunityTeamMember();
        otm.opportunityId = myOpp.Id;
        // If a Manager exist, add it to the list of myOpptyTeamMembers
        if(myOpp.Owner.ManagerId != null){
            otm.userId = myOpp.owner.ManagerId;
            otm.TeamMemberRole = 'Sales Manager';
            myOpptyTeamMembers.add(otm);
        }
        // If Dependents exist, add it/them to the list of myOpptyTeamMembers
        List<User> dependentUsers = [SELECT Id
                                     FROM User
                                     WHERE ManagerId = :myopp.OwnerId];
        if(dependentUsers.size()>0){
            // Loop on dependentUsers List
            OpportunityTeamMember otm2 = new OpportunityTeamMember();
            for(User myDependentUser : dependentUsers){
                otm2.UserId         = myDependentUser.Id;
                otm2.TeamMemberRole = 'Sales Rep';
                myOpptyTeamMembers.add(otm2);
            }
        }
    }
    // Add/Insert Team Members to the myOpp
    insert myOpptyTeamMembers;
}

According to the error message, it sounds like I am trying to insert a List (myOpptyTeamMembers) with two identical items (?).
I guess that, to Salesforce, two identical items would be identicals if their Id were the same, right? This would mean that, in myOpptyTeamMembers (which is the list I am inserting at the end of the code), there are 2 records Opportunity Team Members with the same Id?
How could this be possible?
Any clue?
(Thank you very much)
I have an apex trigger which does not align (AT ALL!) with Salesforce "Best Practice" of never having queries and/or DMLs inside a 'for' loop.

I know this theory but, as I am new to coding, I need to break the ice and put this theory into practice (for the first time of my life) and I would like to ask if there is a "Best approach" to doing precisely that (moving SOQL-queries and/or DMLs outside the 'for' loop on 'Trigger.new', or for that matter, to move them from any loop).

Is there any approach, guide, video that could teach me to learn this "optimization process" of my code?

Below, here is my trigger (but please, do not give me the whole solution yet/inmediately, I am looking for a guide for me to try putting it into practice); thank you!:

==>This trigger adds Team Members to an Opportunity upon creation of that new Opportunity:
trigger OwnerManager on Opportunity (after insert) {
    for(Opportunity opp : Trigger.new){
        //Get opp Owner.Manager info
        Opportunity oppWithManagerInfo = [SELECT Id,
                                          Owner.ManagerId
                                          FROM Opportunity
                                          WHERE Id = :opp.Id];
        //Get opp Owner direct dependents
        List<user> directDependents = [SELECT Id
                                       FROM user
                                       WHERE ManagerId = :opp.OwnerId
                                       LIMIT 1];
        //Create Opportunity Team Role
        if (oppWithManagerInfo.Owner.ManagerId != null) {
            OpportunityTeamMember otm = new OpportunityTeamMember();
            otm.UserId                = oppWithManagerInfo.Owner.ManagerId;
            otm.OpportunityId         = opp.Id;
            otm.TeamMemberRole        = 'Sales Manager';
            insert otm;
            //Create another Opportunity Team Role with directDependent
            if (directDependents.size()>0){
                OpportunityTeamMember otm2 = new OpportunityTeamMember();
                otm2.UserId                = directDependents[0].Id;
                otm2.OpportunityId         = opp.Id;
                otm2.TeamMemberRole        = 'Sales Rep.';
                insert otm2;
            }
        }
    }
}

 
Hello,
I am very new to programming and am learning to code with apex.
If you have experience in coding with apex, you will observe that the following code breaches many good practices' rules but, for now, I do not care (this is not about good practices, this question is about the error); I am just trying to understand WHY am I getting this error (Variable does not exit: Id)
I think it might have something to do with the "scope" of the code where this variable is being referenced but, I still need understand and to learn how to avoid these kind of issue in the future.

Could you possibly explain in plain English (for a beginner), why is this error being produced and how to avoid it?

Thank you very much. Here is the code:
trigger OwnerManager on Opportunity (after insert) {
    for(Opportunity opp : Trigger.new){
        //Get opp owner manager info
        Opportunity oppWithManagerInfo = [SELECT Id,
                                          Owner.ManagerId
                                          FROM Opportunity
                                          WHERE Id = :opp.Id];
        //Get opp owner direct dependents
        List<user> directDependents = [SELECT Id
                                       FROM user
                                       WHERE ManagerId = :opp.OwnerId
                                       LIMIT 1];
        //Create Opportunity Team Role
        if (oppWithManagerInfo.Owner.ManagerId != null) {
            OpportunityTeamMember otm = new OpportunityTeamMember();
            otm.UserId                = oppWithManagerInfo.Owner.ManagerId;
            otm.OpportunityId         = opp.Id;
            otm.TeamMemberRole        = 'Sales Manager';
            insert otm;
            //Create another Opportunity Team Role with directDependent
            if (directDependents.size()>0){
                OpportunityTeamMember otm2 = new OpportunityTeamMember();
                otm2.UserId                = directDependents.Id; // HERE is the error
                otm.OpportunityId          = opp.Id;
                otm.TeamMemberRole         = 'Sales Rep.';
                insert otm2;
            }
        }
    }
}

 
Hello,

The apex code below is resolving the following requirement (specified as an exercises for practice):

When an opportunity is inserted, automatically add the Oppty's Owner's Manager as a Team Member (of the Opportunity being inserted), with the role "Sales Manager".

The solution provided by the exercise's author is below:
trigger OwnerManager on Opportunity (after insert) {
    for(Opportunity opp : Trigger.new){
        //Get opp owner manager info
        Opportunity oppWithManagerInfo = [SELECT Id,
                                                 Owner.ManagerId
                                            FROM Opportunity
                                           WHERE Id = :opp.Id];
        //Create Opportunity Team Role
        if (oppWithManagerInfo.Owner.ManagerId != null) {
            OpportunityTeamMember otm = new OpportunityTeamMember();
            otm.UserId                = oppWithManagerInfo.Owner.ManagerId;
            otm.OpportunityId         = opp.Id;
            otm.TeamMemberRole        = 'Sales Manager';
            insert otm;
        }
    }
}
My question is regarding Line 7 --> WHERE Id = :opp.Id

The question is: since the trigger is an "after" trigger, from what I have learnt regarding "after" trigger, you would need to first INSERT the value contained in the variable opp (insert opp;) in order for Salesforce to generate an Id for that record. So, I would have thought that Line 7 would only work after opp has been inserted in the data base.

But, the above code seems to work fine, that is why I am perplexed and would like to understand how can the system know the opp.Id before the opp record has even been inserted by the apex code.

Thank you very much.
Hi,

How do you "read" (in plane English) this piece of code?
List<OpportunityShare> oppShareList = [select Id, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId IN :opportunityIdList and RowCause = 'Team'];
My interpretation is...

Create a variable of the type List<OpportunityShare> which is called oppShareList and assign the following records to such list: all records (display the fields Id, OpportunityAccessLevel, etc...) FROM the table OpportunityShare WHERE ...????

I do not understand the code after the WHERE

Could someone explain?

Thank you very much.


 
Hello,
I am getting the above error message when creating a new Opportunity.

I seems obvious by the nature of the error that there is a missing value on a required field somewhere, but I am not sure how this error message has to be interpreted exactly. Does  it mean that a value on a field "User" on the Opportunity object is missing?
The only "user"-like field I can think of in the Opportunity is the Owner (?) but I would have thought that the Owner is automatically set to the running user right after creating the myOpp.

Here is my apex  trigger:

trigger AddTeamMember on Opportunity (before insert) {
    // Create Account to relate it to the Oppty
    Account acc = new Account();
    acc.Name = 'Test'+' '+ System.today();
    //Every time we insert a new Oppty
    for(Opportunity myOpp : Trigger.new){
        // Assign values to required fields of Oppty
        myOpp.Name = 'Test'+' '+ System.today();
        myOpp.AccountId = acc.Id; 
        myOpp.CloseDate = System.today().addDays(10);
        myOpp.StageName = 'Negotiation/Review';
        // Add one Team Member to myOpp
        OpportunityTeamMember myTeamMember = new OpportunityTeamMember();
        myTeamMember.OpportunityId = myOpp.id;
        myTeamMember.OpportunityAccessLevel = 'Read';
        myTeamMember.TeamMemberRole = 'Sales Manager”';
        myTeamMember.UserId = '0050Y000002MN2F'; //myOpp.Owner.ManagerId
        insert myTeamMember;
    }
}


Here is a screenshot of  the error on the Opportunit object:
error due to trigger on Oppty:
User-added image

Can you spot the error on my trigger?
Could someone please explain how the .split method works in a String?

I am facing this line in a code:
String domain = myContact.Email.split('@').get(1);
I believe it is trying to capture the domain of an email address (and assign it to the variable domain), so if the email address is, for example: firstName.LastName@salesforce.com, the above line of code is probably capturing the domain 'salesforce.com' and assigns it to the variable.

But how does it do it? How does this .split method works= I do not understand this bit: .split('@').get(1);

When looking at Salesforce String methods here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm , and searching by .split, I find the following method/description:

User-added image
so, even if I do not understand how could this method possibly return a "list", I sort of guess that it returns a substring that is terminated by a regular expression that, in my line of code would be '@' ? But, this does not make sense in my line of code as the substring in it that terminates with '@' would in fact be firstName.LastName (not salesforce.com). 

Also, what is the .get(1) doing in this line of code?

Thank you very much.
Hello, I need to understand WHY my first code below (b) does NOT work.

(a) Here is the functional requirement: when creating a new Case, I want the related Contact (parent) to have its Owner updated with the Case's CreatedBy user, in other words, the Case's CreatedBy will be used to update the Contact's Owner.

(b) Here is the code that does NOT work
trigger CaseContactOwner on Case (after insert){
    for(Case myCase:Trigger.new){
        if(myCase.ContactId != null){
            myCase.Contact.OwnerId = myCase.CreatedById;
        }
    } 
}

(c) Here is the solution (the code that DOES works fine):
trigger CaseContactOwner on Case (after insert) {
    for(Case myCase:Trigger.new){
        // Make sure the Case has an Contact
        if(myCase.ContactId != null){
            // Find the contact for updating
            Contact myContact = [SELECT Id
                                   FROM Contact
                                   WHERE Id = :myCase.ContactId];
            // Update the Contact
            myContact.OwnerId = myCase.CreatedById;
        }
    }
}

My question is:

As the trigger is an "after insert" trigger, I would have thought that Line 4 (of my first code b) would work fine:
myCase.Contact.OwnerId = myCase.CreatedById;
//this would assign the value in CreatedById on my new Case to the Owner of the associated Contact of my Case.

But that does NOT work and I do not understand why.

The solution seem to be (c) where I have to query on the table Contact and store the resulting record on a SObject variable (myContact) which I eventually use to reference the Owner of the Contact.
Is it really necessary to do all this query?

Thank you very much.
Hello,

I am getting the following error message when detonating this trigger below:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger OpportunityTeamMembers caused an unexpected exception, contact your administrator: OpportunityTeamMembers: execution of BeforeInsert caused by: System.ListException: Before Insert or Upsert list must not have two identically equal elements: Trigger.OpportunityTeamMembers: line 28, column 1​
 
trigger OpportunityTeamMembers on Opportunity (before insert) {
    List<OpportunityTeamMember> myOpptyTeamMembers = new List <OpportunityTeamMember>();
    for(Opportunity myOpp : Trigger.new){
        //Create an Oppty Team Member
        OpportunityTeamMember otm = new OpportunityTeamMember();
        otm.opportunityId = myOpp.Id;
        // If a Manager exist, add it to the list of myOpptyTeamMembers
        if(myOpp.Owner.ManagerId != null){
            otm.userId = myOpp.owner.ManagerId;
            otm.TeamMemberRole = 'Sales Manager';
            myOpptyTeamMembers.add(otm);
        }
        // If Dependents exist, add it/them to the list of myOpptyTeamMembers
        List<User> dependentUsers = [SELECT Id
                                     FROM User
                                     WHERE ManagerId = :myopp.OwnerId];
        if(dependentUsers.size()>0){
            // Loop on dependentUsers List
            OpportunityTeamMember otm2 = new OpportunityTeamMember();
            for(User myDependentUser : dependentUsers){
                otm2.UserId         = myDependentUser.Id;
                otm2.TeamMemberRole = 'Sales Rep';
                myOpptyTeamMembers.add(otm2);
            }
        }
    }
    // Add/Insert Team Members to the myOpp
    insert myOpptyTeamMembers;
}

According to the error message, it sounds like I am trying to insert a List (myOpptyTeamMembers) with two identical items (?).
I guess that, to Salesforce, two identical items would be identicals if their Id were the same, right? This would mean that, in myOpptyTeamMembers (which is the list I am inserting at the end of the code), there are 2 records Opportunity Team Members with the same Id?
How could this be possible?
Any clue?
(Thank you very much)
Hello,
I am very new to programming and am learning to code with apex.
If you have experience in coding with apex, you will observe that the following code breaches many good practices' rules but, for now, I do not care (this is not about good practices, this question is about the error); I am just trying to understand WHY am I getting this error (Variable does not exit: Id)
I think it might have something to do with the "scope" of the code where this variable is being referenced but, I still need understand and to learn how to avoid these kind of issue in the future.

Could you possibly explain in plain English (for a beginner), why is this error being produced and how to avoid it?

Thank you very much. Here is the code:
trigger OwnerManager on Opportunity (after insert) {
    for(Opportunity opp : Trigger.new){
        //Get opp owner manager info
        Opportunity oppWithManagerInfo = [SELECT Id,
                                          Owner.ManagerId
                                          FROM Opportunity
                                          WHERE Id = :opp.Id];
        //Get opp owner direct dependents
        List<user> directDependents = [SELECT Id
                                       FROM user
                                       WHERE ManagerId = :opp.OwnerId
                                       LIMIT 1];
        //Create Opportunity Team Role
        if (oppWithManagerInfo.Owner.ManagerId != null) {
            OpportunityTeamMember otm = new OpportunityTeamMember();
            otm.UserId                = oppWithManagerInfo.Owner.ManagerId;
            otm.OpportunityId         = opp.Id;
            otm.TeamMemberRole        = 'Sales Manager';
            insert otm;
            //Create another Opportunity Team Role with directDependent
            if (directDependents.size()>0){
                OpportunityTeamMember otm2 = new OpportunityTeamMember();
                otm2.UserId                = directDependents.Id; // HERE is the error
                otm.OpportunityId          = opp.Id;
                otm.TeamMemberRole         = 'Sales Rep.';
                insert otm2;
            }
        }
    }
}

 
Hello,

The apex code below is resolving the following requirement (specified as an exercises for practice):

When an opportunity is inserted, automatically add the Oppty's Owner's Manager as a Team Member (of the Opportunity being inserted), with the role "Sales Manager".

The solution provided by the exercise's author is below:
trigger OwnerManager on Opportunity (after insert) {
    for(Opportunity opp : Trigger.new){
        //Get opp owner manager info
        Opportunity oppWithManagerInfo = [SELECT Id,
                                                 Owner.ManagerId
                                            FROM Opportunity
                                           WHERE Id = :opp.Id];
        //Create Opportunity Team Role
        if (oppWithManagerInfo.Owner.ManagerId != null) {
            OpportunityTeamMember otm = new OpportunityTeamMember();
            otm.UserId                = oppWithManagerInfo.Owner.ManagerId;
            otm.OpportunityId         = opp.Id;
            otm.TeamMemberRole        = 'Sales Manager';
            insert otm;
        }
    }
}
My question is regarding Line 7 --> WHERE Id = :opp.Id

The question is: since the trigger is an "after" trigger, from what I have learnt regarding "after" trigger, you would need to first INSERT the value contained in the variable opp (insert opp;) in order for Salesforce to generate an Id for that record. So, I would have thought that Line 7 would only work after opp has been inserted in the data base.

But, the above code seems to work fine, that is why I am perplexed and would like to understand how can the system know the opp.Id before the opp record has even been inserted by the apex code.

Thank you very much.
Hi,

How do you "read" (in plane English) this piece of code?
List<OpportunityShare> oppShareList = [select Id, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId IN :opportunityIdList and RowCause = 'Team'];
My interpretation is...

Create a variable of the type List<OpportunityShare> which is called oppShareList and assign the following records to such list: all records (display the fields Id, OpportunityAccessLevel, etc...) FROM the table OpportunityShare WHERE ...????

I do not understand the code after the WHERE

Could someone explain?

Thank you very much.


 
Hello,
I am getting the above error message when creating a new Opportunity.

I seems obvious by the nature of the error that there is a missing value on a required field somewhere, but I am not sure how this error message has to be interpreted exactly. Does  it mean that a value on a field "User" on the Opportunity object is missing?
The only "user"-like field I can think of in the Opportunity is the Owner (?) but I would have thought that the Owner is automatically set to the running user right after creating the myOpp.

Here is my apex  trigger:

trigger AddTeamMember on Opportunity (before insert) {
    // Create Account to relate it to the Oppty
    Account acc = new Account();
    acc.Name = 'Test'+' '+ System.today();
    //Every time we insert a new Oppty
    for(Opportunity myOpp : Trigger.new){
        // Assign values to required fields of Oppty
        myOpp.Name = 'Test'+' '+ System.today();
        myOpp.AccountId = acc.Id; 
        myOpp.CloseDate = System.today().addDays(10);
        myOpp.StageName = 'Negotiation/Review';
        // Add one Team Member to myOpp
        OpportunityTeamMember myTeamMember = new OpportunityTeamMember();
        myTeamMember.OpportunityId = myOpp.id;
        myTeamMember.OpportunityAccessLevel = 'Read';
        myTeamMember.TeamMemberRole = 'Sales Manager”';
        myTeamMember.UserId = '0050Y000002MN2F'; //myOpp.Owner.ManagerId
        insert myTeamMember;
    }
}


Here is a screenshot of  the error on the Opportunit object:
error due to trigger on Oppty:
User-added image

Can you spot the error on my trigger?