Contact trigger to limit an account to not have more than 2 contacts Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Moderator Election Q&A - Questionnaire 2019 Community Moderator Election ResultsAccount Roll up of contacts meeting certian criteriaTrigger on AccountAfter Update Trigger on Account to create contactPreventing duplicate records from being processed by triggerProcess more than 50K records in triggerI don't know the rest logic how to add both contacts amount and display it accountHow to create Account,Contact records based on the web-case data if contact email not existed in system?How can I have the contact record detail page reflect total accountHow to set ParentID field on Account record related to contact in a Trigger?update a field on contact once i associate a account

How can I fade player character when he goes inside or outside of the area?

Why is black pepper both grey and black?

What's the difference between `auto x = vector<int>()` and `vector<int> x`?

Models of set theory where not every set can be linearly ordered

What do you call a plan that's an alternative plan in case your initial plan fails?

I am not a queen, who am I?

What would be the ideal power source for a cybernetic eye?

Is a manifold-with-boundary with given interior and non-empty boundary essentially unique?

Disable hyphenation for an entire paragraph

What is the longest distance a 13th-level monk can jump while attacking on the same turn?

Why did the IBM 650 use bi-quinary?

When to stop saving and start investing?

Storing hydrofluoric acid before the invention of plastics

Why is "Captain Marvel" translated as male in Portugal?

Problem drawing boxes with arrows in tikZ

Do I really need recursive chmod to restrict access to a folder?

Dominant seventh chord in the major scale contains diminished triad of the seventh?

Did Xerox really develop the first LAN?

Is the address of a local variable a constexpr?

Gastric acid as a weapon

What happens to sewage if there is no river near by?

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

Why aren't air breathing engines used as small first stages

Is there a documented rationale why the House Ways and Means chairman can demand tax info?



Contact trigger to limit an account to not have more than 2 contacts



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Moderator Election Q&A - Questionnaire
2019 Community Moderator Election ResultsAccount Roll up of contacts meeting certian criteriaTrigger on AccountAfter Update Trigger on Account to create contactPreventing duplicate records from being processed by triggerProcess more than 50K records in triggerI don't know the rest logic how to add both contacts amount and display it accountHow to create Account,Contact records based on the web-case data if contact email not existed in system?How can I have the contact record detail page reflect total accountHow to set ParentID field on Account record related to contact in a Trigger?update a field on contact once i associate a account



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















Yesterday I got rejected from a job interview because the interviewer asked me to write a trigger to limit the number of contacts per account and I wrote exactly the below but he said this won't work and it is not the correct way to write the same.
I ran the same and it is working fine I am not able to see any problem with the below code can someone please help me understand from the interview's perspective why he said this is not the right way.



 trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) Trigger.operationType == triggerOperation.AFTER_UPDATE) 
set<Id> IdSet =new set<Id>();
for(Contact cot : trigger.new)
if(cot.accountID != null)
IdSet.add(cot.accountId);



Integer contactListCount = [Select count() from contact where accountID IN: IdSet];

if(contactListCount > 2)
for(contact cop : trigger.new)
cop.addError('cannot have more than 2 contacts per account');













