• Sainath Venkat
  • NEWBIE
  • 271 Points
  • Member since 2017

  • Chatter
    Feed
  • 5
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 54
    Questions
  • 133
    Replies
Hi,

I need help writing a test for the following trigger which submits a record for approval if the created_from_onboarding__c checkbox field is marked true.
trigger autoapprovenewhire on Change_of_statusnew__c (after insert) {
    for(Change_of_statusnew__c changeofstatus : trigger.new){
        if(changeofstatus.created_from_onboarding__c == TRUE){
            // create the new approval request to submit
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Submitted for approval. Please approve.');
            req.setObjectId(changeofstatus.Id);
            // submit the approval request for processing
            Approval.ProcessResult result = Approval.process(req);
            // display if the reqeust was successful
            System.debug('Submitted for approval successfully: '+result.isSuccess());
        }
    }
}
@AuraEnabled
    public static void updatePicturePath(String recId){
        //In Lightning Experience, Attachments are stored in ContentDocuments
        ContentDocumentLink docLink = [ SELECT ContentDocumentId
                               FROM ContentDocumentLink
                               WHERE LinkedEntityId = :recId order by Id desc Limit 1];
        //ContentVersion Id uniquely identifies the attachment
        ContentVersion ver = [SELECT Id FROM ContentVersion Where ContentDocumentId = :docLink.ContentDocumentId];
        //Update the Picture_Path field with the url of the image
        Speaker__c speaker = [SELECT Id FROM Speaker__c WHERE Id = :recId];
        speaker.Picture_Path__c = '/sfc/servlet.shepherd/version/download/'+ ver.Id;
        upsert speaker;
    }
====================================
Unexpected token 'void'.
A developer creates a Workflow Rule declaratively that updates a field on an object. An Apex update trigger exists for that object.
What happens when a user updates a record?  

A. No changes are made to the data.
B. Both the Apex Trigger and Workflow Rule are fired only once.
C. The Workflow Rule is fired more than once.
D. The Apex Trigger is fired more than once
I need help in writing a trigger, I have two objects

1) Opportunity
2) Opportunity_ Program__c

both are having lookup relationship, Opportunity is Parent and Opportunity Program is child.

Opportunity program has Status field.

I need to write a trigger on Opportunity Program object, for a given Opportunity if any of the child records contains status as "MATR" then Opportunity.StageName = 'Closed Won', if any of the child record for a given opportunity does not contain "MATR" then Opportunity.StageName = 'Closed Lost'

Can anyone helps me out in this issue please.
I am working one trigger which will update the stage in Opportunity based on child field.
for a given opportunity, if any of the child record contains Program_Action__c = "MATR" then I want to update the status to Closed Won, if none of the child records contains MATR and only contains "WADM" or "WAPP" then stage is Closed Lost and child records contains Program_Action__c = "ADMT" then stage should be Open
My code is working for all conditions but if any of the child record contains MATR then stage is not updating to "Closed Won".
Can anyone helps me out in this issue here.
public class ParentUpdateFromChildOpportunity {
public static void ParentUpdate(List<Opportunity_Programs__c> oppProgramList){
    try{
            System.debug('Opportunity List==>'+oppProgramList);

    Set<Id> opportunityId = new Set<Id>();
    for(Opportunity_Programs__c oppPrgmObj : oppProgramList){
        opportunityId.add(oppPrgmObj.Opportunity_ID__c);
    }
    List<Opportunity> opportunityList = New List<Opportunity>();
    opportunityList = [Select Id,
                       StageName
                       From Opportunity
                       Where Id IN : opportunityId
                       Limit 50000
                      ];
    Integer won=1;
    List<Opportunity> olist=new List<Opportunity>();
    for(Opportunity_Programs__c oppPrgmObj2 : oppProgramList){
        for(Opportunity oppObj : opportunityList){
            if(oppPrgmObj2.Program_Action__c == 'MATR' && (oppPrgmObj2.Opportunity_ID__c == oppObj.Id)){
                oppObj.StageName='Closed Won';
                olist.add(oppObj);
                won=2;
            }
            else if((oppPrgmObj2.Program_Action__c == 'WADM' ||oppPrgmObj2.Program_Action__c == 'WAPP') && (oppPrgmObj2.Opportunity_ID__c == oppObj.Id)){
                    oppObj.StageName='Closed Lost';
                    olist.add(oppObj);
                    won=2;
                }

            else if((oppPrgmObj2.Program_Action__c == 'ADMT' && (oppPrgmObj2.Opportunity_ID__c == oppObj.Id)){
                oppObj.StageName='Open';
                olist.add(oppObj);
                    won=2;
            }
        }
    }
    if(won == 2){
        system.debug('enter won');
        Update olist;
    }
    }catch(Exception e){
        system.debug('message::'+e.getMessage()+'line::'+e.getLineNumber());
    }
}
 }

 
I need help in writing a trigger here. I have two objects

1) Opportunity
2) Opportunity_Programs__c

I have lookup relationship between them, opportunity is parent and Opportunity_Programs__c is child, so one opportunity can have multiple Opportunity_Programs__c.

I have Status__c field in Opportunity_Programs__c object, so if Opportunity_Programs__c records that related to particular opportunity has Status__c value as "Open" then I need to update Opportunity stage to Open, if Stage__c is "Close" then I need to update Opportuntiy stage to "Closed Lost"

Can anyone help me out in this issue here
Can anyone help me out in writing batch apex that will create or update records.I never worked on batch apex so struggling here I have two objects
1) SIS_Staging__c
2) Contact
Both objects are having same field Siscode__c, so on inserting records in SIS_Staging__c, I need to check if any contact records are having same Siscode__c or not, if yes then I need to update else I need to create Contact.
I tried below code but when I run batch apex in anonymous window then I am getting below error.
"Constructor not defined: [BatchSISstagingObject].()"
My code is below.
 
global class BatchSISstagingObject implements Database.Batchable<sObject>{
    List <SIS_Staging__c> mapSisobject = new List <SIS_Staging__c> ();
    List <Contact> contactlist1 = new List <Contact> ();
    
    global BatchSISstagingObject(List <SIS_Staging__c> sisobjectUpdate) {
        mapSisobject=sisobjectUpdate;
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return DataBase.getQueryLocator([SELECT Id, SIS_Student_ID__c
                                         FROM Contact
                                        ]);
    }
    global void execute(Database.BatchableContext BC , List <Contact> contactlist) {
        for (SIS_Staging__c acct : mapSisobject){ 
            for (Contact con : contactList){
                if (con.SIS_Student_ID__c == acct.Name){
                        contactlist1.add(new Contact(
                            Id = con.Id,
                            FirstName = acct.First_Name__c,
                            LastName = acct.Last_Name__c
                           ));
                    }
            }   
        }
        
         update contactlist1;
    } 
    global void finish(Database.BatchableContext BC){
        
    }

}

 
Can anyone help me out in writing batch apex that will create or update records. I have two objects
1) Staging_Event__c
2) Contact
Both objects are having same field Siscode__c, so on inserting records in Staging_Event__c, I need to check if any contact records are having same Siscode__c or not, if yes then I need to update else I need to create Contact.

