• Abhishek Bansal
  • ALL STAR
  • 5788 Points
  • Member since 2015
  • Software Developer

  • Chatter
    Feed
  • 195
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 930
    Replies
This code (not written by me) references the Id of a record in a before insert trigger. I was always under the impression you couldn't do that, as there is no Id before the record is committed to the database.

But it works... the Campaign__c field is correctly set every time. So naturally my question is how does it work? Because of the Id reference, or in spite of it? Is this some well known feature of Apex that I should be aware of, or a flawed trigger that happens to do the right thing?

trigger RegionTargetSetCampaign on Region_Targets__c (before insert) {

    Map<Id,Id> regionTargetToCallingGuide = new Map<Id,Id>();
    
    for(integer i=0; i<Trigger.size; i++) {
        Region_Targets__c regionTarget = Trigger.new[i];
        regionTargetToCallingGuide.put(regionTarget.id, regionTarget.Campaign_Delivery__c);
    }
    
    Map<Id,Campaign_Delivery__c> callingGuideMap = new Map<Id,Campaign_Delivery__c>([SELECT id, Campaign__c FROM Campaign_Delivery__c WHERE id IN :regionTargetToCallingGuide.values()]);
    
    for(Region_Targets__c regionTarget : Trigger.new) {
        regionTarget.Campaign__c = callingGuideMap.get(regionTargetToCallingGuide.get(regionTarget.id)).Campaign__c;
    }
}
I have a requirement that I have to fetch all the Account Lookup fields.I'm using Schema.DisplayType for fetching Text,Picklistlist fields.But for lookup fields I don't know how to fetch.Can anyone help me?
Hello all,

I have a Before Insert Trigger on Leads object. On my Leads object I have a custom field, NetNewLead with a default value of TRUE.

My trigger checks the Contacts object looking for a match on Leads.Email = Contacts.Email and when a match is found NetNewLead is set to FALSE.

My trigger works correctly when I enter a new Lead, however Web-To-Lead always sets my custom field NetNewLead to FALSE even when the Leads.Email is not found as a Contacts.Email.

Any ideas? I have includded my code if you would like to take a look.

* I know I need to remove hard-coded check for RecrdTypeId.

Thanks for your help in advance.

Robert.


trigger Update_NetNewLead_Trigger on Lead (before insert) {

// Step 1 - Iterate over incoming Leads and store email in a set
    List<String> leadEmails = new List<String>();
    for(Lead lead:Trigger.new){
        leadEmails.add(lead.Email);
    }

// Step 2 - Check whether there are any existing Business Contacts with matching email

    //Id RecordTypeIdContact = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Business_Contact').getRecordTypeId();

    List<Contact> contacts = [
        SELECT 
            Id, Email 
        FROM 
            Contact
        WHERE 
            //Email IN :leadEmails and RecordTypeId=:RecordTypeIdContact 
            Email IN :leadEmails and RecordTypeId='0121A0000007rgsQAA'
            // Only Select "Business Contacts" 
    ];

    Set<String> contactEmails = new Set<String>();
    for(Contact contact:contacts){
        contactEmails.add(contact.Email);
    }

// Step 3 - Iterate over Leads if Business Contact has matching email set NetNewLead = False
    for(Lead lead:Trigger.new){
        if(contactEmails.contains(lead.Email)){
            lead.NetNewLead__c = False;
        }
    }
}

 
Hello, 

We have a Lead Trigger set in our org and its been active since 2013. 
 I came across this Salesforce document stating that the first name and last name character limits have increased. 

https://help.salesforce.com/articleView?id=leads_fields.htm&type=5

First Name character limit is 40
Last Name character limit is 80

So created a lead with 30 characters for the first name and 40 for the last name, to be modest. Well, I received the error message that the max limit is 20 characters, etc. Contacted Salesforce, and concluded that a custom lead trigger, shown below, was the culprit. I deactivated it, tested a new lead with the number of characters I tried before, and it worked. 

Unfortunately, I can't deactivate this trigger in production since it is executing various actions. Is there a way to modify this code to allow the first and last name to increase the character limits when a new lead is created? 

The past few months we've been receiving email erroring out and we found out why, but now need to know if anyone can help me out. 

Thanks!
 
trigger triggerLead on Lead (after insert, before insert, before update, after update) {

    LeadTrigger lt = new LeadTrigger();
    if (Trigger.isInsert)
        lt.LeadInsertion(Trigger.New, Trigger.isBefore, Trigger.isAfter);
    else if (Trigger.isBefore)
        lt.LeadUpdate(Trigger.New, Trigger.old, Trigger.isBefore);
    
    if (Trigger.isAfter) {
        lt.ReassignALOnClosedLeads(Trigger.New, Trigger.old, null);
        lt.AddToCampaign(Trigger.New, Trigger.oldMap);
        lt.ProcessQuotingLeads(Trigger.New, Trigger.old);
    } else 
        lt.PopulateAmbassador(Trigger.New, Trigger.old);   
        
    if (Trigger.isBefore && Trigger.isUpdate){
        lt.CreateLastVisitTask(Trigger.new);
        lt.CopyHistoryLog(Trigger.new, Trigger.oldMap);   
    }
}

 
Dear Friends,

