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;
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
add a comment |
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
add a comment |
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
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
apex trigger
edited 2 days ago
sanket kumar
3,6032427
3,6032427
asked 2 days ago
gs650xgs650x
168111
168111
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
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
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
add a comment |
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.
Thank you so much, I will always keep this in mind
– gs650x
yesterday
add a comment |
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.
Thank you for responding, I got the error.
– gs650x
yesterday
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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
add a comment |
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
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
add a comment |
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
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
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
add a comment |
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
add a comment |
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.
Thank you so much, I will always keep this in mind
– gs650x
yesterday
add a comment |
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.
Thank you so much, I will always keep this in mind
– gs650x
yesterday
add a comment |
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.
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.
answered yesterday
sfdcfoxsfdcfox
265k13212459
265k13212459
Thank you so much, I will always keep this in mind
– gs650x
yesterday
add a comment |
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
add a comment |
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.
Thank you for responding, I got the error.
– gs650x
yesterday
add a comment |
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.
Thank you for responding, I got the error.
– gs650x
yesterday
add a comment |
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.
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.
edited yesterday
answered 2 days ago
JsonJson
463522
463522
Thank you for responding, I got the error.
– gs650x
yesterday
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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