Can anyone help me out on writing batch apex here if possible.
Hi everyone,

Can anyone help me in writing a trigger for below scenario, I have 3 objects
1) Opportunity
2) Account
3) Mutual_Plan__c

opportunity is having lookup to account,Mutualplans objects and Mutual_Plan__c has lookup to Account objects
On opportunity, on selecting account and clicks on save button, I need to populate the MutualPlan__c field on opportunity with mutual plan record id.
On opportunity I have Datefield__c, if I select this date field and account field then I need to fetch the Mutualplan record that is related to the account and populate it on Mutualplan__c field on opportunity.

Can anyone help me out in this issue here.
I worked on one trigger which will auto populate number field of all child records that were related to a parent record, for each parent record, child records auto number will start from 1.

I did achieved with below apex class and trigger, can anyone help me out in writing a generic trigger on Sobject for below apex class and trigger.

Apex class:
public class RenameActionItem {
    //code by venkat for auto number on actionitem object for a build cycle
    public static void renameActionItemRecord(List<Action_Item__c> actionItemList){
        try{
            //Set to store the buildcycleid from action item
            Set<Id> buildCycleId = new Set<Id>();
            for(Action_Item__c actionObj : actionItemList) {
                buildCycleId.add(actionObj.DCS_Build_Cycle__c);   
            }  
            
            //Fetch action items that are related to buildcycleid
            List<Action_Item__c> actionItemList2 = new List<Action_Item__c>();
            actionItemList2 = [SELECT Id FROM Action_Item__c WHERE DCS_Build_Cycle__r.Id IN :buildCycleId]; 
            
            //Fetching Action item records in descending order to catch the highest Auto Number
            List<Build_Cycle__c> buildCycleList = new List<Build_Cycle__c>();
            buildCycleList = [SELECT Name, (SELECT Id, DCS_Auto_Number__c FROM Action_Items__r order by DCS_Auto_Number__c desc limit 1) FROM Build_Cycle__c WHERE Id IN: buildCycleId];
            
            for(Build_Cycle__c bObj : buildCycleList){
                //custom label to assign first record to 1 if there are no existing records
                integer length = integer.valueOf(Label.Auto_Number);
               try{
                  //if auto number is not null for existing records then storing in inetger variable
               if(bObj.Action_Items__r[0].DCS_Auto_Number__c != null){
                    length = integer.valueOf(bObj.Action_Items__r[0].DCS_Auto_Number__c);
                    }
                }catch(exception e){
                }
                for(Action_Item__c cObj : actionItemList){
                    if(bObj.Id == cObj.DCS_Build_Cycle__c){
                            length++;
                            cObj.DCS_Auto_Number__c = length;
                    }
                }
                    
            }
       }catch(Exception e){
            System.debug('Exception in code'+e.getCause() + 'Exception in Line number'+e.getLineNumber());
       }
    }
}
trigger:
 
trigger ActionItemTrigger on Action_Item__c (before insert, after insert, after update, after delete, after undelete) {
    if(trigger.isInsert && trigger.isBefore){
        RenameActionItem.renameActionItemRecord(trigger.new);
    }
}


 
I am working on trigger which will populate a number field based on parent record.

For each parent record, child will have auto number

I have two objects which are having lookup relationship.
1) Build_Cycle__c
2) Action_Item__c
Auto number is working fine on creation but on deleting my trigger is not working.
lets say for one build cycle I have 4 action items
BUILD CYCLE:1
1) Actionitem1
2) Actionitem2
3) Actionitem3
4) Actionitem4

I tried below code which is not working if there are child existing records where auto numberfield is null rest everything is working perfectly.

my code is below, can anyone help me out in this issue.
 
public class RenameActionItem {
    public static void renameActionItemRecord(List<Action_Item__c> actionItemList){
        try{
            //Set to store the buildcycleid from action item
            Set<Id> buildCycleId = new Set<Id>();
            for(Action_Item__c actionObj : actionItemList) {
                buildCycleId.add(actionObj.DCS_Build_Cycle__c);   
            }  
            
            //Fetch action items that are related to buildcycleid
            List<Action_Item__c> actionItemList2 = new List<Action_Item__c>();
            actionItemList2 = [SELECT Id FROM Action_Item__c WHERE DCS_Build_Cycle__r.Id IN :buildCycleId]; 
            
            //Fetching Action item records in descending order to catch the highest Auto Number
            List<Build_Cycle__c> buildCycleList = new List<Build_Cycle__c>();
            buildCycleList = [SELECT Name, (SELECT Id, DCS_Auto_Number__c FROM Action_Items__r order by DCS_Auto_Number__c desc limit 1) FROM Build_Cycle__c WHERE Id IN: buildCycleId];
            
            for(Build_Cycle__c bObj : buildCycleList){
                //if existing records have DCS_Auto_Number__c == null then setting it to 1 using custom label
                integer length = integer.valueOf(Label.Auto_Number);
               try{
                    length = integer.valueOf(bObj.Action_Items__r[0].DCS_Auto_Number__c);
                }catch(exception e){
                }
                for(Action_Item__c cObj : actionItemList){
                    if(bObj.Id == cObj.DCS_Build_Cycle__c){
                            length++;
                            cObj.DCS_Auto_Number__c = length;
                    }
                }
                    
            }
       }catch(Exception e){
            System.debug('Exception in code'+e.getCause() + 'Exception in Line number'+e.getLineNumber());
       }
    }
}

 
I am working on apex class which will fetch details from Campaign Member object, once it is fetched I am looking at map size, if it is greater than zero then I am creating a record in Staging_Event_Attendee__c object.
in Campaign Member if ContactId field is not null then I am populating Staging_Event_Attendee__c.Attendant = ContactId, now same like that if LeadId is not null then I need to populate Staging_Event_Attendee__c.Lead__c = LeadId
Can anyone help me out in this issue, on Campaign Member record I can have either leadId or ContactId at time.
I need to have a condition to check whether LeadId or ContactId is not null, if leadId is not null then I need to create a new record where Staging_Event_Attendee__c.Lead__c = CampaignMap.get(Con.Barcode__c).LeadId If ContactId is not null then I need to create a new record where Staging_Event_Attendee__c.Lead__c = CampaignMap.get(Con.Barcode__c).ContactId
 