i got an requirement, I have teacher and student lookup relationships objects. Teacher object will have student related list, student related list will show student name and their total fees paid. I need to have custom field in Teacher object which will show total fees of all students uunder him.
i would like to use batch apex to update the total fees in Teached object based on student related list fees.

it would be great help if you could direct me to get the proper sample code.

Teacher Obect 
                  Fee total ( Sum ( all students fees under this teacher))


 Thanks in advance 
 
I have a flow that creates multiple records at once. The last record I am trying to create has record types and with each record types. When i try to create a specific record "Software" by running the flow it give me the following error.

Error Occurred: This error occurred when the flow tried to create records: INVALID_FIELD_FOR_INSERT_UPDATE: Yushin_Product__c: bad field names on insert/update call: Brief_description_of_the_modification__c, Current_running_program__c, New_Errors__c.

I'm guessing this is caused by not having the record type that would associate the new software record and fields on the page.

I've tried a few different things but nothing seems to work. I am working in the new Flow Builder UI, so anything i find online doesnt match my option because the screenshot are from the old version of flow. 

below ar escreenshot of my flow. Any help would be greatly appreciated.

Account record creation
User-added image

Opportunity Creation
User-added image

Software record creation

User-added image
 
  • February 20, 2019
  • Like
  • 0
Good day developers

I have a Apex Class in Sandbox which redirects a user to a record created from a visual workflow with the help of a visualforce page:

public with sharing class FlowRedirectController {

    public Object FlowRedirectController() { 
        String unique_id = ApexPages.currentPage().getParameters().get('id');
        
        if(unique_id == null){
            // Return Home if no ID 
            String url = '/home/home.jsp';
            return new PageReference(url);
         } 
         
         // Get Order ID and set Redirect 
         String orderId = [SELECT Name,
                                    Unique_Flow_Identifier__c, 
                                    Id  
                             FROM Order  
                             WHERE Unique_Flow_Identifier__c = :unique_id 
                             ORDER BY CreatedDate DESC   
                             LIMIT 1].Id;
                             
        // Did we find a Order? 
        if (orderId == null) {
            // Return Home if no ID 
            String url = '/home/home.jsp'; 
            return new PageReference(url); 
            }

        // Redirect to Order 
        String url = '/' + orderId;
        return new PageReference(url); 
        }
}


When deploying to production I am getting code coverage error. This is becasue I need to create an Apex Test Class however being new to Apex i'm unsure what I would need to test in this code... Is anyone able to help with this?

Thanks
Hi - I have finally built a scheduled apex class to create a renewal for my opportunities. The final part Im trying to configure is the email notifications. I can get everything working except the URL - i suspect this is because at the time of sending each email it hasnt committed the new opportunities so there is no ID yet addigned. Anyone know of a clever way to get round this ?

code so far is below. relevant lines highlighted in bold

