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

  • Chatter
    Feed
  • 197
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 939
    Replies
hi , created a list and going to add the record , but the 1st record is not getting added, only the second record is geting add, my i knw the reason behind that thanks ..
<apex:page controller="accountinsert" >
 
 
  <apex:form >
   
   <apex:pageblock >
    <apex:pageblockSection >
     
     <apex:inputField value="{!acc.name}"/>
    <apex:inputField value="{!acc.phone}"/>
    <apex:inputField value="{!acc.Rating}"/>
    <apex:inputField value="{!acc.Industry}"/>
    
    </apex:pageblockSection>
   
    <apex:pageblockButtons location="top">
    
    <apex:commandButton Value="Submit" action="{!addtolist}"  />
    
     <apex:commandButton Value="Clear" action="{!Clear}"  />
    </apex:pageblockButtons>
   
   <apex:pageblockSection columns="1" Rendered="{!lstaccount.size>0}"  >
   
     <apex:pageblockTable value="{!lstaccount}" var="a"  > 
    
     <apex:column headerValue="Name">{!a.name}</apex:column>
     
     <apex:column headerValue="Phone">{!a.Phone}</apex:column>
     
     <apex:column headerValue="Rating">{!a.Rating}</apex:column>
     
     
     <apex:column headerValue="industry">{!a.industry}</apex:column>
    </apex:pageblockTable>
    
    
   </apex:pageblockSection>
  
   
   
   
   
   </apex:pageblock>
  
  </apex:form>
</apex:page>

Controller:
 
public class accountinsert {

 public list<account> lstaccount{get;set;}
 
  public account acc{get;set;}
  
  
   public accountinsert(){
   
    lstaccount= new list<account>();
     //acc = new account();
  
   }
   
    public void addtolist(){
    
     acc = new account();
      
    lstaccount.add(acc);
    
    
    }
    
    public void Clear(){
    
    lstaccount.clear();
    
    }
}

my i know the reason, why iam not getting add, the 1st record, and other getting added,,

Thanks 
Deepika


 
hi, i have an extention controller and a test method but i am only able to achieve 13 % converage, 3/23. This code is just queries and sending the output to a visualforce page. Can anyone please explain what i need to test for to get 100% coverage? And an example woudl be helpful too, please. Thank you!

controller:
public extendAccountsChannel2(ApexPages.StandardController controller) {
        Id id = ApexPages.currentPage().getParameters().get('id');
        
        
        if(ApexPages.currentPage().getParameters().get('id') != null){
            
           id accRecId = [select id from Account where id = :id].id;
           
           
            if(accRecId != null){
                channels = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Retail' AND Investor_Status__c = 'Active' LIMIT 1];
                channelsWholesale = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Wholesale' LIMIT 1];  
                channelsMiniCorrespondent = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Mini Correspondent' LIMIT 1];
                channelsCorrespondentAOTDirectTrade = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent AOT / Direct Trade' LIMIT 1]; 
                channelsCorrespondentBestEfforts = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Best Efforts' LIMIT 1]; 
                channelsCorrespondentMandatoryBulkFlow = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Mandatory (Bulk/Flow)' LIMIT 1]; 
                channelsCorrespondentNonDelegated = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Non Delegated' LIMIT 1];
                channelsCorrespondentNonDelMandatory = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Non-Del Mandatory' LIMIT 1];
                
                
                 
            }
        }
        
        
        
    }
    
}

test:
 
