• brozinickr
  • NEWBIE
  • 25 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 42
    Questions
  • 74
    Replies
I have a custom button on an parent object called SMART__c.  The child to this object is Monthly Objective.  Basically when I save the record on the child, Monthly Objective, I want to be able to redirect the user to the parent record (SMART) of the child.

So basically, when I create a Monthly Objective and click save, I want to be directed to the related SMART record.

Is this possible with just URL hacking or do I need to do custom visualforce?

Thanks,

Rachel

Hello,

 

I'm having issues with a trigger that I wrote to prevent users from saving cases with adding the Account Name and Contract ID.  Users can't submit record with a blank Account Name and Contract ID but they are able to submit records with blank Account Name and have a Contract ID.

 

Here's my code:

 

trigger PopulateSPIDContractIdonCase on Case (before insert, before update) {

    Profile p = [SELECT Id from Profile where Name='System Administrator'];
        
        if(System.Trigger.IsUpdate||System.Trigger.IsInsert)
        {
            for (Case c : trigger.new)
            
                if (UserInfo.getProfileId() != p.Id && (c.Reason__c == 'Recon Related') && (c.Account == NULL) && (c.Contract_ID__c == NULL))
                {
                c.addError('  Please enter a Contract ID and Account Name.');
                }
        }
       
}

 

Hello, I have this trigger that stops people from deleting an opportunity of a certain type.  Originally only system admins were allowed to delete these opportunities, but now we need another profile to be able to do this as well.

 

I am getting a list has 1 or more rows for assignments error on the line that is underlined in red.  I am not sure how to make this  trigger accommodate for both profiles though.

 

trigger CannotDeleteAcctMgmtRenewal on Opportunity (before insert, before delete) {

    Profile p = [SELECT Id from Profile where Name IN ('System Administrator', 'Sales Op Admin')];
        if(System.Trigger.IsDelete)
        {       
            for (Opportunity opps : trigger.old)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'||Opps.Type == 'New Ad Sales'))
                {
                 opps.addError('You do not have the permissions delete opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
         
        }
        
        if(System.Trigger.IsInsert)
        {
            for (Opportunity Opps : trigger.new)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'))
                {
                Opps.addError('Error:  You do not have the permissions create Acct. Mgmt. Renewal opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
        }
       
}

 

I was wondering if someone would be able to help me with this.

 

I am trying to build a trigger that will populate the appropriate AL_Goal__c id in a lookup field on Opportunity to connect the two objects.  I am trying to connect the two based of the OwnerID and Date (Year_Month__c needs to equal the same month and year of the CloseDate, and assign the appropriate Goal to the opportunity based on the date).

 

So for example, I create an opportunity with a close date of 91/2013.  When I save, it should populate the lookup field on the opportunity with the id of AL_Goal__c with Year_Month of 2013-9 and OwnerID is my user Id.

 

This is what I have so far, but I am confused on how to connect the Opportunities and AL_Goal__c together.  I figured I would have to create two lists like this and do some sort of a map, but I am not entirely sure on how to go about doing this:

 

List <Opportunity> oppids = [SELECT Id, OwnerID, CloseDate, AL_Goal__c from Opportunity];
List <AL_Goal__c> goals = [SELECT Id, Year_Month__c, OwnerID from AL_Goal__c];

 

 

 

 

trigger UpdateOpportunityGoalLookUp on Opportunity (before insert, before update) 
{
    //instantiate set to hold unique AL_Goal record ids
    Set<Id> GoalIds = new Set<Id>();
    
    for(Opportunity o : Trigger.new)
    {
        GoalIds.add(o.AL_Goal__c);
    }

    //instantiate map to hold AL_Goal record ids to their corresponding ownerids
    Map<Id, AL_Goal__c> AL_GoalMap = new Map<Id, AL_Goal__c>([SELECT Id FROM AL_Goal__c WHERE Id IN: GoalIds]);

    for (Opportunity o : Trigger.new) 
    {
        if (o.AL_Goal__c == null && AL_GoalMap.containsKey(o.AL_Goal__c)) 
        {
            o.AL_Goal__c = AL_GoalMap.get(o.Id).Id;
        }
    }
}

 

Hi,

 

I was wondering if someone might be able to take a look at a batch apex class that I wrote:

 

The gist of what's supposed to happen is this.  Whenever the Expiration Date passes for a Contact, this batch apex process needs to go in and change the BGC_Status__c field to Expired.

 

I ran this execute anon window in the Developer Console to test, but it's not changing any of the statuses.  The logic is pretty simple and I thought my code was correct, but is there something that I could be missing?

 

 

 

global class expireBackgroundChecks implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        Date d = Date.today();
        String soql = 'SELECT id, BGC_Expiration_Date__c, BGC_Status__c FROM Contact WHERE BGC_Expiration_Date__c <: d';
        return Database.getQueryLocator(soql);
    }
   
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
         for(Contact c : scope)
         {
             c.BGC_Status__c = 'Expired';
             update c;
         }
    }   
    global void finish(Database.BatchableContext BC)
    {
    AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            from AsyncApexJob where Id =
            :BC.getJobId()];
 
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
        mail.setToAddresses(new String[] {a.CreatedBy.Email});
        mail.setReplyTo('rachelbr@angieslist.com');
        mail.setSenderDisplayName('Senor Cardgage');
        mail.setSubject('Background Check Expiration has been' + a.Status);
        mail.setPlainTextBody('Hi there, Belindas.  The batch apex job processed ' + a.TotalJobItems +
        ' batches with ' + a.NumberofErrors + ' failures.  ');
 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    
    }
}

 

Hello,

 

I have the following trigger:

 

I have a field on the dsfs__DocuSign_Status__c object called dsfs__Sender__c that is a text field.  I need it to be a lookup field from the User object though so I can use it for reporting.  I created another field called DocuSign_Sender__c that is a lookup to the User.  What I am trying to do with this trigger is query the User table and populate the lookup with User's id matching on the String in the dsfs__Sender__c field.  

 

I am getting this error and I'm not sure since I think my logic is pretty much correct:

 

Apex trigger populateContactfromUser caused an unexpected exception, contact your administrator: populateContactfromUser: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.populateContactfromUser: line 20, column 1

 

 

trigger populateDocuSignSenderfromUser on dsfs__DocuSign_Status__c (before insert , before update){
    
    Set<String> setConIds = new Set<String>();
    
    for(dsfs__DocuSign_Status__c obj : trigger.new){
    
        if(obj.dsfs__Sender__c != null)
        
        setConIds.add(obj.dsfs__Sender__c);
    }
    
     Map <String, User> mapCon = new Map <String, User>([Select Id from User where Name in: setConIds]);
     
     for(dsfs__DocuSign_Status__c obj : trigger.new){
     
        if(obj.dsfs__Sender__c != null){
        
            User c = mapCon.get(obj.dsfs__Sender__c);
            
            obj.DocuSign_Sender__c= c.Id;

          }
       
       }
}

 

