<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>apex &#8211; Hamza Siddiqui</title>
	<atom:link href="https://www.mhamzas.com/blog/tag/apex/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mhamzas.com</link>
	<description>4x Salesforce MVP &#124; 26x Certified &#124; Salesforce App &#38; System Architect</description>
	<lastBuildDate>Mon, 17 Apr 2023 07:23:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<site xmlns="com-wordpress:feed-additions:1">233526040</site>	<item>
		<title>Field Utils Helper Class</title>
		<link>https://www.mhamzas.com/blog/2023/04/17/field-utils-helper-class/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=field-utils-helper-class</link>
					<comments>https://www.mhamzas.com/blog/2023/04/17/field-utils-helper-class/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Mon, 17 Apr 2023 07:23:29 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[util]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3526</guid>

					<description><![CDATA[I was exploring the internet and found a wonderful utility class having methods to get information about fields and objects, including schema information by Kevin Antonioli posted on Playground App. Although I do have my own version but I prefer this one <br /><a href="https://www.mhamzas.com/blog/2023/04/17/field-utils-helper-class/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>I was exploring the internet and found a wonderful utility class having methods to get information about fields and objects, including schema information by <a href="https://www.linkedin.com/in/kevin-antonioli-b075b340/" target="_blank" rel="noreferrer noopener nofollow">Kevin Antonioli</a> posted on <a href="https://live.playg.app/play/field-utils" target="_blank" rel="noreferrer noopener">Playground App</a>. Although I do have my own version but I prefer this one as this has probably more methods and documented :p</p>



<h3 class="wp-block-heading">Examples:</h3>



<p>Get the describe for an object without ever running an expensive Schema.globalDescribe() call</p>



<pre class="wp-block-preformatted">// using object api name string param:
Schema.DescribeSObjectResult accountDescribe = FieldUtils.getDynamicDescribe('Account');

// using SObject record param:
Schema.DescribeSObjectResult accountDescribe = FieldUtils.getDynamicDescribe(accountRecord);
</pre>



<p>Get the field map for an object without ever running an expensive Schema.globalDescribe() call</p>



<pre class="wp-block-preformatted">// using object api name string param:
Map&lt;String, Schema.SObjectField&gt; accountFieldMap = FieldUtils.getFieldMap('Account'); 

// using SObject record param:
Map&lt;String, Schema.SObjectField&gt; accountFieldMap = FieldUtils.getFieldMap(accountRecord); 
</pre>



<p>Get the properties for a particular field set:</p>



<pre class="wp-block-preformatted">List&lt;Schema.FieldSetMember&gt; accountFieldSet = FieldUtils.readFieldSet( 'My_Field_Set',  'Account');
</pre>



<p>Get just the api names of the fields belonging to a particular field set:</p>



<pre class="wp-block-preformatted">List&lt;Schema.FieldSetMember&gt; acctFieldSetApiNames = FieldUtils.getFieldSetFieldAPINames( 'My_Field_Set',  'Account');
</pre>



<p>Determine if SObjectField is createable using object and field string params:</p>



<pre class="wp-block-preformatted">Boolean isCreateable = FieldUtils.isFieldCreateable('Account', 'Industry');
</pre>



<p>Determine if SObjectField is accessible using object and field string params:</p>



<pre class="wp-block-preformatted">Boolean isAccessible = FieldUtils.isFieldAccessible('Account', 'Industry');
</pre>



<p>Determine if SObjectField is updateable using object and field string params:</p>



<pre class="wp-block-preformatted">Boolean isUpdateable = FieldUtils.isFieldUpdateable('Account', 'Industry');
</pre>



<p>Get the field type for an SObject field using object and field string params:</p>



<pre class="wp-block-preformatted">String industryFieldType = FieldUtils.getFieldType('Account', 'Industry'); //PICKLIST
</pre>



<p>Get a list of all field api names for a given object:</p>



<pre class="wp-block-preformatted">List&lt;String&gt; acctFields = FieldUtils.getAllFieldsForSobj('Account');
</pre>



<p>Get a list of all createable fields for a given object:</p>



<pre class="wp-block-preformatted">List&lt;String&gt; acctCreateableFields = FieldUtils.getCreateableFields('Account');
</pre>



<p>Get a list of all accessible fields for a given object:</p>



<pre class="wp-block-preformatted">List&lt;String&gt; acctAccessibleFields = FieldUtils.getAccessibleFields('Account');
</pre>



<p>Get a list of all updateable fields for a given object:</p>



<pre class="wp-block-preformatted">List&lt;String&gt; acctUpdateableFields = FieldUtils.getUpdateableFields('Account');
</pre>



<p>Get a list of all fields (except within a specified blacklist) for a given object:</p>



<pre class="wp-block-preformatted">List&lt;String&gt; acctFieldsExceptBlacklist = FieldUtils.getAllFieldsExceptBlacklist('Account', new List&lt;String&gt;{'PersonPronouns', 'PersonGenderIdentity'});
</pre>



<p>Parse last object from field path:</p>



<pre class="wp-block-preformatted">// sample data:
Contact contact = [SELECT Id, Name, Account.Owner.Name FROM Contact LIMIT 1];

// dynamically get the last object within a multi-level path (in this case, User/Owner):
SObject deepestRecordFromPath = ApexUtils.parseLastSubObjectFromPath(contact, 'Account.Owner.Name'); // get the user record
</pre>



<p>Parse value from field path:</p>



<pre class="wp-block-preformatted">// sample data:
Contact contact = [SELECT Id, Name, Account.Owner.Name FROM Contact LIMIT 1];

// dynamically get the field value as an Object for a multi-level path:
Object fieldValueObj = ApexUtils.parseValueFromFieldPath(contact, 'Account.Owner.Name'); // get the value stored in the Name field</pre>



<h2 class="wp-block-heading">Source</h2>



<script src="https://gist.github.com/mhamzas/925a84cabcf8fdc4736ca93e334471d5.js"></script>



<p><strong>Credits</strong>: <a href="https://www.linkedin.com/in/kevin-antonioli-b075b340/" target="_blank" rel="noreferrer noopener nofollow">Kevin Antonioli</a> </p>



<p><strong>Source</strong>: https://live.playg.app/play/field-utils</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2023/04/17/field-utils-helper-class/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3526</post-id>	</item>
		<item>
		<title>Get all Parent and child objects related to the current object</title>
		<link>https://www.mhamzas.com/blog/2022/12/15/get-all-parent-and-child-objects-related-to-the-current-object/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=get-all-parent-and-child-objects-related-to-the-current-object</link>
					<comments>https://www.mhamzas.com/blog/2022/12/15/get-all-parent-and-child-objects-related-to-the-current-object/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Thu, 15 Dec 2022 11:01:24 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[platform]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3497</guid>

					<description><![CDATA[Many times you have to find the related objects either you do it the hardcode way or another. Here I am sharing an example of how you can dynamically get the Related either Parent or Child. The below examples are for the <br /><a href="https://www.mhamzas.com/blog/2022/12/15/get-all-parent-and-child-objects-related-to-the-current-object/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>Many times you have to find the related objects either you do it the hardcode way or another. Here I am sharing an example of how you can dynamically get the Related either Parent or Child.</p>



<p>The below examples are for the standard &#8220;Account&#8221; object. However, this will work for any other standard or custom object &#8211; don&#8217;t forget to add __c for the custom objects.</p>



<h2 class="wp-block-heading">Get All Parent objects.</h2>



<pre class="wp-block-code"><code>for(Schema.SobjectField strFld: Account.SobjectType.getDescribe().fields.getMap().Values())
{
    if(strFld.getDescribe().getType() == Schema.DisplayType.REFERENCE)
    {
        system.debug('==parent object='+strFld.getDescribe().getReferenceTo());
    } 
}
</code></pre>



<h2 class="wp-block-heading">Get All Child objects.</h2>



<pre class="wp-block-code"><code>Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship cr: R.getChildRelationships()) 
{
  system.debug('====child object==='+cr.getChildSObject());
}
</code></pre>



<h2 class="wp-block-heading">Getting Relationship Names</h2>



<pre class="wp-block-code"><code>Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship cr: R.getChildRelationships()) 
{
  system.debug('====child object relation Name==='+cr.getRelationshipName());
}
</code></pre>



<p>Source: https://salesforce.stackexchange.com/questions/117050/get-all-parent-and-child-objects-related-to-the-current-object<br>Credit: https://salesforce.stackexchange.com/users/18731/ratan-paul</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2022/12/15/get-all-parent-and-child-objects-related-to-the-current-object/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3497</post-id>	</item>
		<item>
		<title>Troubleshooting Apex heap size</title>
		<link>https://www.mhamzas.com/blog/2022/06/27/troubleshooting-apex-heap-size/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=troubleshooting-apex-heap-size</link>
					<comments>https://www.mhamzas.com/blog/2022/06/27/troubleshooting-apex-heap-size/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Mon, 27 Jun 2022 13:35:09 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3441</guid>

					<description><![CDATA[Salesforce enforces an Apex Heap Size Limit of 6MB for synchronous transactions and 12MB for asynchronous transactions and this is a governor limit which means it is a hard limit and cannot be modified or relaxed. The &#8220;Apex heap size too large&#8221; <br /><a href="https://www.mhamzas.com/blog/2022/06/27/troubleshooting-apex-heap-size/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>Salesforce enforces an Apex Heap Size Limit of 6MB for synchronous transactions and 12MB for asynchronous transactions and this is a governor limit which means it is a hard limit and cannot be modified or relaxed.</p>



<p>The &#8220;Apex heap size too large&#8221; error occurs when too much data is being stored in memory during processing. The limit depends on the type of execution (E.g., synchronous vs asynchronous calls) and current value. </p>



<p>Best practices for running within the Apex heap size,</p>



<ul class="wp-block-list"><li>Don&#8217;t use class level variables to store a large amount of data.</li><li>Utilize SOQL For Loops to iterate and process data from large queries.</li><li>Construct methods and loops that allow variables to go out of scope as soon as they are no longer needed.</li></ul>



<p>Ref: <a href="https://help.salesforce.com/articleView?id=Apex-Heap-Size-Best-Practices&amp;language=en_US&amp;type=1">https://help.salesforce.com/articleView?id=Apex-Heap-Size-Best-Practices&amp;language=en_US&amp;type=1</a></p>



<p>In order to resolve Heap size error issue, you need to revamp the code following the above best practices so that you don&#8217;t hit these limits.</p>



<p>Please refer to the following link which discusses different strategies to manage the heap size.</p>



<ul class="wp-block-list"><li><a href="http://blog.jeffdouglas.com/2010/08/16/managing-the-heap-in-salesforce-com/">http://blog.jeffdouglas.com/2010/08/16/managing-the-heap-in-salesforce-com/</a></li><li><a href="https://success.salesforce.com/questionDetail?qid=a1X30000000ddWJEAY">https://success.salesforce.com/questionDetail?qid=a1X30000000ddWJEAY</a></li></ul>



<p>Troubleshooting approach to fix heap size error,</p>



<p>1) Add the following debug method to the affected class:</p>



<pre class="wp-block-code"><code>void checkHeapSize(String tag) {
system.debug(tag + ': Heap size is ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());
}</code></pre>



<p>2a) Call the method at various points in the code using a &#8220;tag&#8221; parameter so that you know where it&#8217;s called in the code. For example: <strong>checkHeapSize(&#8216;constructor1&#8217;);</strong></p>



<p>2b) In order to check the heap limit, put the check in the loop and then run the check every 1000th iteration. This is done by adding a local variable called &#8220;i&#8221; (i.e. &#8220;integer i;&#8221;), increment it for each iteration, and then running the following code: </p>



<pre class="wp-block-code"><code>if (math.mod(i, 1000) == 0) } { call the method }.</code></pre>



<p>3) Review the debug logs to find the heap size to see if it&#8217;s exceeding the limit. For issues with scheduled batches, testing in the Developer Console will run code synchronously and show the limit as 6 MB but the heap size limit for scheduled batches is the asynchronous limit of 12MB.</p>