global class CreateRenewal implements Schedulable { 
    global void execute(SchedulableContext ctx) { 

        List<Opportunity> InList = [Select 
        AccountID,
        Amount,
        CloseDate,
        CreatedByID,
        Description,
        ExpectedRevenue,
        ForecastCategoryName,
        LeadSource,
        NextStep,
        CurrencyIsoCode,
        Name,
        OwnerID,
        RecordTypeID,
        Pricebook2ID,
        CampaignID,
        IsPrivate,
        Probability,
        TotalOpportunityQuantity,
        IqScore,
        StageName,
        Type,
        Compliance__c,
        Coverholder_Commission__c,
        Local_Insurer_Commission__c,
        Local_Taxes__c,
        Reinsurance_broker_commission__c,
        Retail_broker_commission__c,
        Sum_Insured__c,
        Account_Contact__c,
        Additional_Amount_in_Oppty_Currency__c,
        Additional_Countries__c,
        Additional_tax_commission_cost_descripti__c,
        AXA_ASR_Pricing_Model_Version__c,
        Business_Type_Class__c,
        Cedents_retention__c,
        Cedents_Retention_Amount__c,
        Channel__c,
        Coinsurances_Commissions_from_Brokers__c,
        Coinsurances_Commissions_to_Brokers__c,
        Coinsurances_Commissions_to_Coverholder__c,
        Coinsurances_Percentage__c,
        Coinsurances_Premium__c,
        Contract_Type__c,
        Coverholder__c,
        Days_to_Quote_Released__c,
        DB_Competitor__c,
        Direct_Contact__c,
        Direct_Source__c,
        Estimated_S6130_GNP__c,
        Fast_track__c,
        Global_GNP__c,
        Insured_Period_From__c,
        Insured_Period_To__c,
        Intermediary_Commission__c,
        Intermediary_Account__c,
        Intermediary_Contact__c,
        Intermediary_Reinsurance_Broker__c,
        Intermediary_Reinsurance_Contact__c,
        Layer__c,
        LoB__c,
        Local_Insurer__c,
        Local_Insurer_Commission_Percentage__c,
        Local_Insurer_Contact__c,
        Lost_Cancel_Reason__c,
        Lost_Cancelled_Reason_Comment__c,
        Lost_Due_to_Pricing_amount__c,
        Lost_Due_to_Pricing_currency__c,
        Non_Renewable__c,
        Opportunity_Channel__c,
        P_Coverholder_Commission__c,
        P_Intermediary_Commission__c,
        P_Local_Insurer_Commission__c,
        P_Local_Taxes__c,
        Policy__c,
        Post_Underwriting_Compliance__c,
        Pre_Issue_Compliance__c,
        Pre_Underwriting_Compliance__c,
        Previously_won_or_lost__c,
        Pricing_Model_Source__c,
        Primary_Country__c,
        Proportional__c,
        P_Syndicate_Gross_Premium__c,
        P_Syndicate_Premium__c,
        Quote_Released_Date__c,
        Reinsurance_Facultative__c,
        Reinsurer_Taxes__c,
        Reinsurer_Taxes_Amount__c,
        Renewal_Created__c,
        Renewal_Indicator__c,
        Renewal_Information__c,
        Renewed_Opportunity__c,
        Rest_of_World__c,
        reviewScope__c,
        Risk_Category__c,
        AXA_GNP__c,
        S1084_S6130_Percentage__c,
        S6130_Coverholder_Commission__c,
        S6130_Coverholder_Commission_Amount__c,
        Syndicate_GGP__c,
        S6130_Line_Size__c,
        S6130_Local_Insurer_Commission__c,
        S6130_Local_Insurer_Commission_Amount__c,
        S6130_Local_Taxes__c,
        S6130_Local_Taxes_Amount__c,
        Syndicate_Percentage__c,
        S6130_Reinsurance_Broker_Commission__c,
        S6130_Reinsurance_Broker_Commission_Amou__c,
        S6130_Retail_Broker_Commission__c,
        S6130_Retail_Broker_Commission_Amount__c,
        Short_Name__c,
        Step__c,
        Subject_to_NDA__c,
        Sub_Status__c,
        Underwriter__c,
        UW_Reference__c,
        Renewal_Opportunity__c
        
        From Opportunity 
        where Opportunity.Insured_Period_to__c <= NEXT_90_DAYS 
        AND Opportunity.Renewal_Created__c != 'YES'
        AND (opportunity.StageName = 'Closed - Won' OR opportunity.StageName = 'Closed - Lost')]; 
        
        
        List<Opportunity> newOpps=new List<Opportunity>();

        for(Opportunity c: InList){
        
    if (c.StageName == 'Closed - Won'){
        Opportunity opp = c.clone();

            opp.StageName = 'New';
            opp.Renewal_Indicator__c = true;
            Opp.Insured_period_from__c = c.Insured_period_to__c;
            Opp.Insured_period_to__c = Opp.Insured_period_from__c.adddays(c.Insured_period_from__c.daysbetween(c.Insured_period_to__c));
            Opp.CloseDate = Opp.Insured_period_from__c.addmonths(-1);
            opp.Name = Opp.Insured_period_from__c.year() + '_' + c.Name.substringafter('_');
            c.Renewal_Opportunity__c = opp.name;    
            Opp.OwnerID = c.CreatedByID;
            c.Renewal_Created__c = 'Yes';
            Opp.Previously_won_or_lost__c = 'Won';
            Opp.Renewed_Opportunity__c = opp.Name;
            Opp.Renewal_Information__c = 'Original S6130 Line Size was : ' + Opp.S6130_Line_Size__c;
            newOpps.add(Opp);
                        {
                                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
                                    string [] toaddress= New string[]{'stuart.harrison@axa.com'}; 
                                    email.setSubject('New Renewal Opportunity - ' + opp.name); 
                                    email.setHTMLBody('A new renewal opportnity has been assigned to you : ' +   
                                    URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id
                                    + '<br/>'  + 
                                    '<br/>' + 'The opportunity (' + c.name + ') was previously ' + Opp.Previously_won_or_lost__c +
                                    ' and has an insured period to : ' + c.Insured_period_to__c
                                    + '<br/>' + 'Details from the previous Opportunity : ' + Opp.Renewal_Information__c); 
                                    email.setToAddresses(toaddress); 
                                    Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                        } 
            }
    if (c.StageName == 'Closed - Lost'){
        Opportunity opp = c.clone();

            opp.StageName = 'New';
            opp.Renewal_Indicator__c = true;
            Opp.Insured_period_from__c = c.Insured_period_to__c;
            Opp.Insured_period_to__c = Opp.Insured_period_from__c.adddays(c.Insured_period_from__c.daysbetween(c.Insured_period_to__c));
            Opp.CloseDate = Opp.Insured_period_from__c.addmonths(-1);
            opp.Name = Opp.Insured_period_from__c.year() + '_' + c.Name.substringafter('_');
            c.Renewal_Opportunity__c = opp.name;    
            Opp.OwnerID = c.CreatedByID;
            c.Renewal_Created__c = 'Yes';
            Opp.Previously_won_or_lost__c = 'Lost';
            Opp.Renewed_Opportunity__c = opp.Name;
            Opp.Renewal_Information__c = 'Lost Reason : ' + c.Lost_Cancel_Reason__c + ' - comment : ' + c.Lost_Cancelled_Reason_Comment__c + ' - Pricing : ' + c.Lost_Due_to_Pricing_Currency__c + ' ' + c.Lost_Due_to_Pricing_amount__c;
            Opp.Lost_Cancel_Reason__c = null;
            Opp.Lost_Cancelled_Reason_Comment__c = null;
            Opp.Lost_Due_to_Pricing_Currency__c = null;
            Opp.Lost_Due_to_Pricing_amount__c = null;
            newOpps.add(Opp);
                        {
                                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
                                    string [] toaddress= New string[]{'stuart.harrison@axa.com'}; 
                                    email.setSubject('Renewal Opportunity - ' + opp.name); 
                                    email.setHTMLBody('A new renewal opportnity has been assigned to you : ' +   
                                    URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id
                                    + '<br/>'  + 
                                    '<br/>' + 'The opportunity (' + c.name + ') was previously ' + Opp.Previously_won_or_lost__c +
                                    ' and has an insured period to : ' + c.Insured_period_to__c
                                    + '<br/>' + 'Details from the previous Opportunity : ' + Opp.Renewal_Information__c); 
                                    email.setToAddresses(toaddress); 
                                    Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email}); 
                        } 
          }
       if(!InList.isEmpty()) { 
            update InList; 
        } 
        }
       insert newOpps;
     }
           global void finish(Database.BatchableContext BC)
     {
    } 
}
Hello! I'm creating a before update Trigger that won't allow changing the agreement_start_date and agreement_end_date of an agreement when the jobs associated with it are not within the duration of the new dates.