Hello, I was wondering if someone would be able to assist me with something.

 

We are going to start leveraging leads in our organization.  All of the standard salesforce lead conversion functionality is working great, but the only problem is that we only want to create opportunities, not contacts and accounts when the lead is converted.  I have found some code online and started messing around with it, but it's still creating the account and the contact upon lead conversion.  Is there a way that I can suppress the creation of the contact and the account and just convert the opportunity?  (apex class is first part of code, visualforce is in the bottom)

 

public class leadController
{
    Public lead lObj;
    Public Id leadId;
    public leadController(ApexPages.StandardController stdController)
    {
        leadId = ApexPages.currentPage().getParameters().get('id');
        lObj = (leadid == null) ? new Lead():[SELECT Name from lead where id =: leadid];
    }
    public PageReference autoRun()
    {
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadId);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        Id oppId = lcr.getOpportunityId();
        PageReference Page = new PageReference('https://ap1.salesforce.com/'+oppId);
        Page.setRedirect(true);
        return Page;
    }
    Public PageReference RedirecttoLead(){
        PageReference Page = new PageReference('https://ap1.salesforce.com/'+leadId);
        Page.setRedirect(true);
        return Page;
    }
}

 

 

 

<apex:page standardController="lead" cache="true" action="{!autorun}" extensions="leadController" >
<br/><br/>
<apex:messages style="color:red; font-weight:bold; text-align:center;"/>
<apex:form >
<center>
<apex:commandLink value="Redirect to Lead" style="color:blue; font-weight:bold;" action="{!RedirecttoLead}"/>
</center>
</apex:form>
</apex:page>

Hello!

 

I have some code listed below that I was hoping someone would be able to help me troubleshoot.  The code is supposed to assign the owner of a Lead based on what Account Team of the User.  So when the lead is created, if select "Storefront" for Lead_Direction__c picklist, then it should assign to the Account Team Member on the Account labeled as 'Storefront Associate'.  If the I select Big Deal in the picklist, then it should assign to the Account Team Member for the associated Account labeled as the 'Big Deal Associate'.  It works when I select Storefront in the Lead Direction and assigned the appropriate rep, but it doesn't assign correctly to the Big Deal Rep.

 

trigger OpportunityTrigger on Lead (before insert){

    List<String> accountIds = new List<String>();
    
    List<AccountTeamMember> parentAccounts = new List<AccountTeamMember>();
    
    for(Lead lead : Trigger.new){
    
        accountIds.add(lead.Account__c);    
    }
    
    parentAccounts = [Select AccountId, UserId, TeamMemberRole from AccountTeamMember where AccountId in :accountIds];
    
    Map<String,AccountTeamMember> accountMap = new Map<String,AccountTeamMember>();
    
    for(AccountTeamMember a : parentAccounts){
    
        accountMap.put(a.AccountId,a);
    }
    
    for(Lead lead : Trigger.new){
    
        AccountTeamMember parentAccount = accountMap.get(lead.Account__c);
        String memberRole = accountMap.get(lead.Account__c).TeamMemberRole;
        
        if((parentAccount != null)&&(memberRole == 'Storefront Associate')&&(lead.Lead_Direction__c == 'Storefront')){
        
            lead.OwnerId = parentAccount.UserId;
            
        }
        
        else if((parentAccount != null)&&(memberRole == 'Big Deal Associate')&&(lead.Lead_Direction__c == 'Big Deal')){
        
            lead.OwnerId = parentAccount.UserId;
          
        }
        
        else{
        
        lead.OwnerId = lead.OwnerId;
        
        }
        
    }
}

 

Hello,

 

I was wondering if someone would be able to help me fix my code.  The premise of what I am trying to do is whenever a lead is created, if Storefront is selected in the Lead_Direction__c picklist, assign it to the listed Storefront Associate in the Account Team for the particular Account.  If Big Deal is selected in the Lead_Direction__c picklist, assign it to the Big Deal Associate listed for the particular Account's Account Team.

 

I am pretty sure this probably isn't the prettiest and concise way to go about doing this either, so if there's an entirely easier way to get the end result, I am completely open to changing my code.

 

This the error I am getting and highlighted the line below:

 

Initial term of field expression must be a concrete SObject: LIST<AccountTeamMember> at line 13 column 61

 

trigger LeadAssignmentTrigger on Lead (before insert){

    for (Lead lead : Trigger.new){
         
      if (lead.Account__c != NULL){
      
          // Find the Account Team Member for the Particular Lead
          List<AccountTeamMember> account = [SELECT AccountId,UserId,TeamMemberRole FROM AccountTeamMember where Accountid = :lead.Account__c limit 2];
                
          // if you found one
          if (account.size() > 0) {

              if((lead.Lead_Direction__c == 'Storefront')&&(account.TeamMemberRole == 'Storefront Associate')){
              
              //assign the lead owner to the Storefront Owner
              
              lead.OwnerId = account[0].UserId; 
              
              }
              
              else if ((lead.Lead_Direction__c == 'Big Deal')&&(account.TeamMemberRole == 'Big Deal Associate')){
              
              //assign the lead owner to the Big Deal Owner
              
              lead.OwnerId = account[0].UserId;
              
              }
          
          }
       } 
          
     }
          
}

 

Hello,

 

I was given the requirement to make a related list for one of our Custom Objects to be filterable.  From what I have gathered, it seems that you have to create a VF page to be able to do this.

 

Is it possible though for you to filter dynamically?  For example, the object in question, Targeted_Offer__c has two record types, Big Deal and Storefront.  If a User who has a Department of Big Deal is to click into an Account, would it be possible just to show Big Deal (so match the Department with name of the Record Type) Targeted Offers?  Or could I just do this more simply, and just only display records with the record type assigned to that User's profile?

I'm having issue testing this trigger that I wrote, I thought this would be something pretty simple but it's not working as I thought it would when I manually test it.

 

Basically, when someone edits their Goal record, I want the Owner's Role Name to populate in a field called Role__c.  When I test it, nothing is writing to the record.  I'm pretty sure it's because I haven't queried the User object, but  I am trying to make this efficient and not query from the User.  I know the User object works a little differently and I know some of the fields are more readily available, so I figured I might be able to pull this value in without querying from it.  Is that incorrect logic?

 

 

