function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Viviana Hernández PeñaViviana Hernández Peña 

Sub Query Class Apex

I have the following code where you are sending the payments of the invoices to all contacts associated with the account, is there any way to bring the contact that is associated with the invoice ???


                List<Contact> listofContacts = [SELECT Email FROM Contact where AccountId = :accId and Email != null];
                String[] toRecipients = new List<String> ();

                Integer count = 0;
                for (Contact oneContact : listofContacts)
                {
                    if (count > 0)
                    toRecipients.add(oneContact.Email);
                    count++;
                }

                Id orgWide = [SELECT Id FROM OrgWideEmailAddress limit 1].id;
Rameshwar gaurRameshwar gaur
Please post full codes whenever you need help.
From your code i didn't get what you want to achieve 
but If you are genrating invoice from Orders then you can use this SOQL Query.
Order Contact_Order = [SELECT CustomerAuthorizedById FROM Order WHERE AccountId = :accId];
System.debug('Contact Connected To '+O.Id+' Is '+Contact_Order.CustomerAuthorizedById );
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

 
Viviana Hernández PeñaViviana Hernández Peña
this is the complete code:


I do not want to bring all the contacts associated with the account for sending email, I want it to be sent only to the contact associated with the contact to the invoice.

                //send email 
                //<messaging:emailTemplate 
                //subject="{!Relatedto.fw1__Payment_Receipt_Email_Subject__c}" recipientType="Contact" relatedToType="fw1__Payment__c">

                //String c = ('SELECT Id, Name, Email FROM Contact where AccountId = \''+ accId +'\' and Email != null and Name != null');
                //List<Contact> listofContacts = [SELECT Id, Name, Email FROM Contact where AccountId = :accId and Email != null and Name != null];
                List<fw1__Invoice__c> listofContacts2 =  [SELECT Id FROM fw1__Invoice__c where Email_Contacto__c != null];

                List<Contact> listofContacts =  [SELECT Email FROM Contact where AccountId = :accId and Email != null];
                String[] toRecipients = new List<String> ();

                Integer count = 0;
                for (Contact oneContact : listofContacts)
                {
                    if (count > 0)
                    toRecipients.add(oneContact.Email);
                    count++;
                }

                Id orgWide = [SELECT Id FROM OrgWideEmailAddress limit 1].id;

                for (fw1__Payment__c payment : paymentList)
                {
                    //String[] toRecipients = listofContacts;
                    String templateApiName = 'Standard_Payment_Receipt_v3_9';
                    ID targetObjId = listofContacts[0].Id;
                    ID whatId = payment.id;
                    ID orgWideEmailId = orgWide;
                    Boolean saveAsActivity = true;

                    sendTemplatedEmail(toRecipients, templateApiName, targetObjId, whatId, orgWideEmailId, saveAsActivity);

                }

            } catch(DmlException e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
            } catch(Exception e) {
                System.debug('An exception occurred: ' + e.getMessage() + ' Stacktrace: ' + e.getStackTraceString());
            }
        }
    }



    //  -------------------------------------------------------------------------
    //  HELPER method: sendTemplatedEmail
    //  -------------------------------------------------------------------------
    public void sendTemplatedEmail(String[] toRecipients, String templateApiName, ID targetObjId, Id whatId, ID orgWideEmailId, Boolean saveAsActivity) {
        //  templateId   must be ID of an Email template
        //  targetObjId must be a Contact, User, Lead Id -- also used in merge fields of template recipient.xxxx
        //  whatId    must be an SObject that is used in the merge fields of the template relatedTo.xxxx
        //  fromId    if non null, use current user, otherwise, use this ID (most likely an org wide no reply id)
        //  bcc      not permitted when using templates

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        Id templateId;
        try { templateId = [select id, name from EmailTemplate where developername = :templateApiName].id; }
        catch(Exception e) {
            System.debug('[U-03] Unable to locate EmailTemplate using name: ' + templateApiName +
                         ' refer to Setup | Communications Templates ' + templateApiName);
        }

        email.setToAddresses(toRecipients);
        //email.setCcAddresses(ccRecipients);
        email.setTargetObjectId(targetObjId);
        email.setWhatId(whatId);
        email.setorgWideEmailAddressId(orgWideEmailId);
        email.setTemplateId(templateId);
        email.setSaveAsActivity(saveAsActivity); // save email as activity on the targetObjId (i.e. Contact). Note activity can't be saved on Users

        System.debug(LoggingLevel.INFO, '** entered sendTemplatedEmail, to:' + toRecipients + ' templateId:' + templateId + ' tagetObjId:' + targetObjId +
                     ' whatId:' + whatId + ' orgWideEmailId: ' + orgWideEmailId);
        try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
            return;
        }
        catch(EmailException e) { System.debug('[U-02] sendTemplatedEmail error. ' + e.getMessage()); }

    }
}
 
Rameshwar gaurRameshwar gaur
Is invoice is your custom object?
If it's your custom object are you make a lookup field for contact object?
Viviana Hernández PeñaViviana Hernández Peña

Hello Rameshwar gaur,
he object is personalized and has a relation to a search field to the contact.

User-added imageUser-added image