I want to build a trigger on contact, that accept check box. And In Account object it take 2 contacts that are active. when user assign 3rd active contact to the same account he/she will get error messege. how can it possible? i completed all codes but these limit of 2 contacts are pending. can anyone try to guide me how to do this?
trigger ContactTrigger on Contact(after insert, after update, after delete, after undelete) {
switch on Trigger.operationType {
when AFTER_INSERT {
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
if (String.isNotBlank(con.AccountId)) {
//write automation logic here
accountIds.add(con.AccountId);
}
}
// get aggregate result for all accounts
List<AggregateResult> results = [
SELECT AccountId, COUNT(Id) totalContacts
FROM Contact
WHERE Active__c = TRUE AND AccountId IN :accountIds
GROUP BY AccountId
];
integer var = results.size();
// build final list of accounts to update
List<Account> accountsToUpdate = new List<Account>();
for (AggregateResult result : results) {
// get account id and number of active contacts
String accId = String.valueOf(result.get('AccountId'));
Integer totalContacts = Integer.valueOf(result.get('totalContacts'));
// make sure you use Id feild in your account to update it
Account acc = new Account(Id = accId, Active_Contacts__c = totalContacts);
accountsToUpdate.add(acc);
}
// update the final list of account
update accountsToUpdate;
}
when AFTER_UPDATE {
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
// capture the account id only if active checkbox value is flipped
if (String.isNotBlank(con.AccountId) && Trigger.oldMap.get(con.Id).Active__c != con.Active__c) {
// write automation logic here
accountIds.add(con.AccountId);
} else if (Trigger.oldMap.get(con.Id).AccountId != con.AccountId) {
accountIds.add(con.AccountId);
accountIds.add(Trigger.oldMap.get(con.Id).AccountId);
}
}
// get aggregate result for all accounts
List<AggregateResult> results = [
SELECT AccountId, COUNT(Id) totalContacts
FROM Contact
WHERE Active__c = TRUE AND AccountId IN :accountIds
GROUP BY AccountId
];
// build final list of accounts to update
List<Account> accountsToUpdate = new List<Account>();
for (AggregateResult result : results) {
// get account id and number of active contacts
String accId = String.valueOf(result.get('AccountId'));
Integer totalContacts = Integer.valueOf(result.get('totalContacts'));
// make sure you use Id feild in your account to update it
Account acc = new Account(Id = accId, Active_Contacts__c = totalContacts);
accountsToUpdate.add(acc);
}
// update the final list of account
update accountsToUpdate;
}
}
}
Related
The purpose here is to Remove Product Sharing When user is removed from AccountTeamMember.
List<AccountTeamMember> acctmListProd = [Select id,UserId, AccountId, TeamMemberRole FROM
AccountTeamMember WHERE Id In:acctmList and
TeamMemberRole IN:Roles]
Map<Id,Id> accToUserIdList = new Map<Id,Id>();
for(AccountTeamMember At: acctmListProd)
{
accToUserIdList.put(At.AccountId, At.UserId);
}
List<Product__Share> DelProdShareRecords = new List<Product__Share>();
Set<Id> productIds = new Set<Id>();
for(Id accId: accToUserIdList.keySet())
{
List<Product__c> prodList = [Select id,Account__c from Product__c where
Account__c=accId];
for(Product__c prod: prodList)
{
productIds.add(prod.Id);
}
List<Product__Share> prodShareRecords = [Select id,ParentId,UserOrGroupId from
Product__Share where ParentId IN:productIds AND
UserOrGroupId=accToUserList.get(accId)
];
DelProdShareRecords.addAll(prodShareRecords);
}
if(!DelProdShareRecords.isEmpty())
{
Database.deleteResult[] result = Database.delete(DelProdShareRecords, false);
}
https://ideas.salesforce.com/s/idea/a0B8W00000GdgUVUAZ/allow-global-security-and-sharing-rules-settings-on-products
Product__Share isn't a thing. This code looks like it was never compiled or tested in an org.
Here is snippet I am using in my anonymous window . Purpose is to retrieve Opportunities of a contact. Even after adding opportunity contact role , contact.Opportunities.size is resulting in zero (last debug line). Am I missing something ? you may use the below code directly.
Update: able to get size now but same logic doesn't work for code coverage in test class . details listed below:
Only 'if' part of controller is covered and 'else' part is never covered even though size of contact.opportunities is more than 0.
Controller method :
public PageReference sendingEmail() {
//contact1 has query records
sizeVar = contact1.Opportunities.size();
if(contact1.npo02__OppAmountLastYear__c>0 ) {
if(sizeVar==0) {
// if size is 0 then navigate to a particular vf page
PageReference pr = Page.NoDonationOrNoEmail;
pr.getParameters().put('id',(String)contact1.id);
pr.setRedirect(true);
return pr;
}
else
{ //when contact.opportunities size is more than 0 then navigate to
other vf page.
PageReference pr1 = Page.NoPrint;
pr1.getParameters().put('id',(String)contact1.id);
pr1.setRedirect(true);
return pr1;
}
} return null;
}
Test Class:
//creating account
Account a = new Account();
a.Name = 'Test Co.';
a.BillingStreet = '298 S. Ringo Street';
a.BillingCity = 'Little Rock';
insert a;
//Creating contact
Contact contact1 = new Contact();
contact1.FirstName = 'Paul';
contact1.LastName = 'Test';
contact1.AccountId = a.id;
contact1.npo02__OppAmountLastYear__c=100;
insert contact1;
//creating opportunity
Opportunity o = new Opportunity();
o.RecordType = [SELECT Id, Name, DeveloperName FROM RecordType
WHERE Name = 'Membership' LIMIT 1];
o.Name = 'New Record';
o.StageName = 'Posted';
o.AccountId = contact1.AccountId;
o.CloseDate = Date.today();
o.Description = 'Test Record';
insert o;
//creating opportunity contact role
OpportunityContactRole ocr = new OpportunityContactRole();
ocr.ContactId = contact1.Id;
ocr.OpportunityId = o.Id;
ocr.IsPrimary = TRUE;
ocr.Role = 'Decision Maker';
insert ocr;
System.debug('created opportunity contact role for primary');
Update o;
contact1 = [SELECT Id, Name,(SELECT id FROM opportunities) FROM
Contact WHERE Id=:contact1.Id];
PageReference pr = Page.NoPrint;
pr.getParameters().put('id', String.valueOf(contact1.id));
Test.setCurrentPage(pr);
ApexPages.StandardController cont5 = new
ApexPages.StandardController(contact1);
BulkEmailController testAccPlan = new
BulkEmailController(cont5);
testAccPlan.sendingEmail();
When you create and insert a record, you don't get formula fields nor you can navigate lookup. The same goes with child relationship.
You have to query the fields you need.
Change Update contact1; to contact1 = [SELECT Id, (SELECT Id FROM Opportunities) FROM Contact WHERE Id = :contact1.Id]; and the last debug line will print 1.
trigger MaxProductAmount on OpportunityLineItem (after update) {
Set opportunityIds = new Set();
for (AggregateResult ar : [select Max(Quantity)opport1,Opportunity.AccountId from OpportunityLineItem
where Opportunity.AccountId in :accountIds]) {
Decimal total = Decimal.valueOf(ar.get('opport1'));
accountsToUpdate.add(new Account(Id = ar.Opportunity.AccountId,Max_product_amount__c = total));
}
#isTest
public static void TestEmptySearchQuery() {
User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
System.runAs ( thisUser ) { // running as thisUser to Avoid Error: MIXED_DML_OPERATION
setupData(); // inside setupData, community is created successfully
generateUser(); // List of user assigned with some profile, as required for project.
list<PermissionSetAssignment> PSA = new list<PermissionSetAssignment> ();
PermissionSet ps = [SELECT Id, name FROM PermissionSet where name='Some_Access'];
system.debug('PermissionSet ' + ps);
for(user u:userList)
PSA.add(new PermissionSetAssignment(AssigneeId = u.id, PermissionSetId = ps.Id)); // all the user assgined with some_access based on requirement of project
insert PSA;
}
Test.startTest();
User usr = [select Id from User where Id = :userList[0].id];
System.runAs(usr) {
system.debug('Network ommunityId ****' + Network.getNetworkId()); //getting null
SomeClass obj = new SomeClass();
Id Nid=obj.fetchNetworkId(); // return null;
system.debug('network id ' + Nid); // null
}
Test.stopTest();
}
class SomeClass {
//some code
public id fetchNetworkId() {
system.debug('network id ' + Network.getNetworkId()); // network id null;
return Network.getNetworkId(); // return null
}
// some code
}
While running normally page, controller returns proper network id,
when try to write a test class for this, community network id always return null.
the user you use for the runAs needs to be part of a community, so you need to basically create an account, create a contact and then a user for that contact. That makes the runAS user to be part of a community
i have this APEX trigger and I'm getting this error but not sure why "Error: Compile Error: expecting a left angle bracket, found 'oppcntctrle' at line 13 column 10"
trigger updatecontactrolecount on Opportunity (before insert, before update)
{
Boolean isPrimary;
Integer iCount;
Map<String, Opportunity> oppty_con = new Map<String, Opportunity>();//check if the contact role is needed and add it to the oppty_con map
for (Integer i = 0; i < Trigger.new.size(); i++)
{
oppty_con.put(Trigger.new[i].id,
Trigger.new[i]);
}
isPrimary = False;
for (List oppcntctrle :[select OpportunityId from OpportunityContactRole where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in :oppty_con.keySet())])
{
if (oppcntctrle .Size() >0)
{
isPrimary = True;
}
}
iCount = 0;
for (List oppcntctrle2 : [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.OpportunityId in :oppty_con.keySet())])//Query for Contact Roles
{
if (oppcntctrle2 .Size()>0)
{
iCount= oppcntctrle2 .Size();
}
}
for (Opportunity Oppty : system.trigger.new) //Check if roles exist in the map or contact role isn't required
{
Oppty.Number_of_Contacts_Roles_Assigned__c = iCount;
Oppty.Primary_Contact_Assigned__c =isPrimary;
}
}
Instead of
for (List oppcntctrle :[select OpportunityId from OpportunityContactRole where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in :oppty_con.keySet())])
should be
List<OpportunityContactRole> oppcntctrle = [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in :oppty_con.keySet())];
The same for
for (List oppcntctrle2 : [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.OpportunityId in :oppty_con.keySet())])//Query for Contact Roles
should be changed to
List<OpportunityContactRole> oppcntctrle2 = [select OpportunityId from OpportunityContactRole where (OpportunityContactRole.OpportunityId in :oppty_con.keySet())];//Query for Contact Roles