<p>4) If heap size doesn&#8217;t exceed the limit, repeat steps 1-3. If the limit is exceeded, the debug logs should point out the problematic section of code that will need to be fixed.</p>



<p></p>



<p>Source: https://developer.salesforce.com/forums/?id=9062I000000DHPCQA4<br>Credit: Sweta (Her profile is not available anymore &#8211; 404 error)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2022/06/27/troubleshooting-apex-heap-size/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3441</post-id>	</item>
		<item>
		<title>Apex Data Chunking</title>
		<link>https://www.mhamzas.com/blog/2021/09/03/apex-data-chunking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=apex-data-chunking</link>
					<comments>https://www.mhamzas.com/blog/2021/09/03/apex-data-chunking/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Fri, 03 Sep 2021 14:13:20 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[data]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3259</guid>

					<description><![CDATA[When I execute the following code You receive the following error:Execution Failed. System.TypeException: Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking. but after execution of this script: everything goes smoothly. This is because <br /><a href="https://www.mhamzas.com/blog/2021/09/03/apex-data-chunking/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>When I execute the following code</p>



<pre class="wp-block-code"><code>List&lt;SObject> toSave = new List&lt;SObject>();
for(integer i = 0; i &lt; 100; i++ )
{
    BB_A__c bba = new BB_A__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 5)
    {
        bba.x__c = 'bartek';
    }
    toSave.add(bba);
     
    BB_B__c bbb = new BB_B__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 7)
    {
        bba.y__c = 'bartek';
    }
    toSave.add(bbb);    
}
insert toSave;</code></pre>