Map<Id,CampaignMember> CampaignMap = new Map<Id,CampaignMember>([select ContactId,CampaignId from CampaignMember where Id in: barcodeSet]);
        for(Staging_Event_Attendee__c con : stagingEventAttendeeList) {
            if(CampaignMap.size()>0 ){
            con.Attendant__c = CampaignMap.get(con.Barcode__c).ContactId;
            con.Campaign_ID__c = CampaignMap.get(con.Barcode__c).CampaignId;
            con.Date_Attended__c = system.now();
        }
            else{
                con.Invalid_Barcode__c = true;
                con.Date_Attended__c = system.now();
            }
        }

 
Is it possible to have a trigger to auto name child records based on Parent Record.
I have two objects which are having lookup relationship.
1) BuildCycle__c
2)ActionItem__c

Each build cycle can have multiple action items and I want to name all action items for a particular build cycle in sequence.

For example,
BUILDCYCLE Record1 has 2 action items and sequence should be
 1) ActionItem1
 2) ActionItem2
BUILDCYCLE Record1 has 3 action items and sequence should be
 1) ActionItem1
 2) ActionItem2
 3) ActionItem3

Can anyone guide me on this how to achieve
Hello Everyone,

I am working on one visualforce page where I have a text field and save button, on entering data to text field and clicking on save button, I am creating the record.

Now I want to show the newly inserted record on vf page in a table, I did created vf page and apex class but unable to show the created record on vf page.

Can anyone helps me out in this issue if possible.

Visualforce Page:
<apex:page Controller="StagingEventInsertAndShowData" lightningStylesheets="true">
    <apex:form >
        <apex:pageMessages id="pageMessages"/>
        <apex:pageBlock title="New Staging Event Attendee">
            <apex:pageBlockSection id="reRenderId">
                <apex:inputText label="Barcode" value="{!Barcode}"/>
                <apex:commandButton value="Insert" action="{!save}" reRender="reRenderId,pageBlockRecords,pageMessages"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock title="Details of Attendees" id="pageBlockRecords">
            <apex:pageBlockTable value="{!accList}" var="a">
                <apex:column headerValue="Barcode" value="{!a.Barcode__c}"/>
                <apex:column headerValue="Attendant" value="{!a.Attendant__c}"/>
                <apex:column headerValue="Campaign" value="{!a.Campaign_ID__c}"/>
                <apex:column headerValue="Email" value="{!a.Email__c}"/>
                <apex:column headerValue="Date Attended" value="{!a.Date_Attended__c}"/>
                <apex:column headerValue="Invalid Barcode" value="{!a.Invalid_Barcode__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Controller:
public class StagingEventInsertAndShowData {
    public String Barcode{get;set;}
    public List<Staging_Event_Attendee__c> accList {get;set;}

    public StagingEventInsertAndShowData(){
        getStagingRecords();
    }

    public void getStagingRecords(){
        Date todayDate = Date.today() ;
        accList=[SELECT Id,Name,Barcode__c,Attendant__c,Campaign_ID__c,Email__c,Date_Attended__c,Invalid_Barcode__c FROM Staging_Event_Attendee__c LIMIT 10];
    }

    public PageReference save() {
        if(string.isNotBlank(Barcode)){
            Staging_Event_Attendee__c ac = new Staging_Event_Attendee__c();
            ac.Barcode__c = Barcode;
            insert ac;
            this.Barcode = null;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM , 'Saved Successfully'));
            getStagingRecords();
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Barcode was left blank. Please enter a barcode'));
        }
        return null;
    }
}


 
Hello everyone,

I wrote a trigger that will create records in multiple objects and then converts it but when I insert multiple records then its showing below error.

"ContactCreationFromLead: execution of BeforeUpdate
caused by: System.ListException: List index out of bounds: 3"