share|improve this question






























    1















    Yesterday I got rejected from a job interview because the interviewer asked me to write a trigger to limit the number of contacts per account and I wrote exactly the below but he said this won't work and it is not the correct way to write the same.
    I ran the same and it is working fine I am not able to see any problem with the below code can someone please help me understand from the interview's perspective why he said this is not the right way.



     trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) Trigger.operationType == triggerOperation.AFTER_UPDATE) 
    set<Id> IdSet =new set<Id>();
    for(Contact cot : trigger.new)
    if(cot.accountID != null)
    IdSet.add(cot.accountId);



    Integer contactListCount = [Select count() from contact where accountID IN: IdSet];

    if(contactListCount > 2)
    for(contact cop : trigger.new)
    cop.addError('cannot have more than 2 contacts per account');













    share|improve this question


























      1












      1








      1








      Yesterday I got rejected from a job interview because the interviewer asked me to write a trigger to limit the number of contacts per account and I wrote exactly the below but he said this won't work and it is not the correct way to write the same.
      I ran the same and it is working fine I am not able to see any problem with the below code can someone please help me understand from the interview's perspective why he said this is not the right way.



       trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) Trigger.operationType == triggerOperation.AFTER_UPDATE) 
      set<Id> IdSet =new set<Id>();
      for(Contact cot : trigger.new)
      if(cot.accountID != null)
      IdSet.add(cot.accountId);



      Integer contactListCount = [Select count() from contact where accountID IN: IdSet];

      if(contactListCount > 2)
      for(contact cop : trigger.new)
      cop.addError('cannot have more than 2 contacts per account');













      share|improve this question
















      Yesterday I got rejected from a job interview because the interviewer asked me to write a trigger to limit the number of contacts per account and I wrote exactly the below but he said this won't work and it is not the correct way to write the same.
      I ran the same and it is working fine I am not able to see any problem with the below code can someone please help me understand from the interview's perspective why he said this is not the right way.



       trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) Trigger.operationType == triggerOperation.AFTER_UPDATE) 
      set<Id> IdSet =new set<Id>();
      for(Contact cot : trigger.new)
      if(cot.accountID != null)
      IdSet.add(cot.accountId);



      Integer contactListCount = [Select count() from contact where accountID IN: IdSet];

      if(contactListCount > 2)
      for(contact cop : trigger.new)
      cop.addError('cannot have more than 2 contacts per account');










      apex trigger






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 days ago









      sanket kumar

      3,6032427




      3,6032427










      asked 2 days ago









      gs650xgs650x

      168111




      168111




















          3 Answers
          3






          active

          oldest

          votes


















          1














          This is the best example to use child soql to handle bulky records..
          Please see the Below logic..



          trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) 
          if ((Trigger.isInsert





          share|improve this answer

























          • Thank you for responding but what if the account query fetch more than 50K records

            – gs650x
            yesterday











          • For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

            – sarvesh kumar
            yesterday











          • Thank you so much!

            – gs650x
            yesterday


















          3














          This trigger is not bulkified. It can't handle more than one account at a time. To fix the problem, an aggregate query would have been the most efficient solution. Here's my version of this trigger:



          trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) 
          Set<Id> accountIds = new Set<Id>();
          for(Contact record: Trigger.new)
          accountIds.add(record.AccountId);

          accountIds.remove(null);
          Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
          SELECT AccountId Id
          FROM Contact
          WHERE AccountId = :accountIds
          GROUP BY AccountId
          HAVING COUNT(Id) > 2]).keySet();
          for(Contact record: Trigger.new)
          if(moreThan2Contacts.contains(record.AccountId))
          record.AccountId.addError('You may not have more than 2 contacts per account.');





          You should always look for opportunities to use aggregate results (such as summing, counting, and finding averages) for performance reasons.






          share|improve this answer























          • Thank you so much, I will always keep this in mind

            – gs650x
            yesterday


















          1














          I would recommend creating a developer account to test said code with some debug statements to see what the output is.



          Your soql query returns the total number of contacts in each account. This will work if there is only one account in the org, But it won't if there're more.Example: if there are 3 accounts with 4 contacts each, the output of contactListCount will be 12.



          Also, in your 2nd loop you are looping again over Trigger.new, even if you did manage to filter out the accounts with 2+ contacts and added them to a new list, you ignored it by running over Trigger.new again and not over the new list.






          share|improve this answer

























          • Thank you for responding, I got the error.

            – gs650x
            yesterday











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "459"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f257764%2fcontact-trigger-to-limit-an-account-to-not-have-more-than-2-contacts%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          This is the best example to use child soql to handle bulky records..
          Please see the Below logic..



          trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) 
          if ((Trigger.isInsert





          share|improve this answer

























          • Thank you for responding but what if the account query fetch more than 50K records

            – gs650x
            yesterday











          • For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

            – sarvesh kumar
            yesterday











          • Thank you so much!

            – gs650x
            yesterday















          1














          This is the best example to use child soql to handle bulky records..
          Please see the Below logic..



          trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) 
          if ((Trigger.isInsert





          share|improve this answer

























          • Thank you for responding but what if the account query fetch more than 50K records

            – gs650x
            yesterday











          • For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

            – sarvesh kumar
            yesterday











          • Thank you so much!

            – gs650x
            yesterday













          1












          1








          1







          This is the best example to use child soql to handle bulky records..
          Please see the Below logic..



          trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) 
          if ((Trigger.isInsert





          share|improve this answer















          This is the best example to use child soql to handle bulky records..
          Please see the Below logic..



          trigger ContactTrigger on Contact (after insert, before Insert, before update, after update) 
          if ((Trigger.isInsert






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered yesterday









          sarvesh kumarsarvesh kumar

          10418




          10418












          • Thank you for responding but what if the account query fetch more than 50K records

            – gs650x
            yesterday











          • For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

            – sarvesh kumar
            yesterday











          • Thank you so much!

            – gs650x
            yesterday

















          • Thank you for responding but what if the account query fetch more than 50K records

            – gs650x
            yesterday











          • For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

            – sarvesh kumar
            yesterday











          • Thank you so much!

            – gs650x
            yesterday
















          Thank you for responding but what if the account query fetch more than 50K records

          – gs650x
          yesterday





          Thank you for responding but what if the account query fetch more than 50K records

          – gs650x
          yesterday













          For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

          – sarvesh kumar
          yesterday





          For that case, you can use where clause in soql to store accountid in the set. I update the answer, Please have a look

          – sarvesh kumar
          yesterday













          Thank you so much!

          – gs650x
          yesterday





          Thank you so much!

          – gs650x
          yesterday













          3














          This trigger is not bulkified. It can't handle more than one account at a time. To fix the problem, an aggregate query would have been the most efficient solution. Here's my version of this trigger:



          trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) 
          Set<Id> accountIds = new Set<Id>();
          for(Contact record: Trigger.new)
          accountIds.add(record.AccountId);

          accountIds.remove(null);
          Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
          SELECT AccountId Id
          FROM Contact
          WHERE AccountId = :accountIds
          GROUP BY AccountId
          HAVING COUNT(Id) > 2]).keySet();
          for(Contact record: Trigger.new)
          if(moreThan2Contacts.contains(record.AccountId))
          record.AccountId.addError('You may not have more than 2 contacts per account.');





          You should always look for opportunities to use aggregate results (such as summing, counting, and finding averages) for performance reasons.






          share|improve this answer























          • Thank you so much, I will always keep this in mind

            – gs650x
            yesterday















          3














          This trigger is not bulkified. It can't handle more than one account at a time. To fix the problem, an aggregate query would have been the most efficient solution. Here's my version of this trigger:



          trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) 
          Set<Id> accountIds = new Set<Id>();
          for(Contact record: Trigger.new)
          accountIds.add(record.AccountId);

          accountIds.remove(null);
          Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
          SELECT AccountId Id
          FROM Contact
          WHERE AccountId = :accountIds
          GROUP BY AccountId
          HAVING COUNT(Id) > 2]).keySet();
          for(Contact record: Trigger.new)
          if(moreThan2Contacts.contains(record.AccountId))
          record.AccountId.addError('You may not have more than 2 contacts per account.');





          You should always look for opportunities to use aggregate results (such as summing, counting, and finding averages) for performance reasons.






          share|improve this answer























          • Thank you so much, I will always keep this in mind

            – gs650x
            yesterday













          3












          3








          3







          This trigger is not bulkified. It can't handle more than one account at a time. To fix the problem, an aggregate query would have been the most efficient solution. Here's my version of this trigger:



          trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) 
          Set<Id> accountIds = new Set<Id>();
          for(Contact record: Trigger.new)
          accountIds.add(record.AccountId);

          accountIds.remove(null);
          Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
          SELECT AccountId Id
          FROM Contact
          WHERE AccountId = :accountIds
          GROUP BY AccountId
          HAVING COUNT(Id) > 2]).keySet();
          for(Contact record: Trigger.new)
          if(moreThan2Contacts.contains(record.AccountId))
          record.AccountId.addError('You may not have more than 2 contacts per account.');





          You should always look for opportunities to use aggregate results (such as summing, counting, and finding averages) for performance reasons.






          share|improve this answer













          This trigger is not bulkified. It can't handle more than one account at a time. To fix the problem, an aggregate query would have been the most efficient solution. Here's my version of this trigger:



          trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) 
          Set<Id> accountIds = new Set<Id>();
          for(Contact record: Trigger.new)
          accountIds.add(record.AccountId);

          accountIds.remove(null);
          Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
          SELECT AccountId Id
          FROM Contact
          WHERE AccountId = :accountIds
          GROUP BY AccountId
          HAVING COUNT(Id) > 2]).keySet();
          for(Contact record: Trigger.new)
          if(moreThan2Contacts.contains(record.AccountId))
          record.AccountId.addError('You may not have more than 2 contacts per account.');





          You should always look for opportunities to use aggregate results (such as summing, counting, and finding averages) for performance reasons.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          sfdcfoxsfdcfox

          265k13212459




          265k13212459












          • Thank you so much, I will always keep this in mind

            – gs650x
            yesterday

















          • Thank you so much, I will always keep this in mind

            – gs650x
            yesterday
















          Thank you so much, I will always keep this in mind

          – gs650x
          yesterday





          Thank you so much, I will always keep this in mind

          – gs650x
          yesterday











          1














          I would recommend creating a developer account to test said code with some debug statements to see what the output is.



          Your soql query returns the total number of contacts in each account. This will work if there is only one account in the org, But it won't if there're more.Example: if there are 3 accounts with 4 contacts each, the output of contactListCount will be 12.



          Also, in your 2nd loop you are looping again over Trigger.new, even if you did manage to filter out the accounts with 2+ contacts and added them to a new list, you ignored it by running over Trigger.new again and not over the new list.






          share|improve this answer

























          • Thank you for responding, I got the error.

            – gs650x
            yesterday















          1














          I would recommend creating a developer account to test said code with some debug statements to see what the output is.



          Your soql query returns the total number of contacts in each account. This will work if there is only one account in the org, But it won't if there're more.Example: if there are 3 accounts with 4 contacts each, the output of contactListCount will be 12.



          Also, in your 2nd loop you are looping again over Trigger.new, even if you did manage to filter out the accounts with 2+ contacts and added them to a new list, you ignored it by running over Trigger.new again and not over the new list.






          share|improve this answer

























          • Thank you for responding, I got the error.

            – gs650x
            yesterday













          1












          1








          1







          I would recommend creating a developer account to test said code with some debug statements to see what the output is.



          Your soql query returns the total number of contacts in each account. This will work if there is only one account in the org, But it won't if there're more.Example: if there are 3 accounts with 4 contacts each, the output of contactListCount will be 12.



          Also, in your 2nd loop you are looping again over Trigger.new, even if you did manage to filter out the accounts with 2+ contacts and added them to a new list, you ignored it by running over Trigger.new again and not over the new list.






          share|improve this answer















          I would recommend creating a developer account to test said code with some debug statements to see what the output is.



          Your soql query returns the total number of contacts in each account. This will work if there is only one account in the org, But it won't if there're more.Example: if there are 3 accounts with 4 contacts each, the output of contactListCount will be 12.



          Also, in your 2nd loop you are looping again over Trigger.new, even if you did manage to filter out the accounts with 2+ contacts and added them to a new list, you ignored it by running over Trigger.new again and not over the new list.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered 2 days ago









          JsonJson

          463522




          463522












          • Thank you for responding, I got the error.

            – gs650x
            yesterday

















          • Thank you for responding, I got the error.

            – gs650x
            yesterday
















          Thank you for responding, I got the error.

          – gs650x
          yesterday





          Thank you for responding, I got the error.

          – gs650x
          yesterday

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f257764%2fcontact-trigger-to-limit-an-account-to-not-have-more-than-2-contacts%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form