<p>You receive the following error:<br><em>Execution Failed. System.TypeException: Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking.</em></p>



<p>but after execution of this script:</p>



<pre class="wp-block-code"><code>List&lt;SObject> toSave = new List&lt;SObject>();
for(integer i = 0; i &lt; 100; i++ )
{
    BB_A__c bba = new BB_A__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 5)
    {
        bba.x__c = 'bartek';
    }
    toSave.add(bba);
}
 
for(integer i = 0; i &lt; 100; i++ )
{   
    BB_B__c bbb = new BB_B__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 7)
    {
        bbb.y__c = 'bartek';
    }
    toSave.add(bbb);
     
}
insert toSave;</code></pre>



<p>everything goes smoothly. This is because when you insert a list with multiple objects, the data type cannot change more than 10 times. Do not ask why, this is SALESFORCE.<br>But there is a simple solution:<br>You have to sort the list that you want to add. Because the standard List.sort() method sorts collection by SObject labels then you will have all objects grouped by SObject label that equals to sobject type:). Here is a working example:</p>



<pre class="wp-block-code"><code>List&lt;SObject> toSave = new List&lt;SObject>();
for(integer i = 0; i &lt; 100; i++ )
{
    BB_A__c bba = new BB_A__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 5)
    {
        bba.x__c = 'bartek';
    }
    toSave.add(bba);
     
    BB_B__c bbb = new BB_B__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 7)
    {
        bba.y__c = 'bartek';
    }
    toSave.add(bbb);
     
}
 