My trigger is below.

 
trigger ContactCreationFromLead on Lead (After insert, before Update) {
    //trigger to create contact, relationship, affiliation records from lead.
    List<Lead> em = new List<Lead>();
    List<Contact> conInsertList = new List<Contact>();
    List<hed__Affiliation__c> affiliation = new List <hed__Affiliation__c>();
    List<hed__Relationship__c> relation = new List<hed__Relationship__c>();
    List<hed__Affiliation__c> affiliationListToBeInserted = new List<hed__Affiliation__c>();
    List<String> listEmail = new List<String>();
    List<String> listname = new List<String>();
    Set<String> otherProgramsValueSet = new Set<String>();
    if(trigger.isInsert || trigger.isUpdate){
    for (Lead em : Trigger.new) {
        if(em.Email != null){
            listEmail.add(em.Email);
        }
        if(em.What_is_your_primary_program_of_interest__c != null ){
            listname.add(em.What_is_your_primary_program_of_interest__c);
        }
        if(em.Other_Programs_of_Interest__c != null){
            otherProgramsValueSet.addAll(em.Other_Programs_of_Interest__c.split(';'));
        }
    }
    }
    //to catch the account Id that matches the lead primary program of interest
    //account name should match with primary program of interest picklist values
    List<Account> account = [SELECT Id,Name,Pardot_Program_Name__c from Account WHERE Pardot_Program_Name__c = :listname];
    string record;
    for(Account acc : account){
        record = acc.Id; 
    }
    List<Contact> cem = [SELECT Id, Email FROM Contact WHERE Email = :listEmail];
    String cemail;
    for(Contact ce : cem){
        cemail = ce.Email;
    }
    Id recordtype1 = [select Id From RecordType WHERE DeveloperName='Lead'].Id;
    Id recordtype2 = [select Id From RecordType WHERE DeveloperName='Parent'].Id;
    //code to create contact for student if form is filled by student
    for(Lead ld : Trigger.new) {
        if (ld.Email != cemail && ld.Parent_or_guardian__c == false) {
            
            Contact cnt = new Contact();           
                cnt.FirstName = ld.FirstName;
                cnt.LastName = ld.LastName;
                cnt.Email = ld.Email;
            conInsertList.add(cnt);
        }
        //code to create contacts for parent and student if form is filled by parent
        else{
            if(ld.Email != cemail && ld.Parent_or_guardian__c == true ){
                Contact cnt1 = new Contact();
                cnt1.RecordTypeId = recordtype2;
                cnt1.FirstName = ld.Parent_First_Name__c;
                cnt1.LastName = ld.Parent_Last_Name__c;
                cnt1.Email = ld.Parent_Email__c;
            conInsertList.add(cnt1);
                Contact cnt2 = new Contact();
                cnt2.RecordTypeId = recordtype1;
                cnt2.FirstName = ld.FirstName;
                cnt2.LastName = ld.LastName;
                cnt2.Email = ld.Email;
            conInsertList.add(cnt2);
            }
        }
    }
    if(conInsertList.size()>0){
        INSERT conInsertList;
        List<Id> conInsert = new List<Id>();
        //catch the inserted contact ids to create relationship record
        if(conInsertList.size()>1){
        for(Integer i = 0, s = conInsertList.size(); i < s; i += 2){
            //creates relation record by catching current student and parent record id's
            hed__Relationship__c hedrel = new hed__Relationship__c();
            hedrel.hed__Contact__c = conInsertList[i + 1].Id;
            hedrel.hed__RelatedContact__c = conInsertList[i].Id;
            hedrel.hed__Type__c = 'Parent';
            relation.add(hedrel);
            //creates affiliation record if filled by parent
            if( listname.isEmpty()==false && record != null){
            hed__Affiliation__c hedaff = new hed__Affiliation__c();
            hedaff.hed__Account__c = record;
            hedaff.hed__Contact__c = conInsertList[i + 1].Id;
            hedaff.hed__Primary__c = true;
            affiliation.add(hedaff);
            }
            //creates affiliation records for other programs multi select picklist field
            if(otherProgramsValueSet != null){
            Map<String,Id> accNamesToIdsMap = new Map<String,Id>();
            for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : otherProgramsValueSet]){
                accNamesToIdsMap.put(acc.Pardot_Program_Name__c,acc.Id);
            }
                for(Id accId : accNamesToIdsMap.values()){
                  affiliationListToBeInserted.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                           hed__Contact__c=conInsertList[i + 1].Id));
                }
            }
        }
        }
        else{
            //creates Affiliation record if filled by student only
            if(conInsertList.size()==1){
            for(Integer i = 0, s = conInsertList.size(); i < s; i += 2){
                if( listname.isEmpty()==false && record != null){
            hed__Affiliation__c hedaff = new hed__Affiliation__c();
            hedaff.hed__Account__c = record ;
            hedaff.hed__Contact__c = conInsertList[i].Id;
            hedaff.hed__Primary__c = true;
            affiliation.add(hedaff);
                }
                if(otherProgramsValueSet != null){
                Map<String,Id> accNamesToIdsMap = new Map<String,Id>();
                for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : otherProgramsValueSet]){
                    accNamesToIdsMap.put(acc.Pardot_Program_Name__c,acc.Id);
                }
                for(Id accId : accNamesToIdsMap.values()){
        affiliationListToBeInserted.add(new hed__Affiliation__c(hed__Account__c=accId,hed__Contact__c=conInsertList[i].Id));
    }
                }
        }
        }
        }
        insert relation;
        insert affiliation;
        insert affiliationListToBeInserted;
    }
    LeadStatus convertStatus = [Select MasterLabel from LeadStatus where IsConverted = true limit 1];
 
List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
    map<Id,Contact> conMap = new map<Id,Contact>();
for (Lead lead: Trigger.new) {
if (!lead.isConverted && lead.Status == 'New' ) {
Database.LeadConvert lc = new Database.LeadConvert();
String opportunityName = lead.Name;
 
            lc.setLeadId(lead.Id);
            lc.setSendNotificationEmail(false);
            lc.setDoNotCreateOpportunity(true); 
            String currentemail = lead.Email;
            List<Contact> id1 = [SELECT Id, Email,AccountId FROM Contact WHERE Email = :currentemail AND recordtype.name = 'Lead'];
                String Idcon;
                string accname123;
                 for(Contact ce1 : id1){
                          Idcon = ce1.Id;
                          accname123 = ce1.AccountId;
              }
                  lc.setContactId(Idcon);
                  lc.setAccountId(accname123);
                  lc.setConvertedStatus(convertStatus.MasterLabel);
                  leadConverts.add(lc);
            }
            }
                if (!leadConverts.isEmpty()) {
                List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
}
}


 
Is it possible to create and show created record in vf page one by one.

I have one VF Page which is having Input Field Barcode__c which is text, the moment I click save it creates record which is working perfectly.

Now I want to reset the input field to enter data to create another record but VF Page should have table below to show created records.

Can anyone help me out in this issue
<apex:page standardController="Staging_Event_Attendee__c" lightningStylesheets="true" >
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection>
                <apex:inputField value="{!Staging_Event_Attendee__c.Barcode__c }"/>
            </apex:pageBlockSection>
            <apex:pageblockButtons >
               <apex:commandButton value="save" action="{!save}"/>
           </apex:pageblockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 
On lead object, I have a trigger that will create two contacts, now I want to catch those two created Id's and create a record in Relationship__c object. On relationship object I have two fields Contact1__C and contact2__c, I want to pass two newly created contact id's after inserting in trigger to Contact1__c and Contact2__c fields in Relationship Object.

Can anyone help me out in this issue, my code is below.
 
trigger CreateContact on Lead (after insert) {
    
    List<Contact> conInsertList = new List<Contact>();
    List<npe4__Relationship__c> relation = new List<npe4__Relationship__c>();
    List<String> listEmail = new List<String>();
    
    for (Lead em : Trigger.new) {
        if(em.Email != null){
            listEmail.add(em.Email);
        }
    }
    
    List<Contact> cem = [SELECT Id, Email FROM Contact WHERE Email = :listEmail];
    String cemail;
    for(Contact ce : cem){
        cemail = ce.Email;
    }
    
    for(Lead ld : Trigger.new) {
        if (ld.Email != cemail && ld.Parent_Fill__c == false) {
            
            Contact cnt = new Contact();
            cnt.FirstName = ld.FirstName;
            cnt.LastName = ld.LastName;
            cnt.Email = ld.Email;
            conInsertList.add(cnt);
        }
        else{
            if(ld.Email != cemail && ld.Parent_Fill__c == true ){
                Contact cnt1 = new Contact();
                cnt1.FirstName = ld.Parent_First_Name__c;
                cnt1.LastName = ld.Parent_Last_Name__c;
                cnt1.Email = ld.Parent_Email__c;
                conInsertList.add(cnt1);
                Contact cnt2 = new Contact();
                cnt2.FirstName = ld.FirstName;
                cnt2.LastName = ld.LastName;
                cnt2.Email = ld.Email;
                conInsertList.add(cnt2);
            }
        }
    }
    
    if(conInsertList.size()>0){
        INSERT conInsertList;
        List<Id> conInsert = new List<Id>();
        for(Contact con : conInsertList){
            conInsert.add(con.Id);
        }
    }
}

 
 Can anyone helps me out in writing a trigger that will create a contact from lead if lead email does not exists in contact email id. 