Background:
- An agreement needs an agreement_start_date and agreement_end_date as its duration. 
- An agreement can have multiple Jobs assigned to it and every Job only has one service agreement assigned.
- Every Job has a job_start_date and job_end_date and is within the duration of the agreement_start_date and agreement_end_date.

Agreement_ABC
agreement_start_date = June 1, 2018
agreement_end_date = July 31, 2018

1. Job_01: 
job_start_date = July 1, 2018
job_end_date = July 15, 2018

2. Job_02:
job_start_date = June 2, 2018
job_end_date = June 30, 2018

Agreement_ABC New Dates
agreement_start_date = June 5, 2018
agreement_end_date = July 30, 2018
---> display an error disallowing to save as the new start date conflicts with Job_02 job_start_date

Scenario:
I want to update the agreement_start_date and agreement_end_date with new date values, however, a Trigger will not allow them to save the new dates if jobs associated to it are not within the new date duration.

How can I maximise the use of Set, List, and Map to develop the Trigger? Thanks.
Hi, I need to write a valdation rule for below scenario, 
Two Objects -- Eg, Accounts and Contacts. Contacts has a picklist called "Type" (values - 'Business' , 'Professional')..
I have a vf page where i can enter Account details, (multiple)Contacts and save all at one go.. Now the requirement is, if I save more than one contact, Type should be same - means, it should be either Bussiness or Professional for all contacts.. 
Is it possible to achieve this using ONLY vaidation rule (i cant write trigger for some reasons).?
 
I We are using a Custom object calles US_Counties which includes county name, state, and a list of employee personnel with a max record size of 3,145.
1) Programmatically I want to be able to search the map Collection that stores this info by County name and pull out a list of US Counties objecsts and then based on the Account's Physical state, insert certain personnel into the Account's Account team Object. 
Howvever when I search for the Accont's county name in the Map I get all 3,145 records returned.  Can anyone help me find out what I am doing incorrectly?   

2)  Also how can I use this with a batch script and  avoid the 10000 DML statements Governor Limit?
Thanks
Here is the code:
 