toSave.sort(); // &lt;-- this line fixes our issue:):):)
 
insert toSave;</code></pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Here is the method I found one of the answers from the Salesforce <a href="https://developer.salesforce.com/forums/?id=906F000000090nUIAQ" target="_blank" rel="noreferrer noopener">developers community</a> by Julien Castelluci</p>



<script src="https://gist.github.com/mhamzas/ac7480e9058ac7b06281ef6f5a60526f.js"></script>



<p><strong>Source</strong>: <br>https://bartoszborowiec.wordpress.com/2014/06/15/execution-failed-system-typeexception-cannot-have-more-than-10-chunks-in-a-single-operation-please-rearrange-the-data-to-reduce-chunking/</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/09/03/apex-data-chunking/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3259</post-id>	</item>
		<item>
		<title>Send Email with Attachments in Salesforce Apex</title>
		<link>https://www.mhamzas.com/blog/2021/09/03/send-email-with-attachments-in-salesforce-apex/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=send-email-with-attachments-in-salesforce-apex</link>
					<comments>https://www.mhamzas.com/blog/2021/09/03/send-email-with-attachments-in-salesforce-apex/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Fri, 03 Sep 2021 11:55:45 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[email]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3257</guid>

					<description><![CDATA[In this article, I would like to talk about one specific real-world scenario. Recently, we have been working on the investment platform build on top of Salesforce for one of our clients. At some point, we had an idea of collecting leads <br /><a href="https://www.mhamzas.com/blog/2021/09/03/send-email-with-attachments-in-salesforce-apex/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>In this article, I would like to talk about one specific real-world scenario. Recently, we have been working on the investment platform build on top of Salesforce for one of our clients.</p>



<p>At some point, we had an idea of collecting leads by sending out the investor materials, such as company marketing presentations for an exchange to their contact information.</p>



<p>This task required us to perform the following actions:</p>



<ol class="wp-block-list"><li>Create the Lead object if he does not exist yet</li><li>Query all the specified attachments and send them via email to the Lead to make sure that the email is correct</li><li>Save sent email as the Lead activity for the sales team</li><li>Subscribe Lead to the MailChimp list if he checked the GDPR field</li><li>Remember Lead’s browser so that he could download attachments without filling the form in future to improve the user experience</li></ol>



<p>Of course, this is quite a lot of things to do to make the life of marketers and sales team easier and automate the process. But I would like to focus on the second step and show how you could send out the email with dynamic attachments from the Apex class.</p>



<p><strong>TL;DR;</strong></p>



<p>Please, find the final version of the code at the end of the post.</p>



<h2 class="wp-block-heading">Single Email Message</h2>



<p>Let’s pretend that we have an Apex controller for downloading attachments. It could be the REST API endpoint or just the regular class for the sake of simplicity.</p>



<pre class="wp-block-preformatted">global class DownloadAttachments {
 /**
  * @param {String} startupId The Id of the target startup object, which files we should attach to the email
  * @param {String} emailAddress The email address of the recipient
  */
  global static void download(String startupId, String emailAddress) {
    ...
  }
}</pre>



<p>In this case, to send the email, we will use the&nbsp;<a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm">Messaging.SingleEmailMessage</a>&nbsp;class.</p>



<p>It has the method called setFileAttachments which we will use attach the files we want to send along.</p>



<p>This method accepts the list of Messaging.EmailFileAttachment objects.</p>



<p>Finally, each of this attachment objects should have the name, body, and content type to correctly display it in the email.</p>



<p>To begin with, let’s create the new instance of the SingleEmailMessage class and set the recipient address.</p>



<pre class="wp-block-preformatted">Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

message.setToAddresses(new String[] { emailAddress });</pre>



<p>Then, the exciting part begins. Salesforce allows us to do a lot of things with the messaging class.</p>



<h2 class="wp-block-heading">Email File Attachments</h2>



<p>Before jumping into the mailer class, let’s query all the required information from the object’s attachments.</p>



<p>Note: We can use inner joins in queries to get the list of attachments straight away, but Salesforce does not allow us to retrieve Body file data inside them.</p>



<p>Therefore, we need to perform two queries. First of all, we will get the list of attachment Ids and then retrieve the rest separately.</p>



<pre class="wp-block-preformatted">List&lt;Startup__c&gt; startups = [SELECT Id, (SELECT Id FROM Attachments) FROM Startup__c WHERE Id = :startupId];
if (!startups.isEmpty()) {
  Set&lt;Id&gt; attachmentIds = (new Map&lt;Id, SObject&gt;(startups[0])).keySet();
  List&lt;Attachment&gt; files = [SELECT Name, Body, ContentType FROM Attachment WHERE Id IN :attachmentIds];
}</pre>



<p>As the result of the code above, we would get the list of the files with all the information we need to proceed further.</p>



<p>Now, we need to generate the list of the actual email attachments out of the files that we have and attach them to the email.</p>



<pre class="wp-block-preformatted">List&lt;Messaging.EmailFileAttachment&gt; attachments = new List&lt;Messaging.EmailFileAttachment&gt;();
for (Attachment file: files) {
  Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
  efa.setFileName(file.Name);
  efa.setBody(file.Body);
  efa.setContentType(file.ContentType);
  attachments.add(efa);
}
message.setFileAttachments(attachments);</pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>You can configure whenever you want to attach files as links or actual data in Setup &gt; Email &gt; Email Attachments.</p></blockquote>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/digitalflask.com/wp-content/uploads/2018/10/email-attachments.png?w=640&#038;ssl=1" alt="Salesforce Setup &gt; Email &gt; Email Attachment settings" class="wp-image-73366"/></figure></div>



<p>Here we have the attachment list ready. Next, we can continue with the single email message.</p>



<h2 class="wp-block-heading">Email Templates</h2>



<p>We can compose the email content both in the plain text and HTML right in the Apex class.</p>



<p>However, that is not the best practice.</p>



<p>We want to keep it clear and dynamic. We do not have to edit and deploy our code on every text change. Plus, we might want to customize the email so that it will follow the company branding style guides.</p>



<p>Here come email templates for rescue.</p>



<p>In Salesforce, you can build own email templates which are very versatile. To do so, go to the Setup &gt; Email &gt; Classic Email Templates and click New Template. Choose Custom (without using Letterhead), select folder, check the Available For Use box, give it a name and subject.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" height="288" width="640" decoding="async" src="https://i0.wp.com/digitalflask.com/wp-content/uploads/2018/10/email-template-1024x460.png?resize=640%2C288&#038;ssl=1" alt="Salesforce Setup &gt; Email &gt; Email Templates settings" class="wp-image-73367"/></figure></div>



<p>Then provide the HTML and plain text content.</p>



<p>In conclusion, we have the email template ready to use. We can query it by the DeveloperName and then set its Id, Subject, and HtmlValue to our message.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>For instance, you might query templates dynamically based on the Lead language to send out personalized emails.</p></blockquote>



<pre class="wp-block-preformatted">EmailTemplate template = [SELECT Id, Subject, HtmlValue FROM EmailTemplate WHERE DeveloperName = 'InvestorMaterial'];
message.setTemplateId(template.Id);
message.setSubject(template.Subject);
message.setHtmlBody(template.HtmlValue);</pre>



<p>As a result, the code above will apply the custom template to the email we are planning to send.</p>



<h2 class="wp-block-heading">Organization-Wide Email Addresses</h2>



<p>Besides the custom templates, Salesforce provides the functionality to set the sender email address as well via the organization-wide email address settings.</p>



<p>Otherwise, the email will have the System Administrator user’s address by default.</p>



<p>In addition to templates, organization-wide address settings give us the opportunity to customize the message further.</p>



<p>Go to Setup &gt; Email &gt; Organization-Wide Addresses and click New.</p>



<p>Enter the display name, email address, and choose which Profiles could use this address.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" height="205" width="640" decoding="async" src="https://i0.wp.com/digitalflask.com/wp-content/uploads/2018/10/email-address-1024x328.png?resize=640%2C205&#038;ssl=1" alt="Salesforce Setup &gt; Email &gt; Organization-Wide Addresses settings" class="wp-image-73369"/></figure></div>



<p>Next, we can query this address and set is as the sender.</p>



<pre class="wp-block-preformatted">List&lt;OrgWideEmailAddress&gt; addresses = [SELECT Id FROM OrgWideEmailAddress WHERE Address = 'info@digitalflask.com'];
if (!addresses.isEmpty()) {
  message.setOrgWideEmailAddressId(addresses[0].Id);
}</pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>If you know the Lead or Contact Id, you can record the email out as the object’s activity like</p><p>message. setTargetObjectId(lead.Id);<br>message.setSaveAsActivity(true);</p></blockquote>



<h2 class="wp-block-heading">Send Email</h2>



<p>After all, the only part left is actually to try to send the message.</p>



<pre class="wp-block-preformatted">try {
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
} catch (Exception e) {
  throw e;
}</pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>If you execute the method via the REST API, Throw will return the 500 Http server error response with the detailed description so that we could handle it on the client side.</p></blockquote>



<p>In summary, I hope that I helped you learn more about the Salesforce email settings and how to you could use the Messaging class to extend and customize the standard functionality to send out dynamically generated and personalized emails.</p>



<p>In conclusion, here is the complete sample of the messaging method.</p>



<script src="https://gist.github.com/Frelseren/105ea7574a2854df41c7bb1714e6145f.js"></script>



<p>Credits: Nikita Verkhoshintcev<br>Source: https://digitalflask.com/blog/send-email-attachments-salesforce-apex/</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/09/03/send-email-with-attachments-in-salesforce-apex/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3257</post-id>	</item>
		<item>
		<title>Inserting sObject Record Dynamically in Salesforce</title>
		<link>https://www.mhamzas.com/blog/2021/04/26/inserting-sobject-record-dynamically-in-salesforce/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inserting-sobject-record-dynamically-in-salesforce</link>
					<comments>https://www.mhamzas.com/blog/2021/04/26/inserting-sobject-record-dynamically-in-salesforce/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Mon, 26 Apr 2021 10:43:01 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[dynamic apex]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3240</guid>

					<description><![CDATA[]]></description>
										<content:encoded><![CDATA[
<script src="https://gist.github.com/mhamzas/b0fa92c15598470f613351ec47a49a3a.js"></script>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/04/26/inserting-sobject-record-dynamically-in-salesforce/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3240</post-id>	</item>
		<item>
		<title>Get Object and Field Label value using API Names</title>
		<link>https://www.mhamzas.com/blog/2021/04/21/get-object-and-field-label-value-using-api-names/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=get-object-and-field-label-value-using-api-names</link>
					<comments>https://www.mhamzas.com/blog/2021/04/21/get-object-and-field-label-value-using-api-names/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Wed, 21 Apr 2021 10:18:48 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[dynamic]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3237</guid>

					<description><![CDATA[This is a very common use case where you have the API Name, but you need the Current Labels for your object, or field. Either its Custom or Standard. Typically, you know it already, but you need it when you&#8217;re writing your <br /><a href="https://www.mhamzas.com/blog/2021/04/21/get-object-and-field-label-value-using-api-names/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>This is a very common use case where you have the API Name, but you need the Current Labels for your object, or field. Either its Custom or Standard.</p>



<p>Typically, you know it already, but you need it when you&#8217;re writing your apex dynamically.</p>



<p>Here is a simple method which accept API Names in STRING and returns the labels. You can modify as per your need:</p>



<script src="https://gist.github.com/mhamzas/98555fcde33fd6ee7d4559f31768b33b.js"></script>



<p>Happy Coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/04/21/get-object-and-field-label-value-using-api-names/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3237</post-id>	</item>
		<item>
		<title>Flow: Create/Update CustomMetadata</title>
		<link>https://www.mhamzas.com/blog/2021/01/22/flow-create-update-custommetadata/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=flow-create-update-custommetadata</link>
					<comments>https://www.mhamzas.com/blog/2021/01/22/flow-create-update-custommetadata/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Fri, 22 Jan 2021 11:04:20 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[flows]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3221</guid>

					<description><![CDATA[As of now, you can GET custom metadata records in flows but you cannot create or update them. Using this invocable class you can create/update custom metadata records in Flows. You can access the repository here: https://github.com/mhamzas/Flow-Create-Update-Custom-Metadata The code is self explanatory <br /><a href="https://www.mhamzas.com/blog/2021/01/22/flow-create-update-custommetadata/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" src="https://pbs.twimg.com/media/EsUm8qbXcAIjnSP?format=png&amp;name=small" alt="Image"/></figure>



<p>As of now, you can GET custom metadata records in flows but you cannot create or update them.</p>



<p>Using this invocable class you can create/update custom metadata records in Flows.</p>



<p><strong>You can access the repository here:</strong></p>



<p><a href="https://github.com/mhamzas/Flow-Create-Update-Custom-Metadata">https://github.com/mhamzas/Flow-Create-Update-Custom-Metadata</a></p>



<p>The code is self explanatory but I have tried my best to do better commenting for others to understand what&#8217;s going on here.</p>



<pre class="wp-block-code"><code>/**
 * @description       : This invocable class will allow you to update/create customMetadata using Flow/Process Builder.
 * @author            : M Hamza Siddiqui @ mhamzas.com
 * @group             : Cloudjunction Advisors, Inc.
 * @last modified on  : 01-21-2021
 * @last modified by  : M Hamza Siddiqui @ mhamzas.com
 * Modifications Log 
 * -----------------
 * Ver   Date         Author                             		Modification
 * 1.0   01-22-2021   M Hamza Siddiqui @ mhamzas.com		   Initial Version
**/
global class UpdateCMD implements Metadata.DeployCallback {

    /*An invocable variable used as input or output variables in the process builder*/
    global class ActionRequest {
        @InvocableVariable(required = true)
        public List&lt;sObject&gt; data;
    }
    //This invocable method is used for processing the business by taking the input from process builder/flow
    @InvocableMethod(label = 'Create/Update Custom Metadata')
        global static void invokeService(List &lt;ActionRequest&gt; requests) {
          for (ActionRequest requestObj: requests) {
              //Accessing the values from process builder/flow when record is inserted
              for(sObject obj : requestObj.data){
                  //System.debug('requestObj.sObject@@:' + obj);
                  //System.debug('requestObj.ObjectType@@:' + obj.getSObjectType());
                  // Getting all the Populated fields in a Map
                  Map&lt;String, Object&gt; fieldsToValue = obj.getPopulatedFieldsAsMap();
                  Map&lt;String, Object&gt; metadataFieldValueMap = new Map&lt;String, Object&gt;();
                  String MetadataDevName; // To Store Custom Metadata Record API/Developer name
                  String MetadataLabel; // To Store Custom Metadata Label name
                  // Looping on all the populated fields
                  for (String fieldName : fieldsToValue.keySet()){
                      System.debug('field name is ' + fieldName + ', value is ' + fieldsToValue.get(fieldName));
                      // We don't want to add system fields to the Map for update, so here is some simple logic
                      if(fieldName == 'Label'){
                          MetadataLabel = (String)fieldsToValue.get(fieldName);
                      } else if(fieldName == 'DeveloperName'){
                          MetadataDevName = (String)fieldsToValue.get(fieldName);
                      } else if(fieldName != 'Id' &amp;&amp; fieldName != 'Language' &amp;&amp; fieldName != 'MasterLabel' &amp;&amp; fieldName != 'NamespacePrefix' &amp;&amp; fieldName != 'QualifiedApiName') {
                          // Populating Map for Processing later
                          metadataFieldValueMap.put(fieldName, fieldsToValue.get(fieldName));
                      }
                  }
                  
                  System.debug('Label is ' + MetadataLabel + '&amp; DeveloperName is ' + MetadataDevName);
                  // Making sure to have either Label or Developer Name for the CMD record to process
                  if(String.isBlank(MetadataDevName) &amp;&amp; String.isBlank(MetadataLabel)){
                      throw createCustomException('Make sure to add "Label" attribute in assignemnt for Create and "DeveloperName" for update.');
                  } else { 
                      //if MetadataDevName available, which means the record exists already - Processing UPDATE
                      if(!String.isBlank(MetadataDevName)){
                          UpdateCMD.updateCustomMetadata(String.valueof(obj.getSObjectType()),MetadataDevName, MetadataLabel,metadataFieldValueMap);
                      } else { // Creating a new Custom Metadata record
                          //if ID not available - CREATE
                          UpdateCMD.createCustomMetadata(String.valueof(obj.getSObjectType()), MetadataLabel, metadataFieldValueMap);
                      }
                  }
                  // END
              }
          }
    }
    
    /* Custom Metadata Deploy Methods */
    /* ============================================================*/
    //Inteface method 
    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            //Success
            System.debug('Success Result-' + result);
        } else {
            //Failed
            System.debug('Failed Result-' + result);
            throw createCustomException(String.valueof(result));
        }
    }
     
    //Create Custom Metadata record
    public static void createCustomMetadata(String metdataName, String label, Map&lt;String, Object&gt; metadataFieldValueMap){
        String recordDevName = label.replaceAll(' ', '_');
        Metadata.CustomMetadata cMetadata = new Metadata.CustomMetadata();
        cMetadata.fullName = metdataName + '.' + recordDevName;
        cMetadata.label = label;
         
        for(String key : metadataFieldValueMap.keySet()){
            Metadata.CustomMetadataValue cMetadataValue = new Metadata.CustomMetadataValue();
            cMetadataValue.Field = key;
            cMetadataValue.Value = metadataFieldValueMap.get(key); 
            cMetadata.values.add(cMetadataValue);
        }
         
        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(cMetadata);
        UpdateCMD callback = new UpdateCMD();
        Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
    }
     
    //Update Custom Metadata record
    public static void updateCustomMetadata(String metdataName, String recordDevName, String label, Map&lt;String, Object&gt; metadataFieldValueMap){
        Metadata.CustomMetadata cMetadata = new Metadata.CustomMetadata();
        cMetadata.fullName = metdataName + '.' + recordDevName;
        cMetadata.label = label;
         
        for(String key : metadataFieldValueMap.keySet()){
            Metadata.CustomMetadataValue cMetadataValue = new Metadata.CustomMetadataValue();
            cMetadataValue.Field = key;
            cMetadataValue.Value = metadataFieldValueMap.get(key); 
            cMetadata.values.add(cMetadataValue);
        }
         
        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(cMetadata);
        UpdateCMD callback = new UpdateCMD();
        Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
    }

    /* Flow Exception Handling */
    /* ============================================================*/
    public class CustomException extends Exception {}
    
    static CustomException createCustomException(String message) {
        CustomException ex = new CustomException(message);
        ex.setMessage(message);
        return ex;
    }
}</code></pre>



<p>Happy Coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/01/22/flow-create-update-custommetadata/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3221</post-id>	</item>
		<item>
		<title>Build Invocable Actions That Work for Multiple Objects</title>
		<link>https://www.mhamzas.com/blog/2020/06/18/build-invocable-actions-that-work-for-multiple-objects/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=build-invocable-actions-that-work-for-multiple-objects</link>
					<comments>https://www.mhamzas.com/blog/2020/06/18/build-invocable-actions-that-work-for-multiple-objects/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Thu, 18 Jun 2020 11:32:48 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[invocable]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3144</guid>

					<description><![CDATA[After Spring 20, you can now create reusable Apex actions that use the generic sObject and List&#60;sObject> data types. Build one action that works for multiple objects, rather than one for each individual object. Developers can build a filter or sort action <br /><a href="https://www.mhamzas.com/blog/2020/06/18/build-invocable-actions-that-work-for-multiple-objects/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>After Spring 20, you can now create reusable Apex actions that use the generic sObject and List&lt;sObject> data types. Build one action that works for multiple objects, rather than one for each individual object. </p>



<p>Developers can build a filter or sort action that works with any collection of records, from accounts and contacts to custom objects. Previously, developers couldn&#8217;t use polymorphic Apex structures in invocable actions because generic data types weren&#8217;t supported.</p>



<p>Create a custom action, or edit an existing one. Use the sObject or List&lt;sObject> data type in invocable methods and attributes.</p>



<script src="https://gist.github.com/mhamzas/6f9984bba86809037bbf7b9d47011363.js"></script>



<p>Previously, the example class would have been tied to the Account or Contact or myCustomObject__c object. But now developers create one action, and the Flow Builder admin chooses the object each time they use that action.</p>



<p class="has-text-align-center"><img data-recalc-dims="1" decoding="async"  src="https://i0.wp.com/releasenotes.docs.salesforce.com/en-us/spring20/release-notes/release_notes/images/224_rn_forcecom_flow_fbuilder_dynamic_types.png?w=640&#038;ssl=1" alt="A new action screen with contact specified as the object for “recordsToCheck” input, and Account as the object for “recordsToReturn”."></p>



<h4 class="wp-block-heading">Source</h4>



<ul class="wp-block-list"><li>https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_forcecom_flow_fbuilder_dynamic_types.htm?edition=&amp;impact=</li></ul>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2020/06/18/build-invocable-actions-that-work-for-multiple-objects/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3144</post-id>	</item>
		<item>
		<title>Insert Records in multiple Objects in single DML</title>
		<link>https://www.mhamzas.com/blog/2020/04/06/insert-records-in-multiple-objects-in-single-dml/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=insert-records-in-multiple-objects-in-single-dml</link>
					<comments>https://www.mhamzas.com/blog/2020/04/06/insert-records-in-multiple-objects-in-single-dml/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Mon, 06 Apr 2020 16:54:37 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[apex]]></category>
		<category><![CDATA[sfdc]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3082</guid>

					<description><![CDATA[There could be many cases where you need to insert records in multiple objects in a single method but you might end up with TOO MANY DMLs Error. Here we&#8217;ll discuss how you can insert records in multiple objects in a single <br /><a href="https://www.mhamzas.com/blog/2020/04/06/insert-records-in-multiple-objects-in-single-dml/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>There could be many cases where you need to insert records in multiple objects in a single method but you might end up with TOO MANY DMLs Error.</p>



<p>Here we&#8217;ll discuss how you can insert records in multiple objects in a single dml call.</p>



<p>Let&#8217;s assume you need to add records in Account, Contact and AccountContact (Custom Object). By using the below code, you add records in all 3 objects in a single DML call.</p>



<script src="https://gist.github.com/mhamzas/64bbccc25a41f68509e83781ee8baa0e.js"></script>



<p>Source : <a href="https://salesforce.stackexchange.com/questions/141897/insert-multiple-sobjects-in-single-dml-call">https://salesforce.stackexchange.com/questions/141897/insert-multiple-sobjects-in-single-dml-call</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2020/04/06/insert-records-in-multiple-objects-in-single-dml/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3082</post-id>	</item>
	</channel>
</rss>