Once lead is created, I need to check whether lead.email exists in existing contacts if not then create a new contact
I am working on one lightning component for a calendar on event object.

On single click in calendar its opening up edit page of event record creation but I just want want to do it on double click instead of single click.
Can anyone help me out in this issue please.
My code is below.
Component:
<aura:component controller="LightningCalender" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
	 <ltng:require styles="{!$Resource.Calender     + '/fullcalendar-3.9.0/fullcalendar.css'}"
                  scripts="{!join(',',
                           $Resource.Calender  + '/fullcalendar-3.9.0/lib/jquery.min.js',
                           $Resource.Calender  + '/fullcalendar-3.9.0/lib/moment.min.js',
                           $Resource.Calender  + '/fullcalendar-3.9.0/fullcalendar.js'
                           )}"
                  afterScriptsLoaded="{!c.afterScriptsLoaded}" />
    
    <ltng:require styles="/resource/calender/fullcalendar-3.9.0/fullcalendar.css"/>
    
    <aura:attribute name='Objectlist' type='Object[]'/>
    <aura:attribute name="buttonstate" type="Boolean" default="false"/>
    
     <lightning:buttonStateful
        labelWhenOff="List View"
        labelWhenOn="Grid View"
        
        state="{!v.buttonstate}" onclick="{!c.handleClick }"/>
     
        <div id="calendar" class="slds-card">
      

    </div>
    <div id="listcalendar" class="slds-card"/>
</aura:component>

.js
({
	 afterScriptsLoaded: function(cmp,evt,helper){
         
         helper.fetchCalenderEvents(cmp);
        
    },
    
     handleClick : function(component, event, helper){ 
      
         var buttonstate = component.get("v.buttonstate");
         component.set("v.buttonstate",!buttonstate);
         if(!buttonstate){
          $("#listcalendar").show();
         $("#calendar").hide();
         $('#listcalendar').fullCalendar({
        	defaultView: 'listWeek',
             listDayFormat : true,
             events : component.get("v.Objectlist")
		});
        
         }
         else{
              $("#calendar").show();
           $("#listcalendar").hide();   
             helper.fetchCalenderEvents(component);
         }
        
    },

})

Helper.js
({
	loadDataToCalendar :function(component,data){  
        //Find Current date for default date
        var d = new Date();
        var month = d.getMonth()+1;
        var day = d.getDate();
        var currentDate = d.getFullYear() + '/' +
            (month<10 ? '0' : '') + month + '/' +
            (day<10 ? '0' : '') + day;
         
        var self = this;
        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            selectable : true,
            defaultDate: currentDate,
            editable: true,
            eventLimit: true,
            events:data,
            dragScroll : true,
             droppable: true,
            weekNumbers : true,
  eventDrop: function(event, delta, revertFunc) {

    alert(event.title + " was dropped on " + event.start.format());

    if (!confirm("Are you sure about this change?")) {
      revertFunc();
    }
      else{
          var eventid = event.id;
          var eventdate = event.start.format();
          self.editEvent(component,eventid,eventdate);
      }

  },
            eventClick: function(event, jsEvent, view) {
           console.log(event.id);
              var editRecordEvent = $A.get("e.force:editRecord");
              editRecordEvent.setParams({
              "recordId": event.id
           });
           editRecordEvent.fire();
          },
            dayClick :function(date, jsEvent, view) {
              console.log(date.format());
                var datelist = date.format().toString().split('-');
             console.log(datelist[0]);
                console.log(parseInt(datelist[1])-1);
              var datetime = new Date(datelist[0],parseInt(datelist[1])-1,parseInt(datelist[2])+1,0,0,0,0);
            console.log(datetime);
             var createRecordEvent = $A.get("e.force:createRecord");
    createRecordEvent.setParams({
        "entityApiName": "Event",
        "defaultFieldValues": {
        'StartDateTime' :  datetime
        
    }
    });
    createRecordEvent.fire();
          },
            
            eventMouseover : function(event, jsEvent, view) {
            
          }
    });
    },
       
    
    formatFullCalendarData : function(component,events) {
        var josnDataArray = [];
        for(var i = 0;i < events.length;i++){
            var startdate = $A.localizationService.formatDate(events[i].StartDateTime);
            var enddate = $A.localizationService.formatDate(events[i].EndDateTime);
            josnDataArray.push({
                'title':events[i].Subject,
                'start':startdate,
                'end':enddate,
                'id':events[i].Id
            });
        }
      console.log('josnDataArray'+josnDataArray);
        return josnDataArray;
    },
     
    fetchCalenderEvents : function(component) {
         var action=component.get("c.getAllEvents");
       
         action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var data= response.getReturnValue();
               console.log(JSON.stringify(data));
                 var josnArr = this.formatFullCalendarData(component,response.getReturnValue());
                this.loadDataToCalendar(component,josnArr);
                component.set("v.Objectlist",josnArr);
           
            } else if (state === "ERROR") {
                                 
            }
        });
        
        $A.enqueueAction(action);
       
    }, 
    
    editEvent : function(component,eventid,eventdate){
         var action=component.get("c.updateEvent");
console.log(eventdate);
         action.setParams({ eventid : eventid ,
                           eventdate : eventdate});

         action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
            console.log('updated');
           
            } else if (state === "ERROR") {
                                 
            }
        });
        
        $A.enqueueAction(action);

    }
})


 
I am working on one lightning component to create a calendar but I am getting the following error when I clicked on button.
"Uncaught Action failed: c:LightningCalender$controller$handleClick [$ is not defined]".
Can anyone help me out in this issue here.
My code is below Apex Class:
 
public class LightningCalender {
      @AuraEnabled
    public static list<Event> getAllEvents(){
      list<Event> eventlist =[Select id, EndDateTime,StartDateTime,Subject from Event ] ;
      return eventlist;
    }
    
    
    @AuraEnabled
    public static void updateEvent(string eventid,string eventdate){
    system.debug(eventid);
        system.debug(eventdate);
        string eventdatelist = eventdate.replace('T',' ');
       
  system.debug(eventdatelist);
    Event e= new event(id = eventid);
    e.StartDateTime = DateTime.valueof(eventdatelist);
    update e;
   
    }

}

Component.cmp:
 