trigger Goal_ChangeRecordOwner on Al_Goal__c (before insert, before update) {

    for(Al_Goal__c goal: Trigger.new)
    {
         goal.OwnerId=goal.Goal_Owner__c;
         goal.Role__c=string.valueOf(goal.Owner.UserRole.Name);   
    }
}

 

Hi,

 

I am trying to modify one of my test methods to make sure that it complies with some validation rules I recently created.  I also added a lookup filter on the Decision_Maker__c field (lookup on the Contact) so users can only look up Contact that are related to Account that Opportunity is related to.  So if Account A had two contacts, if I create an Opportunity and want to add the Decision Maker field, I only want to be able to find the two contact that Account A has in the lookup filter.  Here's my logic for the filter:

 

Decision Maker: Account ID equals Field Opportunity: Account ID (required filter)

 

This is the error that I am getting:

 

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Decision_Maker__c]

 

I'm confused because I am pretty sure the Contact that I create in the Unit Test is related the Account I create.  Then the Opportunity I create is related to the Account, so I'm confused on why it's tripping up the error since I related everything together on the original Account.

 

 

 

public static testMethod void TestCreateActualsAndTargets_Trigger(){
    
        Account l_oAccount = new Account(Name='TestAccount', Type='Eligible');
        insert l_oAccount;
        
        User testUser = TestFactory.buildTestASUser(0, 'Standard User');
        insert testUser;
        
        Contact testContact = new Contact ();
        testContact.FirstName='Testo';
        testContact.LastName='Westo';
        testContact.Account=l_oAccount;
        insert testContact;
        
        Opportunity l_oOpportunity = new Opportunity();
        l_oOpportunity.Name='Test Opportunity';
        l_oOpportunity.Type = 'New Ad Sales';
        l_oOpportunity.CloseDate=System.today();
        l_oOpportunity.StageName='Closed/Won';
        l_oOpportunity.AccountId=l_oAccount.Id;
        l_oOpportunity.ForecastCategoryName='Pipeline';
        l_oOpportunity.Contract_ID__c = '123173';
        l_oOpportunity.Multiple_Contract_IDs_at_Close__c = 'No - I have one single Contract';
        l_oOpportunity.Split__c = '50/50';
        l_oOpportunity.User__c = testUser.Id;
        l_oOpportunity.Report_Generation_Tools_Reviewed_withSP__c = 'Yes';
        l_oOpportunity.Personality_of_ServiceProvider__c = 'Yes';
        l_oOpportunity.SPs_Expectations__c = 'Yes';
        l_oOpportunity.Why_We_Gave_SpecialPricing__c = 'Yes';
        l_oOpportunity.UpsellOpportunities__c = 'Yes';
        l_oOpportunity.Advertising_Contact__c = testContact.Id;
        l_oOpportunity.SP_knows_grade_and_current_revie__c = 'Yes';
        l_oOpportunity.Decision_Maker__c = testContact.Id;
        l_oOpportunity.SP_verbally_agreed_to_specific_coupon__c = 'Yes';
        l_oOpportunity.Length_of_SalesCycle__c = 'Within a Week';
        insert l_oOpportunity;   
    }

 

Hello,

 

I was wondering if someone would be able to help with me fix this error that I am getting when I am testing my batch apex class.  The purpose of the class is to find opportunities that have a Last_AS_Verbal_Contact__c greater than 7 Days.  Last_AS_Verbal_Contact__c is a date field formula that is based off a field of the same name on the Account.  The premise is for it to find these opportunities and then switch them to closed lost.

 

Here is the full error that I am receiving:

 

System.QueryException: value of filter criterion for field 'Last_AS_Verbal_Contact__c' must be of type date and should not be enclosed in quotes

 

global class OpprtunityBatchUpdate implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext BC){

    Datetime dateTm = Datetime.now().addDays(-7);

String query = 'Select o.id, o.StageName, o.Last_AS_Verbal_Contact__c from Opportunity o where '
+ 'o.Last_AS_Verbal_Contact__c <= ' +dateTm.format('yyyy-MM-dd\'T\'hh:mm:ss\'z\'') + 'and '
+ 'o.StageName in (\'Discovery\',\'Contract\',\'Quote\') ';

return Database.getQuerylocator(query);
}

global void execute(Database.BatchableContext BC, List<sObject> scope){

    List<Opportunity> opps = new List<Opportunity>();
    system.debug('opportunity size '+scope.size());

        for(sObject s : scope){
        
            Opportunity o = (Opportunity)s;
            system.debug('opportunity name '+o.id);
            o.StageName = 'Closed Lost';
            opps.add(o);
        }
        update opps;
}

global void finish(Database.BatchableContext BC){

// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.

AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =
:BC.getJobId()];

// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation ' + a.Status);
mail.setPlainTextBody
('The batch Apex job processed ' + a.TotalJobItems +
' batches with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

}
}

 

Here's my schedulable class with the test method I am using to test:

 

global class ScheduleOpportunityBatch implements Schedulable {

    global void execute(SchedulableContext sc){
    database.executeBatch(new OpprtunityBatchUpdate());
    }
    
    public static testMethod void testScheduleOpprtunityBatch(){
        Test.startTest();
        ScheduleOpportunityBatch objScheduleOpportunityBatch = new ScheduleOpportunityBatch();
        DateTime dtt=DateTime.now().addMinutes(1);    
        String dt=String.valueOf(dtt.second())+' '+String.valueof(dtt.minute())+' '+String.valueof(dtt.hour())+' '+String.Valueof(dtt.day())+' '+String.Valueof(dtt.month()) +' ? '+String.valueof(dtt.year());
        String JobId = System.Schedule('ScheduleOpportunityBatch',dt,objScheduleOpportunityBatch);                        
        Test.stopTest();
    }
    
}

 

 

 

 

I'm having issues writing a trigger that will insert a Contact record from information based on the Account.

 

Basically, if it's an account is inserted, I want it to create a Contact.  That part is easy.  The next part that I am having trouble writing is if the account is updated part.   If it's an update, I want it to look to see if there are any Contacts with the Contact_Type__c = General.  If not, then it needs to create a Contact like in the insert portion.  Thought it was simple enough but I can't get it work correctly.  I also need to make sure that this bulk safe since we load accounts nightly.

 

 

I marked the line it's failing on in red.

 

 

 

