I want to know how to create a read-only group + like + comment and not being able to post for members except admin and owner
* how to use triggers on the posting in this group?.
i tried but it not work:
trigger N_GroupReadOnly on FeedItem (before insert) {
ID groupId = [Select Id from CollaborationGroup where Name = 'Group_ReadOnly'].Id;
CollaborationGroup ownerId = [Select OwnerId From CollaborationGroup Where Name = 'Group_ReadOnly'];
for(FeedItem item : trigger.new){
if((item.ParentId == groupId) && (item.InsertedById != ownerId.OwnerId)){
system.debug('you can not add post in this group');
alert("you can not add post in this group");
delete item ;
return;
}
else{
insert item;
}
}
}
Thank you.
Solution:
as per this developerforce.com forum entry:
Trigger
trigger GroupReadOnly on FeedItem (before insert) {
CollaborationGroup gp = [Select OwnerId, Id From CollaborationGroup Where Name = 'Group_ReadOnly'];
List<FeedItem> feedItems = new List<FeedItem>();
for(FeedItem item : trigger.new){
if(item.ParentId == gp.Id)
{
feedItems.add(item);
}
}
if(feedItems.size() >0) GroupReadOnlyClass.FilterFeedItems(feedItems);
}
Class
public class GroupReadOnlyClass{
public static void FilterFeedItems(List<FeedItem> feedItems){
CollaborationGroup gp = [Select OwnerId, Id From CollaborationGroup Where Name = 'Group_ReadOnly'];
for(FeedItem item :feedItems){
if(item.ParentId == gp.Id)
{
if(UserInfo.getUserId()!= gp.OwnerId){
item.addError('You cannot post! Just Owner can post in this group');
}
}
}
}
}
Related
I added the Apex Class and Apex trigger below to update the field Number_of_Contacts at the Account level when a Contact is added or removed to a certain Account.
My idea is to display in Accounts reports, how many Contacts an Account has. I had to do this, because Salesforce doesn't provide a Roll-Up Summary, at the Account level, to count Contacts.
I also tried creating a Flow, but it only works when a Contact is created or deleted.
Here are Apex Class and Trigger I tried to use:
Class:
public without sharing class ContactTriggerHandler {
private Set<Id> getAccountIds(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for(Contact c : contacts) {
if(c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
return accountIds;
}
private Map<Id, Account> getAccountMap(Set<Id> accountIds) {
return new Map<Id, Account>([SELECT Id, Number_of_Contacts__c FROM Account WHERE Id in :accountIds]);
}
public void process(List<Contact> contacts, System.TriggerOperation operation) {
Set<Id> accountIds = getAccountIds(contacts);
if(accountIds.size() > 0) {
Map<Id, Account> accountMap = getAccountMap(accountIds);
for(Contact c : contacts) {
if(accountMap.containsKey(c.AccountId)) {
switch on operation{
when AFTER_INSERT {
accountMap.get(c.AccountId).Number_of_Contacts__c += 1;
}
when AFTER_DELETE {
accountMap.get(c.AccountId).Number_of_Contacts__c -= 1;
}
when AFTER_UNDELETE {
accountMap.get(c.AccountId).Number_of_Contacts__c += 1;
}
}
}
}
update accountMap.values();
}
}
}
Trigger
trigger ContactTrigger on Contact (after insert, after delete, after undelete) {
ContactTriggerHandler handler = new ContactTriggerHandler();
switch on Trigger.operationType {
when AFTER_INSERT {
handler.process(Trigger.new, Trigger.operationType);
}
when AFTER_DELETE {
handler.process(Trigger.old, Trigger.operationType);
}
when AFTER_UNDELETE {
handler.process(Trigger.new, Trigger.operationType);
}
}
}
However, how can I include a line of code that updates the Number_of_Contacs__c field when a Contact moves to a different Account (like, an "After_Update" trigger)?
Thank you,
I tried some guidance on how to add AFTER UPDATE triggers in Apex Code, but I didn't succeed.
Trigger context variables give you access to old and new values, state of the database before the user clicked save and what the user has changed. You're passing from trigger to class only trigger.new but to get the id of original account the contact was linked to and update it - something like this.
Set<Id> idsToCheck = new Set<Id>();
// During update, only if account id changes...
for(Contact c : trigger.new){
Contact old = trigger.oldMap.get(c.Id);
if(c.AccountId != old.AccountId){
idsToCheck.add(c.AccountId);
idsToCheck.add(old.AccountId); // mark both for further processing
}
}
idsToCheck.remove(null);
List<Account> accounts = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :idsToCheck];
for(Account a : accounts){
a.Number_of_Contacts__c = a.Contacts.size();
}
update accounts;
this is my first question here.
Nice to meet you all, and looking forward to be here with you from now onward.
I am relatively new to coding with apex in general.
And I need to create the test class for the following code:
trigger CPTC on ContactPointTypeConsent (after insert, after update)
{
for (ContactPointTypeConsent c : Trigger.new)
{
Id ii = [Select PartyId From ContactPointTypeConsent WHERE Id = :c.Id].PartyId;
List<ContactPointTypeConsent> cptcL = [Select id, (Select id, Name, PrivacyConsentStatus From Individuals)
From Individual Where id = :ii].Individuals;
List<Contact> contacts = [Select id, (Select id, Name, MarketingSubscription__c From Contacts)
From Individual Where id = :ii].Contacts;
List<Lead> leads = [Select id, (Select id, Name, MarketingSubscription__c From Leads)
From Individual Where id = :ii].Leads;
Boolean checkBoxValue = checkStatus(cptcL);
for (Contact contact : contacts)
{
contact.MarketingSubscription__c = checkBoxValue;
}
for (Lead lead : leads)
{
lead.MarketingSubscription__c = checkBoxValue;
}
update contacts;
update leads;
}
public Boolean checkStatus(List<ContactPointTypeConsent> cptc)
{
Boolean result = false;
for (ContactPointTypeConsent c : cptc)
{
if (c.PrivacyConsentStatus == 'OptIn')
{
result = true;
Break;
}
}
return result;
}
}
Thank you all for your help, and time!
I write code for Apex trigger, now i need to test him. Can u help me?
here is the code:
public with sharing class Sharing_Sales {
public static void SharingRelatedOrdersAndAccount(List<Sales_Rep_Assignment__c> triggerNew,
Map<Id, Sales_Rep_Assignment__c> oldMap){
List<Order> relatedOrders = new List<Order>();
List<Sales_Rep_Assignment__c> activeAssignments = new List<Sales_Rep_Assignment__c>();
Set<Id> accIds = new Set<Id>();
Set<Id> salesRepsIds = new Set<Id>();
Map<Id, List<Order>> ordersByAccountId = new Map<Id, List<Order>>();
for(Sales_Rep_Assignment__c sar: triggerNew){
if(sar.Active__c == true && (oldMap.get(sar.id).Active__c == false || oldMap == null)) {
activeAssignments.add(sar);
salesRepsIds.add(sar.Sales_Reps__c);
accIds.add(sar.Account__c);
}
for(Order ord : [SELECT Id, AccountId FROM Order WHERE AccountId IN :accIds]) {
if (!ordersByAccountId.containsKey(ord.AccountId)) {
ordersByAccountId.put(ord.AccountId, new List<Order>());
}
ordersByAccountId.get(ord.AccountId).add(ord);
}
List<OrderShare> sharingRecords = new List<OrderShare>();
for (Sales_Rep_Assignment__c srs : activeAssignments) {
for (Order ord : ordersByAccountId.get(srs.Account__c)) {
OrderShare sharingorderrecord = new OrderShare();
sharingorderrecord.OrderId = ord.Id;
sharingorderrecord.OrderAccessLevel = 'Edit';
sharingorderrecord.UserOrGroupId = 'Sales_Rep__c';
sharingorderrecord.RowCause = 'Manual';
sharingRecords.add(sharingorderrecord);
}
if(!sharingRecords.IsEmpty()){
insert sharingRecords;
}
}
}
}
public static void Sharingorderandaccountisdelete(List<Sales_Rep_Assignment__c> triggerNew,
List<Order> relatedOrders,
Map<id, Sales_Rep_Assignment__c> oldMap){
List<Sales_Rep_Assignment__c> falseAssignments = new List<Sales_Rep_Assignment__c>();
Set<Id> accIds = new Set<Id>();
Set<Id> salesRepsIds = new Set<Id>();
Map<Id, List<Order>> ordersByAccountId = new Map<Id, List<Order>>();
for(Sales_Rep_Assignment__c sar: triggerNew){
if(sar.Active__c == false && oldMap.get(sar.id).Active__c == true || triggerNew == null){
falseAssignments.add(sar);
salesRepsIds.add(sar.Sales_Reps__c);
accIds.add(sar.Account__c);
}
}
List<OrderShare> sharingDeletedOrder = new List<OrderShare>();
for(Order ord : [SELECT Id, AccountId FROM Order WHERE AccountId IN :accIds]) {
if (!ordersByAccountId.containsKey(ord.AccountId)) {
ordersByAccountId.put(ord.AccountId, new List<Order>());
}
for(OrderShare sharingRecords: [SELECT Id FROM OrderShare WHERE Id =: ord.id AND UserOrGroupId IN :salesRepsIds]){
sharingDeletedOrder.add(sharingRecords);
}
}
delete sharingDeletedOrder;
}
}`
deskp of task Use
Apex Trigger to share Account and related Orders to Sales Rep when new Sales Rep Assignment is created.
When Sales Rep Assignment record is deleted or set to Active = false Sales Rep should not have edit access to account and related orders anymore, if Active is set back to true – share records again.
You have to create a test class. Here you will find some guidance:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
After you worked it through and wrote a test class, we can help with problems.
Here am using map ,not abled to understand how to solve the duplicate name,i want one agent name against number of payments(child of opp)
how do I get unique names of users
public class First_Pay_ClearRates_Controller {
#AuraEnabled
public static Map<Id,User> fetchUsers() {
// List<User> userList= [SELECT Id, Name FROM User WHERE Profile.Name = 'Sales' LIMIT 20];
Map<Id,User> userMap= new Map<Id,User>([SELECT Id, Name FROM User WHERE Profile.Name = 'Sales' LIMIT 20]);
return userMap;
}
#AuraEnabled
public static List<Opportunity> getOpps(Map<Id,User> usrMap){
Map<Id,List<Opportunity>> oppMap = new Map<Id,List<Opportunity>>();
List<Opportunity> oppList = new List<Opportunity>();
List<Payments__c> payList= new List<Payments__c>();
List<Payments__c> payList1= new List<Payments__c>();
// prev key Agent_Name_User__c
// AND First_Payment_Date__c=THIS_MONTH
for(Opportunity o: [SELECT Id,First_Payment_Date__c,OwnerId,Owner.Name ,of_Payments_Made__c,PaymentsCounter__c,CollectedPaymentCount__c,First_Client_Payment_Collected_Date__c From Opportunity WHERE OwnerId IN: usrMap.keyset() AND First_Payment_Date__c!=null LIMIT 20]){
if(!oppMap.containsKey(o.OwnerId)){
oppMap.put(o.OwnerId,new List<Opportunity>());
}
o.PaymentsCounter__c=0;
o.CollectedPaymentCount__c=0;
//AND Due_Date__c=THIS_MONTH
for(Payments__c p :[Select Id,Opportunity__c,Payment_Collected__c,Due_Date__c FROM Payments__c WHERE Opportunity__c =: o.Id ]){
if(!p.Payment_Collected__c){
payList.add(p);
o.PaymentsCounter__c= payList.size();
}else if(p.Payment_Collected__c){
payList1.add(p);
o.CollectedPaymentCount__c= payList1.size();
}
}
oppList.add(o);
oppMap.put(o.OwnerId,oppList);
}
return oppList;
}
how to count number of opportunities related to account,
total number of opportunities field on account should be increment/decrement when Opportunity is created/deleted.
How to solve it, pl help me with sample code.
Actually, you don't need write a code if you need count of all opportunities related to an account. Create a “Rollup/Summary” field type on the Account. Evaluate the Opportunity object, and run a “Count” operation. That’s it!
UPD:
If you need to solve it with trigger it will looks something like this:
trigger CountOpportunitiesOnAccount on Opportunity (after insert, after delete){
Set<Id> aId = new Set<Id>();
if(Trigger.isInsert || Trigger.isDelete || Trigger.isUndelete){
for(Opportunity opp : Trigger.New){
aId.add(opp.AccountId);
}
updateAccounts(aId);
}
if(Trigger.isDelete){
for(Opportunity opp : Trigger.old){
aId.add(opp.AccountId);
}
updateAccounts(aId);
}
private void updateAccounts(Set<Id> accIds){
List<Account> accs = [select id, OpportunitiesAmount from Account where Id in :accIds];
List<Opportunity> opps = [select id from Opportunity where AccountId in :accIds];
for(Account a : accs){
a.OpportunitiesAmount = opps.size();
}
update accs;
}
}
So, here you go. This is the Exact code that counts the Exact number of Related Opportunities of an Account and Populates it on the Standard field of Account Number ( you can add it on the custom field also).
trigger TriggTask on Opportunity (after insert, after delete)
{
List<id> TriggerList = new List<id>();
if(Trigger.isInsert)
{
List<id> TriggerList = new List<id>();
for(Opportunity Opp : Trigger.new)
{
TriggerList.add(Opp.AccountId);
}
List<Account> DML = New List<Account>();
List<Account> Ls = [select id,(select id from Opportunities) from Account where id in:TriggerList];
for(Account AccNew : ls)
{
Integer Num = AccNew.Opportunities.size();
AccNew.AccountNumber=String.valueOf(Num);
DML.add(AccNew);
}
update ls;
}
if(Trigger.isDelete)
{
for(Opportunity Opp : Trigger.old)
{
TriggerList.add(Opp.AccountId);
}
List<Account> DML = New List<Account>();
List<Account> Ls = [select id,(select id from Opportunities) from Account where id in:TriggerList];
for(Account act : Ls)
{
act.AccountNumber=String.valueOf(act.Opportunities.size());
DML.add(act);
}
update Ls;
}
}
If you must write a trigger, you might also consider the re-parenting of an Opportunity. This is why the Roll-Up Summary field is preferred by many developers. There may be edge cases that generate errors or unexpected results.
trigger CountOpportunitiesOnAccount on Opportunity (after insert, after delete, after update){
Set<Id> aId = new Set<Id>();
if(Trigger.isInsert || Trigger.isDelete || Trigger.isUndelete || Trigger.isUpdate){
for(Opportunity opp : Trigger.New){
if(Trigger.isUpdate){
if(Trigger.newMap.get(opp.Id).AccountID != Trigger.oldMap.get(opp.Id).AccountID){
aId.add(opp.AccountId);
}
}
else{
aId.add(opp.AccountId);
}
}
if(aID != NULL && aID.size() > 0){
updateAccounts(aId);
}
}
if(Trigger.isDelete){
for(Opportunity opp : Trigger.old){
aId.add(opp.AccountId);
}
updateAccounts(aId);
}
private void updateAccounts(Set<Id> accIds){
List<Account> accs = [select id, Number_Of_Opps__c, (select Id from Opportunities) from Account where Id in :accIds];
List<Account> liAccToUpdate = new list<Account>();
//Should be able to handle more than one opportunity/account in the trigger.
for(Account a : accs){
//Prevent recursive updating
if(a.Number_Of_Opps__c != a.Opportunities.size()){
a.Number_Of_Opps__c = a.Opportunities.size();
liAccToUpdate.add(a);
}
}
if(liAccToUpdate != NULL && liAccToUpdate.size() > 0){
update accs;
}
}
}
public static void opportunityCount(List<opportunity> oppList) {
set<id>accountIDs = new set<id>();
list<Account> accList = new List<Account>();
for (opportunity eachOppAccId:oppList) {
accountIDs.add(eachOppAccId.AccountId);
}
for (Account eachAccount:[select id,No_Of_Opportunities__c, (select id, AccountID from opportunities) from Account where id In:accountIDs]) {
eachAccount.No_Of_Opportunities__c=eachAccount.opportunities.size();
accList.add(eachAccount);
}
update accList;
}