system.debug('<<NUMBER OF QUERIES In TOTAL : '+Limits.getLimitQueries());
        
        //For each account selected go and get the Account Team Mebmers while  updating the account owner.
        List<US_Counties__c> uscs = [Select Name,State_Name__c,Field_Director__c, Work_Group_Leader__c, Primary_Missionary__c from US_Counties__c  ORDER BY State_Name__c, Name Asc];
        Map<String,List<US_Counties__c>> usCounties = new Map<String,List<US_Counties__c>>();
        List<US_Counties__c> all_counties = new List<US_Counties__c>();
        for(US_Counties__c usc : uscs){
            	all_counties.add(usc);
            	usCounties.put(usc.Name,all_counties);
		}
        for(Account a: Accts){
        	system.debug('<<NUMBER OF QUERIES In TOTAL : '+Limits.getLimitQueries());
           	system.debug('<<ACCOUNT>> '+a);
            //Make sure that the Physical Counties are searched on and not Phys state because the returned list size is much less on avg.
            List<US_Counties__c> sampleCty = usCounties.get(a.Physical_County__c);
          	system.debug('<<GET COUNTIES SIZE>> '+sampleCty.size());//displays 3,145 records and not 8 for Orange County
            system.debug('<<GET PHY COUNTY >> '+a.Physical_County__c);
            List<US_Counties__c> countiesFound = new List<US_Counties__c>();
          try{
            	countiesFound = usCounties.get(a.Physical_County__c);
			system.debug('<<GET COUNTIES FOUND>> '+countiesFound);
              	for(US_Counties__c a_county : countiesFound){
                    if(a_county.State_Name__c == a.Physical_State__c){
                    	system.debug('<< NUMBER OF QUERIES USED >> '+ Limits.getQueries());
                		insert_ATM_FieldDirs.add(new AccountTeamMember(UserId=countiesFound[0].Field_Director__c, AccountId=a.Id,TeamMemberRole='Field Director')); 
                		insert_ATM_WGroupLdrs.add(new AccountTeamMember(UserId=countiesFound[0].Work_Group_Leader__c, AccountId=a.Id,TeamMemberRole='Work Group Leader'));
                		insert_ATM_PMissions.add(new AccountTeamMember(UserId=countiesFound[0].Primary_Missionary__c, AccountId=a.Id,TeamMemberRole='Primary Missionary'));
                		ownerIDS.add(countiesFound[0].Primary_Missionary__c);
                        break;
                    }
              	}
            	
            }catch(NullPointerException npex){ // TO test: 1)Create county that can be found or 2) that is mispelled 3) 1st letter not capitalized              
                
                system.debug(npex.getMessage());
                
            }//CATCH
             
    	}//OUT FOR



 
I'm facing an AccountHistory delete problem almost exactly the same as https://salesforce.stackexchange.com/questions/210984/accounthistory-not-deleting-immediately-after-an-update. Has anybody else faced this problem? Any ideas?
Hello,

i try to "convert" an attachement to a ContentVersion and link it to a related opportunity. Converting works but linking does not!
ia m getting this error message:
FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, You cannot create a link for this type of entity through the api: Linked Entity ID: [LinkedEntityId]

My code is:
trigger TrgAttachment on Attachment (after insert) {
    System.debug('TRG ' + Trigger.New[0]);
    Attachment att = Trigger.New[0];
    //Task t = Trigger.New[0];    
    System.debug('TYPE ' + att.ParentId.getSobjectType());
    Task t = [SELECT Subject, WhatId FROM Task WHERE id=:att.ParentId][0];
    
    System.debug('ATT ' + att);
    if(t.WhatId <> NULL && t.WhatId.getSobjectType() == opportunity.getSObjectType()){

        Opportunity o = [SELECT Id, Name FROM Opportunity WHERE id=:t.WhatId][0];
        System.debug('Related to opps' + o);
        
        ContentVersion cv = new ContentVersion();
        cv.ContentLocation = 'S';
        cv.PathOnClient = att.Name;
        cv.Origin = 'H';
        cv.OwnerId = att.OwnerId;
        cv.Title = att.Name;
        cv.VersionData = att.Body;
        insert cv;
        
        ContentVersion cv1 = [select Id, ContentDocumentId from ContentVersion where Id =: cv.Id][0];
        Id linkDoc = o.Id;
        ContentDocumentLink cl = new ContentDocumentLink();
        cl.LinkedEntityId = linkDoc;
        cl.ContentDocumentId = cv1.ContentDocumentId;
        cl.ShareType = 'V';
        try{
            insert cl;
        }
        catch(Exception ex){
            throw ex;
        }

        
    }
}
Can someone help?

thanks
Peter
 
Hello Everyone, 
Is it Possible to auto assign data.com licenses with 300 limit to newly created  users? If yes, How can it be done? Triggers? Process builder? 
Thank you for your help
1. Create a custom field on the Contact object: Is Primary Contact (checkbox)
2. Create a custom field on the Contact object: Primary Contact Phone (Phone);
3. A validation should be added so that if the Account already has a Primary Contact set a new one cannot be added;​
4. When a contact is set as primary, the Primary Contact Phone should be updated to all Contacts related to the same account. This should be an asynchronous process. Make sure that if one Contact update fails, it doesn’t rollback the changes for the others.
Hello, I am looking to create a trigger that will update an account field to "Null" or "0" when a child asset is deleted. The two account fields are Max Advisor Count, and Max Mortgage Advisor Count. When adding an asset, depending on the type, it will add a quantity of "1" to either the Max Advisor Count or the Max Mortgage Advisor Count