trigger CreateAccountContact on Account (after insert, after update){

    if(Trigger.isInsert){
    
        List<Contact> ct = new List <Contact>();
        
        for(Account acc : trigger.new){

        Contact c = new Contact(LastName = acc.name,
                        AccountId=acc.id,
                        Fax=acc.Fax,
                        MailingStreet=acc.BillingStreet,
                        MailingCity=acc.BillingCity,
                        MailingState=acc.BillingState,
                        MailingPostalCode=acc.BillingPostalCode,
                        MailingCountry=acc.BillingCountry,
                        Phone=acc.Phone);

        ct.add(c);
        
        }
        
        if(!ct.isEmpty())
            insert ct; 
    }
    
    else{
        
        List<contact> cntsload = new List <Contact>();
        
        for(Account acc : trigger.new){
                List<Contact> cnt = new List<Contact>([select id, Contact_Type__c from Contact where AccountId = acc.id and Contact_Type__c = 'General']);
        
        if(cnt.isEmpty()){

        Contact c = new Contact(LastName = acc.name,
                        AccountId=acc.id,
                        Fax=acc.Fax,
                        MailingStreet=acc.BillingStreet,
                        MailingCity=acc.BillingCity,
                        MailingState=acc.BillingState,
                        MailingPostalCode=acc.BillingPostalCode,
                        MailingCountry=acc.BillingCountry,
                        Phone=acc.Phone);

        cntsload.add(c);
        
        }
        }
        
        if(!cntsload.isEmpty())
            insert cntsload; 
    
    
    }
    
}

 

Helllooo.

 

Wondering if someone could help me with issue I having with this trigger I am attempting to write.

 

The gist of the what I am trying to do is this:  I have a Contract ID field in salesforce on my Opportunity and on a custom object called Recon_Detail__c.  Each Recon_Detail is basically like a line item for one Contract.  My plan for this trigger is to aggregate the sum of all of the Recon_Details of one Contract ID and then write the value on the Total_Amount__c field on the Opportunity.

 

So for example, Recon_Detail 1 has a contract ID of 123123 and amount of $100, Recon Detail 2 has a contract ID of 123123 and amount of 125, Recon Detail 3 has a contract ID of 123124 and amount of $123.

 

When the Opportunity with the Contract ID of 123123 updates, then the Total Amount field should populate with the amount of $225.

 

I'm getting this error in my code: Illegal assignment from LIST<AggregateResult> to LIST<Recon_Detail__c> at line 19 column 1 (line marked in red below)

 

trigger UpdateOppReconDetail on Opportunity (before update) {

//Create a placeholder list of Contract Id's from the opportunity called oppids and
//placeholder map for contract id and total amount from recon detail called rdmap

List<string> oppids = new List<string>();
Map<string,string> rdmap = new Map<string,string>();

    //add the Opportunity contract ids that have blank Total_Amount__c field on Opportunity to the oppids list

    for(Opportunity o : Trigger.new) {
        if(o.Total_Amount__c == null){
            oppids.add(o.Contract_ID__c);
        }
    }

//Get the Contract Id and Amount of all Recon Details that are in the OppId List

List<Recon_Detail__c> rds = [SELECT Contract_ID__c, SUM(Amount__c)sum
                             FROM Recon_Detail__c
                             where Contract_ID__c IN :oppids
                             GROUP BY Contract_ID__c];

    //Create the map that will be used to update; placing Contract ID, then Amount
    
    for(Recon_Detail__c rd : rds) {
        rdmap.put(rd.Contract_ID__c, String.Valueof(rd.get('sum')));
    }

    //If the Recon_Detail__c is blank/null, then get the opportunity id (key) from the map and place it's Amount (value) in that field
    
    for(Opportunity o : Trigger.new) {
           o.Total_Amount__c = rdmap.get(o.Contract_ID__c);
    }

}

 

 

 

Hello,

 

I was wondering if someone would be able to help me bulifying the trigger below.  As of now, this trigger counts all of the calls made in one month on a particular account made by a particular system profile.

 

I just was given the requirements that I need to do the same thing but for another profile, AL - AM Rep and write to a different field, AM_Activity_Count__c.  I know I could just duplicate this trigger, change the name in the soql, and then save it.  But I know there has to be a way that I can bulkify this.  I've been messing around trying to get this to work and I've been unable to get it to work so far.  Here't what I have originally:

 

 

trigger Activity_Count on Task (after insert, after update, after delete) 
{
    List<Id> taskIds = new List<Id>();
    List<Id> accIds = new List<Id>();
    Map<Id,Account> accMap = new Map<Id,Account>();
    List<Account> updateList = new List<Account>();  // edited
    String accPrefix = Account.sObjectType.getDescribe().getKeyPrefix();
    
    for (Task t : Trigger.isDelete ? Trigger.old : Trigger.new)
    {
        taskIds.add(t.Id);
        String str = t.whatId;
        if(str != null && str.startsWith(accPrefix))     // Task belongs to Account
          {
            accIds.add(t.whatId);
          }
    }
    
    if(accIds.size() > 0)
    {
        for(Account ac : [SELECT Id, Activity_Count__c FROM Account WHERE Id in :accIds])
        {
            accMap.put(ac.Id,ac);
        }

        for(AggregateResult ar : [SELECT Count(Id) c, WhatId w, Owner.Profile.Name
                                  FROM Task
                                  WHERE whatId IN :accIds
                                  AND Subject Like 'Call%'
                                  AND CreatedDate = This_Month
                                  AND Owner.Profile.Name = 'AL - AS Rep'
                                  GROUP BY WhatId, Owner.Profile.Name])
        {
            Account acc = new Account();
            
            string str = string.valueOf(ar.get('w'));
            
            acc = accMap.get(str);   // Edited   //
            acc.Activity_Count__c = Integer.valueOf(ar.get('c'));   // Edited
            
            updateList.add(acc);
        }
    }
    
    if(updateList.size() > 0)
    {
        update updateList;
    
    }
}

Hi,

 

I've been tasked to create an opportunity roll up on one of our custom objects AM_Performance__c.  I need to put the number of opportunitites owned by the certain user.

 

I figured what I could do is get a list of owner ids, then get query opportunity to get all of the opportuities owned by that owner id, then write size of that list to the AM_Performance__c object.  Problem is that I am getting this illegal assignment error on the line that's marked in red.  Can someone help?

 

Thanks!

 

 