<aura:component controller="LightningCalender" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
	 <ltng:require styles="{!$Resource.Calender     + '/fullcalendar390/fullcalendar.css'}"
                  scripts="{!join(',',
                           $Resource.Calender  + '/fullcalendar390/lib/jquery.min.js',
                           $Resource.Calender  + '/fullcalendar390/lib/moment.min.js',
                           $Resource.Calender  + '/fullcalendar390/fullcalendar.js'
                           )}"
                  afterScriptsLoaded="{!c.afterScriptsLoaded}" />
    
    <ltng:require styles="/resource/calender/fullcalendar390/fullcalendar.css"/>
    
    <aura:attribute name='Objectlist' type='Object[]'/>
    <aura:attribute name="buttonstate" type="Boolean" default="false"/>
    
     <lightning:buttonStateful
        labelWhenOff="List View"
        labelWhenOn="Grid View"
        
        state="{!v.buttonstate}" onclick="{!c.handleClick }"/>
     
        <div id="calendar" class="slds-card">
      

    </div>
    <div id="listcalendar" class="slds-card"/>
</aura:component>
Controller.js:
 
({
	 afterScriptsLoaded: function(cmp,evt,helper){
         
         helper.fetchCalenderEvents(cmp);
        
    },
    
     handleClick : function(component, event, helper){ 
         var buttonstate = component.get("v.buttonstate");
         component.set("v.buttonstate",!buttonstate);
         if(!buttonstate){
          $("#listcalendar").show();
         $("#calendar").hide();
         $('#listcalendar').fullCalendar({
        	defaultView: 'listWeek',
             listDayFormat : true,
             events : component.get("v.Objectlist")
		});
         }
         else{
              $("#calendar").show();
           $("#listcalendar").hide();   
             helper.fetchCalenderEvents(component);
         }
        
    },

})
helper.js:
 
({
	loadDataToCalendar :function(component,data){  
        //Find Current date for default date
        var d = new Date();
        var month = d.getMonth()+1;
        var day = d.getDate();
        var currentDate = d.getFullYear() + '/' +
            (month<10 ? '0' : '') + month + '/' +
            (day<10 ? '0' : '') + day;
         
        var self = this;
        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            selectable : true,
            defaultDate: currentDate,
            editable: true,
            eventLimit: true,
            events:data,
            dragScroll : true,
             droppable: true,
            weekNumbers : true,
  eventDrop: function(event, delta, revertFunc) {

    alert(event.title + " was dropped on " + event.start.format());

    if (!confirm("Are you sure about this change?")) {
      revertFunc();
    }
      else{
          var eventid = event.id;
          var eventdate = event.start.format();
          self.editEvent(component,eventid,eventdate);
      }

  },
            eventClick: function(event, jsEvent, view) {
           console.log(event.id);
              var editRecordEvent = $A.get("e.force:editRecord");
              editRecordEvent.setParams({
              "recordId": event.id
           });
           editRecordEvent.fire();
          },
            dayClick :function(date, jsEvent, view) {
              console.log(date.format());
                var datelist = date.format().toString().split('-');
             console.log(datelist[0]);
                console.log(parseInt(datelist[1])-1);
              var datetime = new Date(datelist[0],parseInt(datelist[1])-1,parseInt(datelist[2])+1,0,0,0,0);
            console.log(datetime);
             var createRecordEvent = $A.get("e.force:createRecord");
    createRecordEvent.setParams({
        "entityApiName": "Event",
        "defaultFieldValues": {
        'StartDateTime' :  datetime
        
    }
    });
    createRecordEvent.fire();
          },
            
            eventMouseover : function(event, jsEvent, view) {
            
          }
    });
    },
       
    
    formatFullCalendarData : function(component,events) {
        var josnDataArray = [];
        for(var i = 0;i < events.length;i++){
            var startdate = $A.localizationService.formatDate(events[i].StartDateTime);
            var enddate = $A.localizationService.formatDate(events[i].EndDateTime);
            josnDataArray.push({
                'title':events[i].Subject,
                'start':startdate,
                'end':enddate,
                'id':events[i].Id
            });
        }
      console.log('josnDataArray'+josnDataArray);
        return josnDataArray;
    },
     
    fetchCalenderEvents : function(component) {
         var action=component.get("c.getAllEvents");
       
         action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var data= response.getReturnValue();
               console.log(JSON.stringify(data));
                 var josnArr = this.formatFullCalendarData(component,response.getReturnValue());
                this.loadDataToCalendar(component,josnArr);
                component.set("v.Objectlist",josnArr);
           
            } else if (state === "ERROR") {
                                 
            }
        });
        
        $A.enqueueAction(action);
       
    }, 
    
    editEvent : function(component,eventid,eventdate){
         var action=component.get("c.updateEvent");
console.log(eventdate);
         action.setParams({ eventid : eventid ,
                           eventdate : eventdate});

         action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
            console.log('updated');
           
            } else if (state === "ERROR") {
                                 
            }
        });
        
        $A.enqueueAction(action);

    }
})




 
I am working on creating list view button which can pass selected id's to visualforce page but some how vf page is unable to catch those selected id's.
In classis I used javascript buttons but can anyone help me out how to do this in lightning. My code is below.

Apex Class:
public with sharing class PaymentSummaryController {
    
   
    public boolean InError {get;set;}
    
    public decimal TotalAmount {get;set;}
    public decimal TotalAppliedAmount {get;set;}
    public integer TotalItems {get;set;}
    
    public List<String> selectedIds {get;set;}
   
    public PaymentSummaryController(ApexPages.StandardSetController controller) {
       
        InError=false;
        controller.setPageSize(1000); 
        
        String str = ApexPages.currentPage().getParameters().get('selectedIds');
        if(str !=null)
            selectedIds = String.escapeSingleQuotes(str).split(',');
        
        
        if (selectedIds==null || selectedIds.size()==0) {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please select at least one record.');
            ApexPages.addMessage(myMsg);
            InError=true;
        } 
        else {
            TotalAmount=0;
            TotalAppliedAmount=0;
            TotalItems=0;
            for (EXECED_Payment__c p : [select id,Amount__c,Total_Applied_Amount__c from EXECED_Payment__c where id in: selectedIds]){
                if (p.Amount__c!=null)
                    TotalAmount+=p.Amount__c;
                if (p.Total_Applied_Amount__c!=null)
                    TotalAppliedAmount+=p.Total_Applied_Amount__c;
                TotalItems++;
            }
        }
     } 
    
   
   
}
Visualforce page:
<apex:page standardController="EXECED_Payment__c" sidebar="false" showHeader="false" extensions="PaymentSummaryController" recordSetVar="payments" lightningStylesheets="true">
    
    <apex:form > 
        <apex:pagemessages />
        <apex:outputPanel rendered="{!inError}">
            <apex:commandButton action="{!Cancel}" value="Cancel"/>    
        </apex:outputPanel>
        
       
        <apex:outputpanel rendered="{!not(InError)}">
            <br/>
            <table>
                <tr>
                    <td><apex:outputtext value="Number of payments selected:"/></td>
                    <td><apex:outputtext style="font-weight:bold;" value="{!TotalItems}"/></td>
                </tr>
                <tr>
                    <td><apex:outputtext value="Total Amount:"/></td>
                    <td><apex:outputtext style="font-weight:bold;" value="{!TotalAmount}"/></td>
                </tr>
                 <tr>
                    <td><apex:outputtext value="Total Applied Amount:"/></td>
                    <td><apex:outputtext style="font-weight:bold;" value="{!TotalAppliedAmount}"/></td>
                </tr>
            </table>
            
           
          <!--  <br/><br/>
            <apex:commandButton action="{!Cancel}" value="Return"/>      -->
        </apex:outputpanel>
       
    </apex:form>