I set up Process Builder to update those counts when an asset record is created or changed. But it looks like I will need a trigger to set either of those counts to 0 when an asset record is deleted.

All I need is for the trigger to fire after an asset is deleted. Any suggestions are welcome, thank you!!!
By writing an apex trigger on salesforce i get this error message and i don't understand what line -1 and column -1 mean. Can someone help me ? 

Here is my code : 

Trigger OpportunityTrigger on Opportunity (after insert, after update, after delete, after undelete) {
     List<Opportunity>  opportunities =  new  List<Opportunity>();
                   if(Trigger.isAfter){
                       if(Trigger.isInsert || Trigger.isUndelete){
                          opportunities = Trigger.new;
                       }else if(Trigger.isUpdate){                   
 for(Opportunity Opportunity : Trigger.new){
    if(Opportunity.Amount != Trigger.oldMap.get(Opportunity.id).Amount){
        opportunities.add(Opportunity);
    }
                              }
                       } else if(Trigger.isDelete){
                            opportunities  = trigger.old;
                       }
                   }
        list<RollUpSummaryUtility.fieldDefinition> fieldDefinitions1 = 

            new list<RollUpSummaryUtility.fieldDefinition> {

                new RollUpSummaryUtility.fieldDefinition('SUM', 'Amount', 

                'PreviousOpp_MRR__c')

            };

        RollUpSummaryUtility.ObjectDefination objDef = 
          new RollUpSummaryUtility.ObjectDefination('Opportunity','AccountId','Account','',null);

        new RollUpSummaryUtility().rollUp(fieldDefinitions1, objDef , opportunities); 
}
Here is what I need to achieve:
track how many times BDM_Projected_Launch_Date__c gets changed in Count_of_PLD_changes__c
calculate difference in months between the very first BDM_Projected_Launch_Date__c and last one in of_Months_since_1st_PLD__c
the very first BDM_Projected_Launch_Date__c value is recorded on PLD_first_Value__c and it gets populated at record creation by a WFR

here is what I've done so far but it's not really working.
trigger ProjectedLiveDateTracking on Opportunity (before update) {

  Map<Id,Opportunity> o = new Map<Id,Opportunity>();
  
    o = trigger.oldMap;
    
    for(Opportunity newopp: trigger.new)
    {
        
        
        if(newopp.BDM_Projected_Launch_Date__c != o.get(newopp.Id).BDM_Projected_Launch_Date__c)
        
        {
        
        Date old = o.get(newopp.Id).PLD_first_Value__c;
        Date first = newopp.BDM_Projected_Launch_Date__c;
        Integer monthDiff = old.monthsBetween(first);
        if (first.day() > old.day()) monthDiff++;
        System.debug(monthDiff);
        newopp.of_Months_since_1st_PLD__c = monthDiff;
        newopp.Count_of_PLD_changes__c++;

        }
        
    }
}



 
If I have some object A, that has fields
 
Name(string), B__c (sObject) and C__c (sObject)

B__c has the fields 
    