trigger AMPROppCount on Opportunity (after insert, after update, after delete, after undelete) {

    //Create a Set to hold Acct Ids of opps in trigger and a List to hold accts which will be updated
    
    Set<Id> ownerIdSet = new Set<Id>();
    List<AM_Performance__c> amprUpdateList = new List<AM_Performance__c>();

    //Create ths set of Owner IDs.  If this is a delete trigger, pull them the trigger.old,
    //otherwise use trigger.new
    
    if(Trigger.isDelete)
        for(Opportunity o : trigger.old)
            ownerIdSet.add(o.OwnerId);
    else
        for(Opportunity o : trigger.new)
            ownerIdSet.add(o.OwnerId);

    //Query for all of the opportunities 
    List<AM_Performance__c> amprOpptyList = [select Id, OwnerId, IsWon, IsClosed from Opportunity where ownerId IN :ownerIdSet];

    //loop through all of the AM_Performance__cs in the map and get the counts for total number of opps,
    //count of closed and count of won opps.
    
    for(AM_Performance__c a : amprOpptyList){
        //initialize our counters
        Integer wonOpps = 0;
        Integer closedOpps = 0;

        //loop through the associated opportunities and count up the opportunities
        for(Opportunity o : a.Opportunities){
            if(o.IsClosed){
                closedOpps++;
                
            if(o.IsWon) wonOpps++;
            }
        }

        //set the counts
        a.Opportunities_Owned_This_Month__c = a.Opportunities.size();

        //add the AM_Performance__c to the update list
        amprUpdateList.add(a);
    }

    //update all of the AM_Performance__c's if the list isn't empty
    if(!amprUpdateList.IsEmpty())
update amprUpdateList; }

 

Hello,

 

I'm having issues with one of my apex classes not correctly working so my apex trigger will not fire.

 

I have four objects that use this class, Contract_Item__C (which is basically a custom object that list line items of a Contract and the apex trigger fires off of), Account, AM_Performance__c (a custom goal holder object), and AM_Actual__c (custom actual object for the Goal).  The purpose of this apex class is to either find the correct goal record, create a goal record if one hasn't been created, then create and/or delete the actual with with the associated goal record that month.

 

I had found an error that these actuals were writing to the first goal record that it found in query instead of the goal record based on month it should be listed for.  That made sense, because there were no date listed in the class for it to look for it.  So I went in and made the changes so that it had to look off a field called Approval_Date__c (found on the Contract_Item__c object)'s year month in order to determine which goal record to find and associate it to.

 

I tried testing it manually to make sure that it worked before I went ahead and modified my test coverage, now it doesn't even write the actual to the am_performance__c record anymore.  I can't figure out why it won't fire.  Would someone be able to look over my code and tell me what I am missing?

 

 

class

 

public with sharing class AMAttrionActuals {

 public Account accountNew
 {
    get;set;
 }
 
 public Contract_Item__c contractitemNew
 {
    get;set;
 }
 
AM_Attrition_Actual__c l_oActual;
AM_Performance__c l_oTarget;
  
public ID CreateTarget(Id OwnerID)
 {
    System.debug('****Goal Method Call*****');
    ID GoalID;
    if((accountNew!=null)&&(contractitemNew!=null))
    {       
        
           System.debug('Select id ,Name,Goal_Date__c,Target_Owner__c From AM_Performance__c where Owner=:'+OwnerID);
           l_oTarget=null;
           for(AM_Performance__c l_oLoopTarget : [Select id,Name,Goal_Date__c,Target_Owner__c From AM_Performance__c 
                                                  Where 
                                                  Year_Month__c = :contractitemNew.Approval_Date__c.Year()+'-'+contractitemNew.Approval_Date__c.Month()
                                                  And 
                                                  Target_Owner__c= :OwnerID]
                            )
                            {
                                l_oTarget=l_oLoopTarget;
                                break;
                            }
                        
                                            
            if(l_oTarget==null)
            {
                 //Date l_oNewTargetDate = Date.newInstance(accountNew.CloseDate.Year(), accountNew.CloseDate.Month(), 1);
                 //Date l_oNewTargetDate = Date.today();
                 Date l_oNewTargetDate = Date.newInstance(contractitemNew.Approval_Date__c.Year(), contractitemNew.Approval_Date__c.Month(), 1);
                 l_oTarget= new AM_Performance__c();
                 l_oTarget.Goal_Date__c=l_oNewTargetDate;
                 l_oTarget.Target_Owner__c=OwnerID;
                 l_oTarget.CV_Value__c = 0;
                 l_oTarget.Booked_Value__c = 0;
                 l_oTarget.Renewal_Goal__c = 0;
                 l_oTarget.Attrition_Goal__c = 0;
                 l_oTarget.Eligible_Amount__c = 0;
                 insert l_oTarget;
            }
           GoalID=l_oTarget.Id;
                
    //}   
    return GoalID;  
    }
    
    return null;
 }
 
  
 public void CreateAMAttrtionActualNegative(Id OwnerID,Id contractID, ID GoalID,Decimal booked_Value,Decimal CV_value,String attr_Status)
 {
          
    if(GoalID!= null)
    {
            l_oActual = new AM_Attrition_Actual__c(Booked_Value__c = 0,CV__c=0);
            l_oActual.Account__c=accountNew.Id;
            l_oActual.Booked_Value__c = -booked_Value;
            l_oActual.CV__c =-CV_value;
            l_oActual.AttritionStatus__c = attr_Status;
            l_oActual.AM_Renewal_Target__c = GoalID;
            l_oActual.Contract_Item__c = contractID;
            l_oActual.Attrition_Actual_Owner__c = OwnerID;
            insert l_oActual;
    }
 }
 
 
 public void CreateAMAttrtionActualPositive(Id OwnerID,Id contractID, ID GoalID,Decimal booked_Value,Decimal CV_value,String attr_Status)
 {
          
    if(GoalID!= null)
    {
            l_oActual = new AM_Attrition_Actual__c(Booked_Value__c = 0,CV__c=0);
            l_oActual.Account__c=accountNew.Id;
            l_oActual.Booked_Value__c = booked_Value;
            l_oActual.CV__c =CV_value;
            l_oActual.AttritionStatus__c = attr_Status;
            l_oActual.AM_Renewal_Target__c = GoalID;
            l_oActual.Contract_Item__c = contractID;
            l_oActual.Attrition_Actual_Owner__c = OwnerID;
            insert l_oActual;
    }
 }
 public void DeleteActual(ID contractItemId)
 {
    if(accountNew!=null)
    {
        List<AM_Attrition_Actual__c> l_olstActual = [Select id From AM_Attrition_Actual__c Where Contract_Item__c =:contractItemId];
        delete l_olstActual;            
    }
 }


}

 


trigger

 