@isTest
private class extendAccountsChannel2_Test{   
    static testMethod void extendAccountsChannel2_channels(){
        
        Account aa = new Account();
        aa.name='TestInvestor';
        insert aa;
        
        //Create Retail Channel   
        Investor_Channel__c ic = new Investor_Channel__c();
        ic.Channel__c ='Retail';
        ic.Investor_Status__c = 'Active';
        ic.Account_Name__c = aa.Id;
        insert ic;
        
        //Create Wholesale Channel   
        Investor_Channel__c ic2 = new Investor_Channel__c();
        ic2.Channel__c ='Wholesale';
        ic2.Account_Name__c = aa.Id;
        insert ic2;
        
        //Create Mini Correspondent Channel   
        Investor_Channel__c ic3 = new Investor_Channel__c();
        ic3.Channel__c ='Mini Correspondent';
        ic3.Account_Name__c = aa.Id;
        insert ic3;
        
        //Create Correspondent AOT / Direct Trade   
        Investor_Channel__c ic4 = new Investor_Channel__c();
        ic4.Channel__c ='Correspondent AOT / Direct Trade';
        ic4.Account_Name__c = aa.Id;
        insert ic4;
                
           

        ApexPages.StandardController sc = new ApexPages.StandardController(aa);
        extendAccountsChannel2 testAccPlan = new extendAccountsChannel2(sc);
         
        PageReference pageRef = Page.Investor_Channel_Tabs; // Add your VF page Name here
        Test.setCurrentPage(pageRef);
            
         
        //Verify that records were created
   List <Investor_Channel__c> channels = [SELECT Id FROM Investor_Channel__c WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Retail'LIMIT 1];
    
      
        System.assert( channels  != null);
  
    
    
    List <Investor_Channel__c> channelsWholesale = [SELECT Id FROM Investor_Channel__c  WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Wholesale'LIMIT 1];
          System.assert( channelsWholesale != null);
    
    
    List <Investor_Channel__c> channelsMiniCorrespondent = [SELECT Id FROM Investor_Channel__c  WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Mini Correspondent'LIMIT 1];
          System.assert( channelsMiniCorrespondent != null);
          
          List <Investor_Channel__c> channelsCorrespondentAOTDirectTrade = [SELECT Id FROM Investor_Channel__c  WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Correspondent AOT / Direct Trade'LIMIT 1];
          System.assert( channelsCorrespondentAOTDirectTrade != null);
    
    
    
        
}
}

​​​​​​​
  • March 03, 2020
  • Like
  • 0
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); 
}
I have written a code to calculate SI . But the result is not getting displayed. Can anyone help me with the code

HTML

<template>
    <lightning-card title="Simple Interest Cal"></lightning-card>
   
        <lightning-layout multiple-rows></lightning-layout>
            <lightning-layout-item size= "12" padding = "around-medium" > </lightning-layout-item>
<lightning-input type="number" label = "Enter Principle" onchange= {principalChangeHandler}>
    </lightning-input>
   
    <lightning-layout-item size= "12" padding = "around-medium" > </lightning-layout-item>
    <lightning-input type="numer" label = "Enter No Of Years" onchange= {timechangehandler}>
    </lightning-input>
   
    <lightning-layout-item size= "12" padding = "around-medium" > </lightning-layout-item>
    <lightning-input type="number" label = "Enter Rate Of Interest" onchange= {ratechangehandler}>
    </lightning-input>
   
    <lightning-layout-item size= "12" padding = "around-medium" ></lightning-layout-item>
    <lightning-button label= "Calculate SI" icon-position = "centre" onclick= {calculateSIHandler} >
    </lightning-button>

<lightning-layout-item size= "12" padding = "around-medium" > </lightning-layout-item>
    <lightning-formatted-text value= {currentoutput}  ></lightning-formatted-text>
   
       
</template>

Json

import  { LightningElement, track } from 'lwc';
export default class Simpleinterstcal extends LightningElement {
   
@track currentOutput;
principal;
rateofinterest;
noOfyears;
principalChangeHandler (event)
{
this.principal = parseInt(event.target.value,10);
}
timechangehandler (event)
{
this.noOfyears = parseInt(event.target.value,10);
}
ratechangehandler (event)
{
this.rateofinterest = 10);
}
calculateSIHandler()
{
this.currentOutput =  'Simple Interest is :' +parseFloat((this.principal*this.rateofinterest*this.noOfyears)/100);
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
<targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Hello everyone, I want to create a SOQL query to solve an issue I have with a field that I want to filter information from. The field records names of people in the record of this custom object. The issue is, that when there are 3 records in which the field for the first record is filled with "X", the second with "X, Y" and the third with "X, Y, Z", the data is difficult to use for reports/dashboards as it gives you three different records rather than recognising 3 records for X, 2 for Y and 1 for Z. 

Essentially I want to create a SOQL Query that pulls all records from the database in which the records field contains X and then repeat that query for every single individual, so I have a singular number for every individual.

The first issue I ran into is that I cannot use the CONTAINS operator in SQOL. Can I instead use LIKE %X%? Does anyone have experience with a process like this? Am I on the right track with my idea?

Any feedback or ideas would be greatly appreciated. 
Hi, Can someone tell me in detail about Remote Action in Salesforce. 
hi , created a list and going to add the record , but the 1st record is not getting added, only the second record is geting add, my i knw the reason behind that thanks ..
<apex:page controller="accountinsert" >
 
 
  <apex:form >
   
   <apex:pageblock >
    <apex:pageblockSection >
     
     <apex:inputField value="{!acc.name}"/>
    <apex:inputField value="{!acc.phone}"/>
    <apex:inputField value="{!acc.Rating}"/>
    <apex:inputField value="{!acc.Industry}"/>
    
    </apex:pageblockSection>
   
    <apex:pageblockButtons location="top">
    
    <apex:commandButton Value="Submit" action="{!addtolist}"  />
    
     <apex:commandButton Value="Clear" action="{!Clear}"  />
    </apex:pageblockButtons>
   
   <apex:pageblockSection columns="1" Rendered="{!lstaccount.size>0}"  >
   
     <apex:pageblockTable value="{!lstaccount}" var="a"  > 
    
     <apex:column headerValue="Name">{!a.name}</apex:column>
     
     <apex:column headerValue="Phone">{!a.Phone}</apex:column>
     
     <apex:column headerValue="Rating">{!a.Rating}</apex:column>
     
     
     <apex:column headerValue="industry">{!a.industry}</apex:column>
    </apex:pageblockTable>
    
    
   </apex:pageblockSection>
  
   
   
   
   
   </apex:pageblock>
  
  </apex:form>
</apex:page>

Controller:
 
public class accountinsert {

 public list<account> lstaccount{get;set;}
 
  public account acc{get;set;}
  
  
   public accountinsert(){
   
    lstaccount= new list<account>();
     //acc = new account();
  
   }
   
    public void addtolist(){
    
     acc = new account();
      
    lstaccount.add(acc);
    
    
    }
    
    public void Clear(){
    
    lstaccount.clear();
    
    }
}

my i know the reason, why iam not getting add, the 1st record, and other getting added,,

Thanks 
Deepika


 
Hello,

First time to post so apologies if this is not in the correct area.

I am working on some code executed in anonymous that will insert some records in a charity's org.   The charity has job records, on those jobs exist shifts, and those shifts can have hours, for context.

The problem at the moment is that several jobs exist in the org which have shifts, but the hours were not correctly added, so I created the script below which can create those hour records and successfully copy over all the information that is needed from the shift/job record.  However, when I attempt to run this in the live version on a single record (which has 21 shifts)  I am getting Error:System.LimitException: Too many SOQL queries:101.

Below is my script:
List<GW_Volunteers__Volunteer_Job__c> badJobs = new list<GW_Volunteers__Volunteer_Job__c>();
badJobs=[SELECT Id FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__First_Shift__c!=NULL AND GW_Volunteers__Number_of_Completed_Hours__c=0]; //jobs that have shift with no hr
    
List<GW_Volunteers__Volunteer_Shift__c> needsHr = new list <GW_Volunteers__Volunteer_Shift__c>();
needsHr=[SELECT Id, GW_Volunteers__Start_Date_Time__c,GW_Volunteers__Duration__c, GW_Volunteers__Volunteer_Job__r.Volunteer__c FROM GW_Volunteers__Volunteer_Shift__c WHERE GW_Volunteers__Volunteer_Job__c in :badJobs]; //shift records with no hrs
for (GW_Volunteers__Volunteer_Shift__c s :needsHr){
    DateTime dT = s.GW_Volunteers__Start_Date_Time__c;
    Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
    GW_Volunteers__Volunteer_Hours__c hour = new GW_Volunteers__Volunteer_Hours__c(
        GW_Volunteers__Contact__c=s.GW_Volunteers__Volunteer_Job__r.Volunteer__c,
    	GW_Volunteers__Status__c='Completed',
    	GW_Volunteers__Hours_Worked__c=s.GW_Volunteers__Duration__c,
    	GW_Volunteers__Volunteer_Job__c=s.GW_Volunteers__Volunteer_Job__c,
        GW_Volunteers__Volunteer_Shift__c=s.Id,
    	GW_Volunteers__Start_Date__c=myDate,
        GW_Volunteers__End_Date__c=myDate
        
        
    
    );
    insert hour;
}

I believe I need to adjust this so that it is calling fewer queries, but I am not entirely sure what I can do other than put a LIMIT which won't really work for me as I need to run through all of the shifts on a given job record in one go.
When I change the shift query to the following, the script will run fine and insert hours corresponding to the correct shift records:
needsHr=[SELECT Id, GW_Volunteers__Start_Date_Time__c,GW_Volunteers__Duration__c, GW_Volunteers__Volunteer_Job__r.Volunteer__c FROM GW_Volunteers__Volunteer_Shift__c WHERE GW_Volunteers__Volunteer_Job__c ='a0T3Y00000SLivnUAD' LIMIT 10];

I am grateful for any assistance on this.

Thank you.
El
 
  • March 03, 2020
  • Like
  • 0
hi, i have an extention controller and a test method but i am only able to achieve 13 % converage, 3/23. This code is just queries and sending the output to a visualforce page. Can anyone please explain what i need to test for to get 100% coverage? And an example woudl be helpful too, please. Thank you!

controller:
public extendAccountsChannel2(ApexPages.StandardController controller) {
        Id id = ApexPages.currentPage().getParameters().get('id');
        
        
        if(ApexPages.currentPage().getParameters().get('id') != null){
            
           id accRecId = [select id from Account where id = :id].id;
           
           
            if(accRecId != null){
                channels = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Retail' AND Investor_Status__c = 'Active' LIMIT 1];
                channelsWholesale = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Wholesale' LIMIT 1];  
                channelsMiniCorrespondent = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Mini Correspondent' LIMIT 1];
                channelsCorrespondentAOTDirectTrade = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent AOT / Direct Trade' LIMIT 1]; 
                channelsCorrespondentBestEfforts = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Best Efforts' LIMIT 1]; 
                channelsCorrespondentMandatoryBulkFlow = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Mandatory (Bulk/Flow)' LIMIT 1]; 
                channelsCorrespondentNonDelegated = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Non Delegated' LIMIT 1];
                channelsCorrespondentNonDelMandatory = [SELECT Id from Investor_Channel__c WHERE Account_Name__r.id= :accRecId AND Channel__c = 'Correspondent Non-Del Mandatory' LIMIT 1];
                
                
                 
            }
        }
        
        
        
    }
    
}

test:
 
@isTest
private class extendAccountsChannel2_Test{   
    static testMethod void extendAccountsChannel2_channels(){
        
        Account aa = new Account();
        aa.name='TestInvestor';
        insert aa;
        
        //Create Retail Channel   
        Investor_Channel__c ic = new Investor_Channel__c();
        ic.Channel__c ='Retail';
        ic.Investor_Status__c = 'Active';
        ic.Account_Name__c = aa.Id;
        insert ic;
        
        //Create Wholesale Channel   
        Investor_Channel__c ic2 = new Investor_Channel__c();
        ic2.Channel__c ='Wholesale';
        ic2.Account_Name__c = aa.Id;
        insert ic2;
        
        //Create Mini Correspondent Channel   
        Investor_Channel__c ic3 = new Investor_Channel__c();
        ic3.Channel__c ='Mini Correspondent';
        ic3.Account_Name__c = aa.Id;
        insert ic3;
        
        //Create Correspondent AOT / Direct Trade   
        Investor_Channel__c ic4 = new Investor_Channel__c();
        ic4.Channel__c ='Correspondent AOT / Direct Trade';
        ic4.Account_Name__c = aa.Id;
        insert ic4;
                
           

        ApexPages.StandardController sc = new ApexPages.StandardController(aa);
        extendAccountsChannel2 testAccPlan = new extendAccountsChannel2(sc);
         
        PageReference pageRef = Page.Investor_Channel_Tabs; // Add your VF page Name here
        Test.setCurrentPage(pageRef);
            
         
        //Verify that records were created
   List <Investor_Channel__c> channels = [SELECT Id FROM Investor_Channel__c WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Retail'LIMIT 1];
    
      
        System.assert( channels  != null);
  
    
    
    List <Investor_Channel__c> channelsWholesale = [SELECT Id FROM Investor_Channel__c  WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Wholesale'LIMIT 1];
          System.assert( channelsWholesale != null);
    
    
    List <Investor_Channel__c> channelsMiniCorrespondent = [SELECT Id FROM Investor_Channel__c  WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Mini Correspondent'LIMIT 1];
          System.assert( channelsMiniCorrespondent != null);
          
          List <Investor_Channel__c> channelsCorrespondentAOTDirectTrade = [SELECT Id FROM Investor_Channel__c  WHERE Account_Name__r.id = :aa.Id AND Channel__c ='Correspondent AOT / Direct Trade'LIMIT 1];
          System.assert( channelsCorrespondentAOTDirectTrade != null);
    
    
    
        
}
}

​​​​​​​
  • March 03, 2020
  • Like
  • 0
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
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