</apex:page>


 
Hello Everyone, I am working on one lightning component where I need to create a record using quick action.
I have two objects
1) Custom_Program_Course_junction__c
2) EXECED_Event_Class__c
On Custom_Program_Course_junction__c object, I need to have a quick action from which I should create a record in EXECED_Event_Class__c.
Since EXECED_Event_Class__c does not have a look up to Custom_Program_Course_junction__c object, I decided to create a lightning component and call it using quick action.
But some how my component is not working, I need to populate EXECED_Event_Class__c fields with Custom_Program_Course_junction__c fields.
Can anyone help me out in this issue. My code is below.

Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="Custom_Program_Course_junction__c" type="Object" />
    <aura:attribute name="simpleCustom_Program_Course_junction__c" type="Object" />
    <aura:attribute name="Custom_Program_Course_junction__cError" type="String" />
    <force:recordData aura:id="Custom_Program_Course_junction__cRecordLoader"
                      recordId="{!v.recordId}"
                      fields="Name,Course__c"
                      targetRecord="{!v.Custom_Program_Course_junction__c}"
                      targetFields="{!v.simpleCustom_Program_Course_junction__c}"
                      targetError="{!v.Custom_Program_Course_junction__cError}" />
    <aura:attribute name="newEXECED_Event_Class__c" type="Object" access="private" />
    <aura:attribute name="simpleNewEXECED_Event_Class__c" type="Object" access="private" />
    <aura:attribute name="newEXECED_Event_Class__cError" type="String" access="private" />
    <force:recordData aura:id="EXECED_Event_Class__cRecordCreator"
                     layoutType="FULL"
                     targetRecord="{!v.newEXECED_Event_Class__c}"
                     targetFields="{!v.simpleNewEXECED_Event_Class__c}"
                     targetError="{!v.newEXECED_Event_Class__cError}" />

    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />   
    <div class="slds-modal__header">
        <p class="slds-text-heading--label">{!v.simpleCustom_Program_Course_junction__c.Name}</p>
        <h1 class="slds-page-header__title slds-m-right--small slds-truncate slds-align-left">Create new Class</h1>
    </div>
    <aura:if isTrue="{!not(empty(v.Custom_Program_Course_junction__cError))}">
    	<div class="recordError">
        	<ui:message title="Error" severity="error" closable="true">
            	{!v.Custom_Program_Course_junction__cError}
            </ui:message>
        </div>
    </aura:if>
    <aura:if isTrue="{!not(empty(v.Custom_Program_Course_junction__cError))}">
    	<div class="recordError">
        	<ui:message title="Error" severity="error" closable="true">
            	{!v.newEXECED_Event_Class__cError}
            </ui:message>
        </div>
    </aura:if>
    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
    	<lightning:input aura:id="EXECED_Event_Class__cField" name="Start__c" label="Start" type="Date"
                     	value="{!v.simpleNewEXECED_Event_Class__c.Start__c}" required="true" />
    
        <lightning:input aura:id="EXECED_Event_Class__cField" name="End__c" label="End" type="Date"
                         value="{!v.simpleNewEXECED_Event_Class__c.End__c}" required="true" />
    </div>
    <div class="slds-modal__footer">
        <lightning:button class="slds-button_neutral" label="Save" onclick="{!c.handleSaveEXECED_Event_Class__c}"/>
        <lightning:button class="slds-button_brand" label="Cancel" onclick="{!c.cancel}"/>
    </div>
</aura:component>
.JS:
({
	doInit : function(component, event, helper) {
        component.find("EXECED_Event_Class__cRecordCreator").getNewRecord(
        	"EXECED_Event_Class__c",
            null,
            false,
            $A.getCallback(function(){
                var rec = component.get("v.newEXECED_Event_Class__c");
                var error = component.get("v.newEXECED_Event_Class__cError");
                if(error || (rec === null)){
                    console.log("Error initializing record template: " + error);
                }else{
                    console.log("Record template initialized" + rec.sobjectType);
                }
            })
        );
	},

    handleSaveEXECED_Event_Class__c : function(component, event, helper){
        component.set("v.simpleNewEXECED_Event_Class__c.Course__c", component.get("v.simpleCustom_Program_Course_junction__c.Course__c"));
        component.set("v.simpleNewEXECED_Event_Class__c.Name", component.get("v.simpleCustom_Program_Course_junction__c.Name"));
        component.find("EXECED_Event_Class__cRecordCreator").saveRecord(function(saveResult){
            if(saveResult.state === "SUCCESS" || saveResult.state === "DRAFT"){
                var resultsToast = $A.get("e.force:showToast");
                resultsToast.setParams({
                    "title" : "Class saved",
                    "message" : "The new Class was created",
                    "type" : "success"
                });

                $A.get("e.force:closeQuickAction").fire();
                resultsToast.fire();
                $A.get("e.force:refreshView").fire();
            }else if(saveResult.state === "INCOMPLETE"){
                console.log("User is offline, device doesn't support drafts.");
            }else if(saveResult.state === "ERROR"){
                console.log("Problem saving contact, error" + JSON.stringify(saveResult.error));
            }else{
                console.log("Unknown problem, state: " + saveResult.state + ', error: ' + JSON.stringify(saveResult.error));
            }
        });
    },

    cancel : function(component, event, helper){
        $A.get("e.force:closeQuickAction").fire();
    }


})


 
I am working on one trigger where I need to concatinate two fields and populate in third field.
On hed__Course_Offering__c object, I want to concatinate hed__Course__c and hed__Term__c field and need to populate on Name field. I tried below trigger.
trigger ModuleOfferingName on hed__Course_Offering__c (before insert) {
    for(hed__Course_Offering__c con : trigger.New){
        string nameupd = '';
        nameupd += con.hed__Course__r.Name +','+ con.hed__Term__r.Name ;
        con.Name = nameupd;
}
}
The issue is its populating but the hed__Course__c and hed__Term__c are lookup fields so its populating ids but I want names to populate. Can anyone help me out in this issue please.
 