Name(string), BB__c (string of "Yes", "No" and "Maybe)

and C__c has the fields 
 
Name(string), CC_c (bool)



how would I filter such that I can get all A's where 
 
A.B__c.BB__c == "Yes" and A.C__c.CC__c == true



I basically tried the following but I got an error about sObject
 
return [
            SELECT Id, Name, B__c, C__c
            FROM A
            WHERE B__c.BB__c = :"Yes"
            And C__c.CC__c = :true
        ];



 
I need to check if a field is being used in any of the reports in the org. So I created a sandbox environment and created a manifest project in VScode; then authorized the sandbox org and ran the command "SFDX: Retrieve Source in Manifest from Org" by right clicking the package.xml file. All the apex classes and triggers were retrieved but the reports meta data were not retrieved. Here's a part of the content in the package.xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <name>ApexClass</name>
    </types>
    <types>
        <members>*</members>
        <name>ApexComponent</name>
    </types>
    <types>
        <members>*</members>
        <name>ApexPage</name>
    </types>
    <types>
        <members>*</members>
        <name>ApexTestSuite</name>
    </types>
    <types>
        <members>*</members>
        <name>ApexTrigger</name>
    </types>
    <types>
        <members>*</members>
        <name>AuraDefinitionBundle</name>
    </types>
    <types>
        <members>*</members>
        <name>LightningComponentBundle</name>
    </types>
    <types>
        <members>*</members>
        <name>StaticResource</name>
    </types>
    <types>
        <members>PublicReports/AvailableToWorkToday</members>
        <name>Report</name>
    </types>
    <version>45.0</version>
</Package>

But I get the error: Entity of type 'Report' named 'PublicReports/AvailableToWorkToday' cannot be found
Even if this works I'll only be able to retrieve one particular report meta-data which is of no help as I need to retrieve all the reports meta-data at once.
Any help on this would be great. Thanks
Hello, 

I need the trigger below to only run for a specific opportunity record type called 'Conference'. Any assistance is greatly appreciated.
 
trigger UpdateOpportunityProduct on Opportunity (before insert, before update ){

    Map<String, Opportunity> discCodeToOppMap = new Map<String, Opportunity>();

    for(Opportunity opp:Trigger.new){

    discCodeToOppMap.put(opp.Discount_Code__c, opp);

    }

    List<Product2> prodLst = [SELECT ID, ProductCode FROM Product2 where ProductCode in :discCodeToOppMap.keySet()];

    for(Product2 prod : prodLst){
    
        discCodeToOppMap.get(prod.ProductCode).Discount_Code_LU__c = prod.ID;
    }
}

 
  • May 28, 2019
  • Like
  • 0
AND (
  OR (
    [Case].RecordType.Name = 'Community',
    [Case].RecordType.Name = 'Payer',
    [Case].RecordType.Name = 'Partner'
  ),
  OR (
    AND (
      ISCHANGED([Case].Send_Attachment_Notification__c ),
      [Case].Send_Attachment_Notification__c = true
    ),
    AND (
      ISCHANGED([Case].Send_Comment_Notification__c ),
      [Case].Send_Comment_Notification__c = true
    )
  ),
  BEGINS([Case].OwnerId, '005'),
)
This code (not written by me) references the Id of a record in a before insert trigger. I was always under the impression you couldn't do that, as there is no Id before the record is committed to the database.

But it works... the Campaign__c field is correctly set every time. So naturally my question is how does it work? Because of the Id reference, or in spite of it? Is this some well known feature of Apex that I should be aware of, or a flawed trigger that happens to do the right thing?

trigger RegionTargetSetCampaign on Region_Targets__c (before insert) {

    Map<Id,Id> regionTargetToCallingGuide = new Map<Id,Id>();
    
    for(integer i=0; i<Trigger.size; i++) {
        Region_Targets__c regionTarget = Trigger.new[i];
        regionTargetToCallingGuide.put(regionTarget.id, regionTarget.Campaign_Delivery__c);
    }
    
    Map<Id,Campaign_Delivery__c> callingGuideMap = new Map<Id,Campaign_Delivery__c>([SELECT id, Campaign__c FROM Campaign_Delivery__c WHERE id IN :regionTargetToCallingGuide.values()]);
    
    for(Region_Targets__c regionTarget : Trigger.new) {
        regionTarget.Campaign__c = callingGuideMap.get(regionTargetToCallingGuide.get(regionTarget.id)).Campaign__c;
    }
}
Good morning folks,

I was wondering if its is possible to have a trigger on attachment whereas it would check if the record already has an attached file, and if so it would give an error and would not allow anymore files to be attached on said record.

And if the latter is indeed possible what should the trigger be counting? Attachments or Contentdocument?

Thanks in advanced for the help.
I have a requirement that I have to fetch all the Account Lookup fields.I'm using Schema.DisplayType for fetching Text,Picklistlist fields.But for lookup fields I don't know how to fetch.Can anyone help me?
Hello all,

I have a Before Insert Trigger on Leads object. On my Leads object I have a custom field, NetNewLead with a default value of TRUE.

My trigger checks the Contacts object looking for a match on Leads.Email = Contacts.Email and when a match is found NetNewLead is set to FALSE.

My trigger works correctly when I enter a new Lead, however Web-To-Lead always sets my custom field NetNewLead to FALSE even when the Leads.Email is not found as a Contacts.Email.

Any ideas? I have includded my code if you would like to take a look.

* I know I need to remove hard-coded check for RecrdTypeId.

Thanks for your help in advance.

Robert.


trigger Update_NetNewLead_Trigger on Lead (before insert) {

// Step 1 - Iterate over incoming Leads and store email in a set
    List<String> leadEmails = new List<String>();
    for(Lead lead:Trigger.new){
        leadEmails.add(lead.Email);
    }

// Step 2 - Check whether there are any existing Business Contacts with matching email

    //Id RecordTypeIdContact = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Business_Contact').getRecordTypeId();

    List<Contact> contacts = [
        SELECT 
            Id, Email 
        FROM 
            Contact
        WHERE 
            //Email IN :leadEmails and RecordTypeId=:RecordTypeIdContact 
            Email IN :leadEmails and RecordTypeId='0121A0000007rgsQAA'
            // Only Select "Business Contacts" 
    ];

    Set<String> contactEmails = new Set<String>();
    for(Contact contact:contacts){
        contactEmails.add(contact.Email);
    }

// Step 3 - Iterate over Leads if Business Contact has matching email set NetNewLead = False
    for(Lead lead:Trigger.new){
        if(contactEmails.contains(lead.Email)){
            lead.NetNewLead__c = False;
        }
    }
}

 
I have a custom button on the Quote object that, as part of it's function, I want it to select only the most recent document from the 'Files' related list to be sent out.

Right now it 'grabs' all the files in the related list - is there some code I can add to the button that limits it to only the most recent file? What would that code look like?

Thanks, Roger
Hello, 

We have a Lead Trigger set in our org and its been active since 2013. 
 I came across this Salesforce document stating that the first name and last name character limits have increased. 

https://help.salesforce.com/articleView?id=leads_fields.htm&type=5

First Name character limit is 40
Last Name character limit is 80

So created a lead with 30 characters for the first name and 40 for the last name, to be modest. Well, I received the error message that the max limit is 20 characters, etc. Contacted Salesforce, and concluded that a custom lead trigger, shown below, was the culprit. I deactivated it, tested a new lead with the number of characters I tried before, and it worked. 

Unfortunately, I can't deactivate this trigger in production since it is executing various actions. Is there a way to modify this code to allow the first and last name to increase the character limits when a new lead is created? 

The past few months we've been receiving email erroring out and we found out why, but now need to know if anyone can help me out. 

Thanks!
 
trigger triggerLead on Lead (after insert, before insert, before update, after update) {

    LeadTrigger lt = new LeadTrigger();
    if (Trigger.isInsert)
        lt.LeadInsertion(Trigger.New, Trigger.isBefore, Trigger.isAfter);
    else if (Trigger.isBefore)
        lt.LeadUpdate(Trigger.New, Trigger.old, Trigger.isBefore);
    
    if (Trigger.isAfter) {
        lt.ReassignALOnClosedLeads(Trigger.New, Trigger.old, null);
        lt.AddToCampaign(Trigger.New, Trigger.oldMap);
        lt.ProcessQuotingLeads(Trigger.New, Trigger.old);
    } else 
        lt.PopulateAmbassador(Trigger.New, Trigger.old);   
        
    if (Trigger.isBefore && Trigger.isUpdate){
        lt.CreateLastVisitTask(Trigger.new);
        lt.CopyHistoryLog(Trigger.new, Trigger.oldMap);   
    }
}

 
Dear Friends,

i got an requirement, I have teacher and student lookup relationships objects. Teacher object will have student related list, student related list will show student name and their total fees paid. I need to have custom field in Teacher object which will show total fees of all students uunder him.
i would like to use batch apex to update the total fees in Teached object based on student related list fees.

it would be great help if you could direct me to get the proper sample code.

Teacher Obect 
                  Fee total ( Sum ( all students fees under this teacher))


 Thanks in advance 
 
I have a flow that creates multiple records at once. The last record I am trying to create has record types and with each record types. When i try to create a specific record "Software" by running the flow it give me the following error.

Error Occurred: This error occurred when the flow tried to create records: INVALID_FIELD_FOR_INSERT_UPDATE: Yushin_Product__c: bad field names on insert/update call: Brief_description_of_the_modification__c, Current_running_program__c, New_Errors__c.

I'm guessing this is caused by not having the record type that would associate the new software record and fields on the page.

I've tried a few different things but nothing seems to work. I am working in the new Flow Builder UI, so anything i find online doesnt match my option because the screenshot are from the old version of flow. 

below ar escreenshot of my flow. Any help would be greatly appreciated.

Account record creation
User-added image

Opportunity Creation
User-added image

Software record creation

User-added image
 
  • February 20, 2019
  • Like
  • 0
My requirement is,  

Convert Lead status as Joined based on Membershiphistory Begin date and lead created date. But Lead and Membership history does not have relationship. Lead and Member having lookup relation and member and membershiphistory having lookup relationship.
Good day developers

I have a Apex Class in Sandbox which redirects a user to a record created from a visual workflow with the help of a visualforce page:

public with sharing class FlowRedirectController {

    public Object FlowRedirectController() { 
        String unique_id = ApexPages.currentPage().getParameters().get('id');
        
        if(unique_id == null){
            // Return Home if no ID 
            String url = '/home/home.jsp';
            return new PageReference(url);
         } 
         
         // Get Order ID and set Redirect 
         String orderId = [SELECT Name,
                                    Unique_Flow_Identifier__c, 
                                    Id  
                             FROM Order  
                             WHERE Unique_Flow_Identifier__c = :unique_id 
                             ORDER BY CreatedDate DESC   
                             LIMIT 1].Id;
                             
        // Did we find a Order? 
        if (orderId == null) {
            // Return Home if no ID 
            String url = '/home/home.jsp'; 
            return new PageReference(url); 
            }

        // Redirect to Order 
        String url = '/' + orderId;
        return new PageReference(url); 
        }
}


When deploying to production I am getting code coverage error. This is becasue I need to create an Apex Test Class however being new to Apex i'm unsure what I would need to test in this code... Is anyone able to help with this?

Thanks