trigger CreateAMAttrtionActual on Contract_Item__c (after insert, after update) {
if(Trigger.isUpdate || Trigger.isInsert)   
    {
      Map<ID,Contract_Item__c> contractItemDetails = new Map<ID,Contract_Item__c> ([Select id,Status__c,SPID__c, Approval_Date__c, Attrition_Reason__c,Booked_Value__c,CV__c From Contract_Item__c o where id in:trigger.newMap.keySet()]);
      Set<ID> contractAcntIds = new Set<ID>();
      AMAttrionActuals l_oGooalAndActuals = new AMAttrionActuals();
      //start : to overcome salesforce SOQL limit exception
      for(Contract_Item__c contractItem:contractItemDetails.values())
      {
        contractAcntIds.add(contractItem.SPID__c);
      } 
      
      Map<ID,Account> AccountDetails = new Map<ID,Account> ([Select id,o.Owner.ManagerId,o.OwnerId,o.Type From Account o where Id in:contractAcntIds]);
      //end: to overcome salesforce SOQL limit exception     
      for(Contract_Item__c contractItem:contractItemDetails.values())
      {
        Account acnt = AccountDetails.get(contractItem.SPID__c);
        if((acnt!= null) && (acnt.Type=='Advertiser'))
        {
        System.debug('********************Trigger Start***********************');
            
    if(((contractItem.Status__c=='Pull')|| (contractItem.Status__c=='Cancel')) && (contractitem.Attrition_Reason__c != null) && (contractitem.Booked_Value__c != null))
            {
              ID SalesRepGoalID,ManagerGoalID;
              //modified
              l_oGooalAndActuals = new AMAttrionActuals();
              
               
               System.debug('SPID' + contractItem.SPID__c );
              
              
                  l_oGooalAndActuals.accountNew=acnt;
                  //Goal Creation
                  SalesRepGoalID  =l_oGooalAndActuals.CreateTarget(acnt.OwnerId);//SalesRep Goal Creation
                      
                  if(acnt.Owner.ManagerId!= null)
                  {
                    ManagerGoalID = l_oGooalAndActuals.CreateTarget(acnt.Owner.ManagerId);//Manager Goal Creation
                  }
              
              
                  //Actual Deletion
                  if(Trigger.isUpdate)
                  {
                    l_oGooalAndActuals.DeleteActual(contractItem.Id);
                    
                  }
              
                  //Actual Creation
                  l_oGooalAndActuals.CreateAMAttrtionActualNegative(acnt.OwnerId,contractItem.Id,SalesRepGoalID,contractItem.Booked_Value__c,contractItem.CV__c,contractItem.Status__c );//SalesRep Actual Creation
                  if(acnt.Owner.ManagerId!= null)
                  {
                    l_oGooalAndActuals.CreateAMAttrtionActualNegative(acnt.Owner.ManagerId,contractItem.Id,ManagerGoalID,contractItem.Booked_Value__c,contractItem.CV__c,contractItem.Status__c);//Manager Actual Creation
                  }
                  
                }
                else if(contractItem.Status__c=='Reinstate')
                {
                    ID SalesRepGoalID,ManagerGoalID;
              //modified
              l_oGooalAndActuals = new AMAttrionActuals();
              
               AM_Renewal_Goal__c ManagerGoal;  
               System.debug('SPID' + contractItem.SPID__c );
              
              
                  l_oGooalAndActuals.accountNew=acnt;
                  //Goal Creation
                  SalesRepGoalID  =l_oGooalAndActuals.CreateTarget(acnt.OwnerId);//SalesRep Goal Creation
                      
                  if(acnt.Owner.ManagerId!= null)
                  {
                    ManagerGoalID = l_oGooalAndActuals.CreateTarget(acnt.Owner.ManagerId);//Manager Goal Creation
                  }
              
              
                  //Actual Deletion
                 /* if(Trigger.isUpdate)
                  {
                    l_oGooalAndActuals.DeleteActual(contractItem.Id);
                    
                  }*/
              
                  //Actual Creation
                  l_oGooalAndActuals.CreateAMAttrtionActualPositive(acnt.OwnerId,contractItem.Id,SalesRepGoalID,contractItem.Booked_Value__c,contractItem.CV__c,contractItem.Status__c );//SalesRep Actual Creation
                  if(acnt.Owner.ManagerId!= null)
                  {
                    l_oGooalAndActuals.CreateAMAttrtionActualPositive(acnt.Owner.ManagerId,contractItem.Id,ManagerGoalID,contractItem.Booked_Value__c,contractItem.CV__c,contractItem.Status__c);//Manager Actual Creation
                  }
                }
        
       
        
        /*
        Start: Big Deal Project 
        *   Purpose: It will remove Actual record(s) associated to Opportunity if Stage goes from 'Closed/Won' to some other stage.
        */        
     /*  else if(Trigger.isUpdate)
        {
            if(((Trigger.oldMap.get(contractItem.Id).Status__c=='Pulled') ||(Trigger.oldMap.get(contractItem.Id).Status__c=='Cancelled')||(Trigger.oldMap.get(contractItem.Id).Status__c=='Reinstated')) && 
            ((contractItem.Status__c != 'Pulled')||(contractItem.Status__c != 'Cancelled')||(contractItem.Status__c != 'Reinstated')))
            {
                l_oGooalAndActuals = new AMAttrionActuals ();
                l_oGooalAndActuals.accountNew=acnt;
                l_oGooalAndActuals.DeleteActual(contractItem.Id);
            }
        }*/
        /*End: Big Deal Project */ 
        
        }//if acnt!=null    
        
      }
    }
}

 

 

 

 

 

Hello.  In our org we have a trigger on the Account so that if the Account changes ownership, that open opportunities do not switch to the new account owner.  When manually testing , it seems to work for those opportunitites that are Closed/Won, but it still switches the owners if they are Protected. (Protected is a checkbox on the opportunity.  I want it so if the opportunity is protected, the opportunity owner will NOT change).

 

Here's my code:

 

public class AlOpportunity {
    
    public static Opportunity GetOpportunity(string Id){
        Opportunity opp = null;
        for (Opportunity oppr: [SELECT Id, Name, AccountId from Opportunity WHERE Opportunity.Id=: Id]){
            System.debug('Testing_Code');
            opp = oppr;
            break;
        }
        return opp;
    }
    
    //unit test TestGetOpportunity
    public static testMethod void TestGetOpportunity(){
        
        Opportunity o = new Opportunity();
        o.Name = 'test opp';
        o.StageName = 'test stage';
        o.CloseDate = Date.today();
        insert o;
        
        Opportunity o1 = GetOpportunity(o.id);
        
        System.assertEquals(o1.id == o.id, true);
    }
    
    public static List<Opportunity> ChangeOpportynityOwners(Map<Id,Account> accounts){
        List<Opportunity> opps = [Select o.Id, o.OwnerId, o.AccountId From Opportunity o WHERE accountid in: accounts.KeySet() AND Protected__c = false AND StageName <> 'Closed/Won' AND StageName <> 'Closed Lost'];
        if (opps == null)
            opps = new List<Opportunity>();
        for (Opportunity opp: opps){
            opp.OwnerId = accounts.get(opp.AccountId).OwnerId;
        }
        return opps;
    }
    