I need help in writing a trigger, I have two objects

1) Opportunity
2) Opportunity_ Program__c

both are having lookup relationship, Opportunity is Parent and Opportunity Program is child.

Opportunity program has Status field.

I need to write a trigger on Opportunity Program object, for a given Opportunity if any of the child records contains status as "MATR" then Opportunity.StageName = 'Closed Won', if any of the child record for a given opportunity does not contain "MATR" then Opportunity.StageName = 'Closed Lost'

Can anyone helps me out in this issue please.
I need help in writing a trigger, I have two objects

1) Opportunity
2) Opportunity_ Program__c

both are having lookup relationship, Opportunity is Parent and Opportunity Program is child.

Opportunity program has Status field.

I need to write a trigger on Opportunity Program object, for a given Opportunity if any of the child records contains status as "MATR" then Opportunity.StageName = 'Closed Won', if any of the child record for a given opportunity does not contain "MATR" then Opportunity.StageName = 'Closed Lost'

Can anyone helps me out in this issue please.
Hello Guys

i am new to the trigges and apex development, so here  is my requirement - There is checkbox Called "Private__c" in account object
Once locked, if a new Lead is created with this Private Locked Account which already has a Allocated Owner, then a new Contact should be created for this Account under the allocated Account owner name. Lead will not be created. 

And If a new lead is added without a Private Account checkbox being checked then allow the Lead to be created with Lead creator as the Lead owner. 

so far i have tried to design a trigger, but its not meeting up my goal
 
trigger AutoConvertLeadAccount on Lead (after insert) {
    Set<String> leademails = new Set<String>();
    List<Lead> newLeads = new List<Lead>();

    // Get all the new leads
    for(Lead l : system.trigger.new){
        newLeads.add(l);
        leademails.add(l.email);
    }

    /* Make some maps of account and email addresses */
    List<Account> AccountList = [select Id, Website, OwnerId from Account where Website IN: leademails];
    Map<ID, String> peAccounts = new Map<ID, String>();
    Map<ID, ID> peAccountsOwner = new Map<ID, ID>();

if(AccountList.size()>0){
    // Generic map for preventing loss of ids
    for(Account a : AccountList){
        peAccounts.put(a.id, a.Website);
        peAccountsOwner.put(a.id, a.OwnerId);
    }

    // We will need this to get the id from the email address
    Map<String, ID> peAccountsFlipped = new Map<String, ID>();
    for(ID i : peAccounts.keyset()){
        peAccountsFlipped.put(peAccounts.get(i), i);
    }

    /* System Conversion Requirements */
    leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
    List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
    Database.LeadConvert lc = new Database.LeadConvert();

    /* Configuring Payload */    
    for (Lead nl : newleads) {
        lc = new Database.LeadConvert();
        lc.setLeadId(nl.id);
        lc.setOverwriteLeadSource(false);
        lc.setConvertedStatus(convertStatus.MasterLabel);

        // Check to see if account already exists
        if(!peAccounts.isEmpty()){
            if(peAccountsFlipped.get(nl.email)!=null){
                lc.setAccountId(peAccountsFlipped.get(nl.email));
                lc.setOwnerId(peAccountsOwner.get(peAccountsFlipped.get(nl.email)));
                lc.setDoNotCreateOpportunity(true);
            }    
        } else {
            // In the event an account doesn't exist
            lc.setOwnerId(nl.OwnerId);
            lc.setDoNotCreateOpportunity(false);
            lc.setOpportunityName(nl.Name);
        }
        leadConverts.add(lc);
    }

    // Fire Payload
    Database.LeadConvertResult[] lcr = Database.convertLead(leadConverts);
    System.debug(LoggingLevel.INFO, lcr);
 }
}

 
I need help in writing a trigger here. I have two objects

1) Opportunity
2) Opportunity_Programs__c

I have lookup relationship between them, opportunity is parent and Opportunity_Programs__c is child, so one opportunity can have multiple Opportunity_Programs__c.

I have Status__c field in Opportunity_Programs__c object, so if Opportunity_Programs__c records that related to particular opportunity has Status__c value as "Open" then I need to update Opportunity stage to Open, if Stage__c is "Close" then I need to update Opportuntiy stage to "Closed Lost"

Can anyone help me out in this issue here
Can anyone help me out in writing batch apex that will create or update records.I never worked on batch apex so struggling here I have two objects
1) SIS_Staging__c
2) Contact
Both objects are having same field Siscode__c, so on inserting records in SIS_Staging__c, I need to check if any contact records are having same Siscode__c or not, if yes then I need to update else I need to create Contact.
I tried below code but when I run batch apex in anonymous window then I am getting below error.
"Constructor not defined: [BatchSISstagingObject].()"
My code is below.
 
global class BatchSISstagingObject implements Database.Batchable<sObject>{
    List <SIS_Staging__c> mapSisobject = new List <SIS_Staging__c> ();
    List <Contact> contactlist1 = new List <Contact> ();
    
    global BatchSISstagingObject(List <SIS_Staging__c> sisobjectUpdate) {
        mapSisobject=sisobjectUpdate;
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return DataBase.getQueryLocator([SELECT Id, SIS_Student_ID__c
                                         FROM Contact
                                        ]);
    }
    global void execute(Database.BatchableContext BC , List <Contact> contactlist) {
        for (SIS_Staging__c acct : mapSisobject){ 
            for (Contact con : contactList){
                if (con.SIS_Student_ID__c == acct.Name){
                        contactlist1.add(new Contact(
                            Id = con.Id,
                            FirstName = acct.First_Name__c,
                            LastName = acct.Last_Name__c
                           ));
                    }
            }   
        }
        
         update contactlist1;
    } 
    global void finish(Database.BatchableContext BC){
        
    }

}

 
Good Morning all,
I'm trying to get familiar with the Sales Cloud, I've a doubt regarding the Order Object - We've Account Name and Contract Name fields on Order object. I just want to know how does Account Name field get generated automatically  if I select Contract Name. [Order has a lookup with Account n Contract]
 
Can anyone tell me how does this work ?

Thanks in advance,
Harsha Deepthi