    //unit test TestChangeOpportynityOwners
    public static testMethod void TestChangeOpportynityOwners(){
        
        Account acc = new Account();
        acc.Name = 'Unit test account';
        insert acc;
        
        Opportunity o = new Opportunity();
        o.Name = 'test opp';
        o.StageName = 'Quote';
        o.AccountId = acc.id;
        o.CloseDate = date.today();
        insert o;
                
        Map<Id,Account> accs = new Map<Id,Account>();
        accs.Put(acc.id,acc);
        AlOpportunity.ChangeOpportynityOwners(accs);
    }

}

 

and the trigger:

 

trigger Account_UpdateOpportunityAndTaskOwners on Account (after update) {
  
  Map<id,Account> accountsToProcess = new Map<id,Account>();
  
  //filter accounts with changed owner
  for (Account acc : trigger.new){
    if (acc.OwnerId != trigger.oldMap.get(acc.id).OwnerId){
      accountsToProcess.put(acc.id,acc);
    }
  }
  
  try{
  if (accountsToProcess.size() > 0) {
    System.Debug('Processing the accounts tasks and opprs');
    List<Task> tasksToUpdate = AlAccount.ChangeTaskOwners(accountsToProcess);
    List<Opportunity> oppsToUpdate = AlOpportunity.ChangeOpportynityOwners(accountsToProcess);
    
    if (tasksToUpdate.size() > 0)
    {
      System.debug('updating the tasks');
      update tasksToUpdate;
    }
    if (oppsToUpdate.size() > 0)
      update oppsToUpdate;
  }
  }
  catch( Exception ex)
  {
    //String subject;
    System.Debug('Exception occured in deleting tasks...' + ex.getMessage()+ '\r\n' + 
    'Stack Trace ...' + ex.getStackTraceString() + '\r\n');
    /*subject += 'Exception occured in deleting tasks...' + ex.getMessage() + '\r\n';
      subject += 'Stack Trace ...' + ex.getStackTraceString() + '\r\n';  
      if (AL_Settings__c.getInstance('MaxProtectedAccounts').Territory_Process_Error_Email__c != null){
        List<string> toAddresses = new List<string>();
        toAddresses.add(AL_Settings__c.getInstance('MaxProtectedAccounts').Territory_Process_Error_Email__c);  
        if (toAddresses.size() > 0)
        {
              Messaging.SingleEmailMessage statusMail = new Messaging.SingleEmailMessage();
              List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
              statusMail.setToAddresses(toAddresses);
              statusMail.setReplyTo('padma.ramkumar@revelanttech.com');
              statusMail.setSubject(subject + ' ' + String.valueOf(Datetime.now()) );
              statusMail.setPlainTextBody('Account_DefineRelatedTerritory:Account Bulk Load');
              mails.add(statusMail);
              Messaging.sendEmail(mails);
        }
      }  */        
  }
  
}

 

 

 

 

 

 

 

 

 

Hello,

 

I have a trigger that I have written that writes the Activity Count for an Account.  I have been now given the requirement that it should only count tasks for users that have the department of Account Management.  I'm not sure how to add this functionality to this trigger. I'm figuring that I am going to have get the set of user ids with a department like account management.  Then somehow map it to the task (task id as the key, user as the value?)  Then is it possible to map one map to another one?  so I could map accmap to task map?  Is there another easier way to do this?

 

 

trigger Activity_Count on Task (after insert, after update, after delete) 
{
    List<Id> taskIds = new List<Id>();
    List<Id> accIds = new List<Id>();
    Map<Id,Account> accMap = new Map<Id,Account>();
    List<Account> updateList = new List<Account>();  // edited
    String accPrefix = Account.sObjectType.getDescribe().getKeyPrefix();
    
    for (Task t : Trigger.isDelete ? Trigger.old : Trigger.new)
    {
        taskIds.add(t.Id);
        String str = t.whatId;
        if(str != null && str.startsWith(accPrefix))     // Task belongs to Account
          {
            accIds.add(t.whatId);
          }
    }
    
    if(accIds.size() > 0)
    {
        for(Account ac : [SELECT Id, Activity_Count__c FROM Account WHERE Id in :accIds])
        {
            accMap.put(ac.Id,ac);
        }

        for(AggregateResult ar : [SELECT Count(Id) c, WhatId w FROM Task WHERE whatId IN :accIds and Subject Like 'Call%' and CreatedDate = This_Month and IsBigDealRep__c = false GROUP BY WhatId])
        {
            Account acc = new Account();
            
            string str = string.valueOf(ar.get('w'));
            
            acc = accMap.get(str);   // Edited   //
            acc.Activity_Count__c = Integer.valueOf(ar.get('c'));   // Edited
            
            updateList.add(acc);
        }
    }
    
    if(updateList.size() > 0)
    {
        update updateList;
    
    }
}

 

Hello,

 

I was given the requirement to make a related list for one of our Custom Objects to be filterable.  From what I have gathered, it seems that you have to create a VF page to be able to do this.

 

Is it possible though for you to filter dynamically?  For example, the object in question, Targeted_Offer__c has two record types, Big Deal and Storefront.  If a User who has a Department of Big Deal is to click into an Account, would it be possible just to show Big Deal (so match the Department with name of the Record Type) Targeted Offers?  Or could I just do this more simply, and just only display records with the record type assigned to that User's profile?

Hello,

 

I'm having issues with a trigger that I wrote to prevent users from saving cases with adding the Account Name and Contract ID.  Users can't submit record with a blank Account Name and Contract ID but they are able to submit records with blank Account Name and have a Contract ID.

 

Here's my code:

 

trigger PopulateSPIDContractIdonCase on Case (before insert, before update) {

    Profile p = [SELECT Id from Profile where Name='System Administrator'];
        
        if(System.Trigger.IsUpdate||System.Trigger.IsInsert)
        {
            for (Case c : trigger.new)
            
                if (UserInfo.getProfileId() != p.Id && (c.Reason__c == 'Recon Related') && (c.Account == NULL) && (c.Contract_ID__c == NULL))
                {
                c.addError('  Please enter a Contract ID and Account Name.');
                }
        }
       
}

 

Hello, I have this trigger that stops people from deleting an opportunity of a certain type.  Originally only system admins were allowed to delete these opportunities, but now we need another profile to be able to do this as well.

 

I am getting a list has 1 or more rows for assignments error on the line that is underlined in red.  I am not sure how to make this  trigger accommodate for both profiles though.

 

trigger CannotDeleteAcctMgmtRenewal on Opportunity (before insert, before delete) {

    Profile p = [SELECT Id from Profile where Name IN ('System Administrator', 'Sales Op Admin')];
        if(System.Trigger.IsDelete)
        {       
            for (Opportunity opps : trigger.old)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'||Opps.Type == 'New Ad Sales'))
                {
                 opps.addError('You do not have the permissions delete opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
         
        }
        
        if(System.Trigger.IsInsert)
        {
            for (Opportunity Opps : trigger.new)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'))
                {
                Opps.addError('Error:  You do not have the permissions create Acct. Mgmt. Renewal opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
        }
       
}

 

Hello, I was wondering if someone would be able to assist me with something.

 

We are going to start leveraging leads in our organization.  All of the standard salesforce lead conversion functionality is working great, but the only problem is that we only want to create opportunities, not contacts and accounts when the lead is converted.  I have found some code online and started messing around with it, but it's still creating the account and the contact upon lead conversion.  Is there a way that I can suppress the creation of the contact and the account and just convert the opportunity?  (apex class is first part of code, visualforce is in the bottom)

 

public class leadController
{
    Public lead lObj;
    Public Id leadId;
    public leadController(ApexPages.StandardController stdController)
    {
        leadId = ApexPages.currentPage().getParameters().get('id');
        lObj = (leadid == null) ? new Lead():[SELECT Name from lead where id =: leadid];
    }
    public PageReference autoRun()
    {
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadId);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        Id oppId = lcr.getOpportunityId();
        PageReference Page = new PageReference('https://ap1.salesforce.com/'+oppId);
        Page.setRedirect(true);
        return Page;
    }
    Public PageReference RedirecttoLead(){
        PageReference Page = new PageReference('https://ap1.salesforce.com/'+leadId);
        Page.setRedirect(true);
        return Page;
    }
}

 

 

 

<apex:page standardController="lead" cache="true" action="{!autorun}" extensions="leadController" >
<br/><br/>
<apex:messages style="color:red; font-weight:bold; text-align:center;"/>
<apex:form >
<center>
<apex:commandLink value="Redirect to Lead" style="color:blue; font-weight:bold;" action="{!RedirecttoLead}"/>
</center>
</apex:form>
</apex:page>

Hello!

 

I have some code listed below that I was hoping someone would be able to help me troubleshoot.  The code is supposed to assign the owner of a Lead based on what Account Team of the User.  So when the lead is created, if select "Storefront" for Lead_Direction__c picklist, then it should assign to the Account Team Member on the Account labeled as 'Storefront Associate'.  If the I select Big Deal in the picklist, then it should assign to the Account Team Member for the associated Account labeled as the 'Big Deal Associate'.  It works when I select Storefront in the Lead Direction and assigned the appropriate rep, but it doesn't assign correctly to the Big Deal Rep.

 

trigger OpportunityTrigger on Lead (before insert){

    List<String> accountIds = new List<String>();
    
    List<AccountTeamMember> parentAccounts = new List<AccountTeamMember>();
    
    for(Lead lead : Trigger.new){
    
        accountIds.add(lead.Account__c);    
    }
    
    parentAccounts = [Select AccountId, UserId, TeamMemberRole from AccountTeamMember where AccountId in :accountIds];
    
    Map<String,AccountTeamMember> accountMap = new Map<String,AccountTeamMember>();
    
    for(AccountTeamMember a : parentAccounts){
    
        accountMap.put(a.AccountId,a);
    }
    
    for(Lead lead : Trigger.new){
    
        AccountTeamMember parentAccount = accountMap.get(lead.Account__c);
        String memberRole = accountMap.get(lead.Account__c).TeamMemberRole;
        
        if((parentAccount != null)&&(memberRole == 'Storefront Associate')&&(lead.Lead_Direction__c == 'Storefront')){
        
            lead.OwnerId = parentAccount.UserId;
            
        }
        
        else if((parentAccount != null)&&(memberRole == 'Big Deal Associate')&&(lead.Lead_Direction__c == 'Big Deal')){
        
            lead.OwnerId = parentAccount.UserId;
          
        }
        
        else{
        
        lead.OwnerId = lead.OwnerId;
        
        }
        
    }
}

 

Hello,

 

I was wondering if someone would be able to help me fix my code.  The premise of what I am trying to do is whenever a lead is created, if Storefront is selected in the Lead_Direction__c picklist, assign it to the listed Storefront Associate in the Account Team for the particular Account.  If Big Deal is selected in the Lead_Direction__c picklist, assign it to the Big Deal Associate listed for the particular Account's Account Team.

 

I am pretty sure this probably isn't the prettiest and concise way to go about doing this either, so if there's an entirely easier way to get the end result, I am completely open to changing my code.

 

This the error I am getting and highlighted the line below:

 

Initial term of field expression must be a concrete SObject: LIST<AccountTeamMember> at line 13 column 61

 

trigger LeadAssignmentTrigger on Lead (before insert){

    for (Lead lead : Trigger.new){
         
      if (lead.Account__c != NULL){
      
          // Find the Account Team Member for the Particular Lead
          List<AccountTeamMember> account = [SELECT AccountId,UserId,TeamMemberRole FROM AccountTeamMember where Accountid = :lead.Account__c limit 2];
                
          // if you found one
          if (account.size() > 0) {

              if((lead.Lead_Direction__c == 'Storefront')&&(account.TeamMemberRole == 'Storefront Associate')){
              
              //assign the lead owner to the Storefront Owner
              
              lead.OwnerId = account[0].UserId; 
              
              }
              
              else if ((lead.Lead_Direction__c == 'Big Deal')&&(account.TeamMemberRole == 'Big Deal Associate')){
              
              //assign the lead owner to the Big Deal Owner
              
              lead.OwnerId = account[0].UserId;
              
              }
          
          }
       } 
          
     }
          
}

 

I'm having issue testing this trigger that I wrote, I thought this would be something pretty simple but it's not working as I thought it would when I manually test it.

 

Basically, when someone edits their Goal record, I want the Owner's Role Name to populate in a field called Role__c.  When I test it, nothing is writing to the record.  I'm pretty sure it's because I haven't queried the User object, but  I am trying to make this efficient and not query from the User.  I know the User object works a little differently and I know some of the fields are more readily available, so I figured I might be able to pull this value in without querying from it.  Is that incorrect logic?

 

 

trigger Goal_ChangeRecordOwner on Al_Goal__c (before insert, before update) {

    for(Al_Goal__c goal: Trigger.new)
    {
         goal.OwnerId=goal.Goal_Owner__c;
         goal.Role__c=string.valueOf(goal.Owner.UserRole.Name);   
    }
}