if i try to insert records my after update trigger is running and when aim only updating the records after update is running. i want to control the order of execution. i want to execute like when record is inserted my after insert trigger will, run when record is updated my after update trigger will run
public class DuplicateTicketHandler {
public void afterinsert(List<Case> newcase){
List<String> newNaturofIssue = new List<String>();
List<String> newFacility = new List<String>();
List<Case>updatedChuld = new List<Case>();
List<Case> parent = new List<Case>();
List<Case> Childs = new List<Case>();
List<Case> childtoupdate= new List<Case>();
List<Case> childtoupdate2 = new List<Case>();
Set<Id> newset = new Set<Id>();
Case test;
for(Case cs : newcase){
newNaturofIssue.add(cs.Nature_of_issue_Formula__c);
newFacility.add(cs.Facility_Formula__c);
}
for(Case cs : [Select Id,Nature_of_issue_Formula__c,Facility_Formula__c from Case where status <> 'closed' and (
Nature_of_issue_Formula__c IN:newNaturofIssue
and
Facility_Formula__c IN: newFacility) ]){
newset.add(cs.Id);
}
parent = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc Limit 1];
System.debug(parent + 'parent ===>');
Childs = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc];
Childs.remove(0);
System.debug( 'child ===>'+Childs);
if(parent.size()> 0){
test = parent[0];
System.debug('test'+test);
}
if(Childs.size()>0 ){
for(Case c : Childs){
c.ParentId = test.Id;
updatedChuld.add(c);
}
}
System.debug('childupdated===>'+updatedChuld);
if(updatedChuld.size() > 0){
update updatedChuld;
}
System.debug('test===>'+test);
}
public void afterUpdate(List<Case> OldAcc , List<Case> newAcc, Map<Id, Case> newCase, Map<Id, Case> oldCase){
List<String> newNaturofIssue = new List<String>();
List<String> newFacility = new List<String>();
List<Case> parent = new List<Case>();
List<Case> Childs = new List<Case>();
List<Case> childtoupdate= new List<Case>();
List<Case> childtoupdate2 = new List<Case>();
Case test ;
for(Case cs : OldAcc){
newNaturofIssue.add(cs.Nature_of_issue_Formula__c);
newFacility.add(cs.Facility_Formula__c);
}
System.debug('dupliactes'+[Select Id,Nature_of_issue_Formula__c,Facility_Formula__c from Case Where status <> 'Closed' and (
Nature_of_issue_Formula__c IN:newNaturofIssue
and
Facility_Formula__c IN: newFacility) ]);
Set<Id> newset = new Set<Id>();
for(Case cs : [Select Id,Nature_of_issue_Formula__c,Facility_Formula__c from Case Where status <> 'Closed' and (
Nature_of_issue_Formula__c IN:newNaturofIssue
and
Facility_Formula__c IN: newFacility) ]){
newset.add(cs.Id);
}
System.debug('newset'+newset);
parent = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc Limit 1];
System.debug(parent + 'parent ===>');
Childs = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc offset 1];
System.debug( 'child ===>'+Childs);
if(parent.size()> 0){
test = parent[0];
System.debug('test'+test);
}
Case oldparentcase ;
Case newparentcase;
for(Case cs : newAcc){
oldparentcase = oldCase.get(cs.Id);
newparentcase = newCase.get(cs.Id);
}
if(string.valueOf(oldparentcase.OwnerId).startsWith('00G') && oldparentcase.Status == newparentcase.Status){
for(Case cstr : childs){
cstr.OwnerId = newparentcase.OwnerId;
cstr.Status = newparentcase.Status;
childtoupdate.add(cstr);
}
}
else if(oldparentcase.Status != newparentcase.Status){
for(Case cstr : childs){
cstr.OwnerId = newparentcase.OwnerId;
cstr.Status = newparentcase.Status;
childtoupdate2.add(cstr);
}
}
if (childtoupdate.size()>0) {
update childtoupdate;
}
if (childtoupdate2.size()>0) {
update childtoupdate2;
}
System.debug('childupdate===>'+childtoupdate);
System.debug('childupdate2===>'+childtoupdate2);
System.debug('oldparentcase===>'+oldparentcase);
System.debug('oldparentcase====>'+oldparentcase.Nature_of_issue_Formula__c);
System.debug('oldparentcase====>'+oldparentcase.Facility_Formula__c);
System.debug('oldparentcase====>'+oldparentcase.Status);
System.debug('oldparentcase====>'+oldparentcase.OwnerId);
System.debug('newparentcase===>'+newparentcase);
System.debug('newparentcase====>'+newparentcase.Nature_of_issue_Formula__c);
System.debug('newparentcase====>'+newparentcase.Facility_Formula__c);
System.debug('newparentcase====>'+newparentcase.Status);
System.debug('oldparentcase====>'+newparentcase.OwnerId);
System.debug('childtoupdate===>'+childtoupdate);
}
}
handler trigger below
trigger DuplicateTicketsTriggerV1 on Case (after insert,after Update) {
DuplicateTicketHandler dth = new DuplicateTicketHandler();
if(Trigger.isInsert && Trigger.isAfter){
dth.afterinsert(Trigger.New);
}
else {
if(Trigger.isAfter && Trigger.isUpdate){
dth.afterUpdate(Trigger.Old, Trigger.New, trigger.newMap, trigger.oldMap);
}
}
}
If you want to have more control over what needs to be executed in your trigger (for example, in order to avoid executing the AfterUpdate logic when the AfterInsert has been run already), you can use static class variables to control the execution. For example, say you want to prevent your AfterUpdate logic to be executed if the AfterInsert logic has been executed already, you can modify your class and trigger like this:
public class DuplicateTicketHandler {
public static Boolean runAfterUpdate = true;
public void afterinsert(List<Case> newcase){
List<String> newNaturofIssue = new List<String>();
List<String> newFacility = new List<String>();
List<Case>updatedChuld = new List<Case>();
List<Case> parent = new List<Case>();
List<Case> Childs = new List<Case>();
List<Case> childtoupdate= new List<Case>();
List<Case> childtoupdate2 = new List<Case>();
Set<Id> newset = new Set<Id>();
Case test;
for(Case cs : newcase){
newNaturofIssue.add(cs.Nature_of_issue_Formula__c);
newFacility.add(cs.Facility_Formula__c);
}
for(Case cs : [Select Id,Nature_of_issue_Formula__c,Facility_Formula__c from Case where status <> 'closed' and (
Nature_of_issue_Formula__c IN:newNaturofIssue
and
Facility_Formula__c IN: newFacility) ]){
newset.add(cs.Id);
}
parent = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc Limit 1];
System.debug(parent + 'parent ===>');
Childs = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc];
Childs.remove(0);
System.debug( 'child ===>'+Childs);
if(parent.size()> 0){
test = parent[0];
System.debug('test'+test);
}
if(Childs.size()>0 ){
for(Case c : Childs){
c.ParentId = test.Id;
updatedChuld.add(c);
}
}
System.debug('childupdated===>'+updatedChuld);
if(updatedChuld.size() > 0){
update updatedChuld;
}
System.debug('test===>'+test);
}
public void afterUpdate(List<Case> OldAcc , List<Case> newAcc, Map<Id, Case> newCase, Map<Id, Case> oldCase){
List<String> newNaturofIssue = new List<String>();
List<String> newFacility = new List<String>();
List<Case> parent = new List<Case>();
List<Case> Childs = new List<Case>();
List<Case> childtoupdate= new List<Case>();
List<Case> childtoupdate2 = new List<Case>();
Case test ;
for(Case cs : OldAcc){
newNaturofIssue.add(cs.Nature_of_issue_Formula__c);
newFacility.add(cs.Facility_Formula__c);
}
System.debug('dupliactes'+[Select Id,Nature_of_issue_Formula__c,Facility_Formula__c from Case Where status <> 'Closed' and (
Nature_of_issue_Formula__c IN:newNaturofIssue
and
Facility_Formula__c IN: newFacility) ]);
Set<Id> newset = new Set<Id>();
for(Case cs : [Select Id,Nature_of_issue_Formula__c,Facility_Formula__c from Case Where status <> 'Closed' and (
Nature_of_issue_Formula__c IN:newNaturofIssue
and
Facility_Formula__c IN: newFacility) ]){
newset.add(cs.Id);
}
System.debug('newset'+newset);
parent = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc Limit 1];
System.debug(parent + 'parent ===>');
Childs = [Select ID,Status,createdDate from case where Id IN: newset order by createdDate asc offset 1];
System.debug( 'child ===>'+Childs);
if(parent.size()> 0){
test = parent[0];
System.debug('test'+test);
}
Case oldparentcase ;
Case newparentcase;
for(Case cs : newAcc){
oldparentcase = oldCase.get(cs.Id);
newparentcase = newCase.get(cs.Id);
}
if(string.valueOf(oldparentcase.OwnerId).startsWith('00G') && oldparentcase.Status == newparentcase.Status){
for(Case cstr : childs){
cstr.OwnerId = newparentcase.OwnerId;
cstr.Status = newparentcase.Status;
childtoupdate.add(cstr);
}
}
else if(oldparentcase.Status != newparentcase.Status){
for(Case cstr : childs){
cstr.OwnerId = newparentcase.OwnerId;
cstr.Status = newparentcase.Status;
childtoupdate2.add(cstr);
}
}
if (childtoupdate.size()>0) {
update childtoupdate;
}
if (childtoupdate2.size()>0) {
update childtoupdate2;
}
System.debug('childupdate===>'+childtoupdate);
System.debug('childupdate2===>'+childtoupdate2);
System.debug('oldparentcase===>'+oldparentcase);
System.debug('oldparentcase====>'+oldparentcase.Nature_of_issue_Formula__c);
System.debug('oldparentcase====>'+oldparentcase.Facility_Formula__c);
System.debug('oldparentcase====>'+oldparentcase.Status);
System.debug('oldparentcase====>'+oldparentcase.OwnerId);
System.debug('newparentcase===>'+newparentcase);
System.debug('newparentcase====>'+newparentcase.Nature_of_issue_Formula__c);
Trigger:
trigger DuplicateTicketsTriggerV1 on Case (after insert,after Update) {
DuplicateTicketHandler dth = new DuplicateTicketHandler();
if(Trigger.isInsert && Trigger.isAfter){
dth.afterinsert(Trigger.New);
DuplicateTicketHandler.runAfterUpdate = false;
}
else {
if(Trigger.isAfter && Trigger.isUpdate && DuplicateTicketHandler.runAfterUpdate){
dth.afterUpdate(Trigger.Old, Trigger.New, trigger.newMap, trigger.oldMap);
}
}
}
Related
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.
I have created a test class with 51% code coverage till line no 34.
Further, I tried to satisfy if condition but I couldn't. Now I am not getting how to do with 100% code coverage.
Here is the Apex class:
public class AssignProjectController {
public String CaseIds;
public String status {get;set;}
public List<Project__c> activeProjects {get;set;}
public String keyWordSearched {get;set;}
public Id projectId {get;set;}
public AssignProjectController (){
CaseIds = ApexPages.currentPage().getParameters().get('id');
}
public void getProjects(){
status = '';
String searchQuery = 'FIND \'' + keyWordSearched + '*\' IN ALL FIELDS RETURNING Project__c (id,Name,Description__c where Status__c =\'Active\')';
try{
List<List<Project__c >> searchList = search.query(searchQuery);
activeProjects = searchList[0];
if(activeProjects.size() == 0) status = 'No search result found.';
}catch(Exception ex){
system.debug('ex..'+ex.getMessage());
}}}
public PageReference assignProjectToCases(){
List<Case__c> customSettingList = Case__c.getall().values();
List<String> settingRecordTypeList = new List<String>();
for(Case__c caseObj:customSettingList){
settingRecordTypeList.add(caseObj.Name);
}
List<RecordType> recordTypeListData = [SELECT Id FROM RecordType WHERE SObjectType = 'Case' and Name In : settingRecordTypeList];
if(CaseIds != null){
List<String> caseIDList = new List<String>();
caseIDList = CaseIds.split(',');
if([Select id from Case where Id In : caseIDList and RecordType.Id NOT In : recordTypeListData].size() > 0){
status = 'failed';
}else{
List<Case> cases = [Select id,Project__c,RecordType.Name from Case where Id In : caseIDList and RecordType.Id In : recordTypeListData];
if(cases.size() > 0){
for(case caseOb: cases){
caseOb.Project__c = projectId ;
}
try{
update cases ;
status = 'Changes are scheduled';
}catch(Exception ex){
system.debug('AssignProjectController :::'+ex.getMessage());
status = 'Something Went Wrong';
}}}}
return null;
}}
Here is the test class- which I tried to resolve
#isTest public class TestAssignProjectController {
public static Project__c insertProject(){
Project__c proObj = new Project__c();
proObj.Name = 'testProject';
proObj.Status__c = 'Active';
proObj.Description__c = 'for testing';
proObj.Internal_Email_Alias__c = 'a#test.com';
return proObj;
}
public static Account getAccount(){
Account accoObj = new Account();
accoObj.Name = 'testAcc';
accoObj.Location__c = 'testLocation';
accoObj.Type = 'CM';
accoObj.BillingCountry = 'United States';
return accoObj;
}
public static Contact insertContact(Account accObj){
Contact conObj = new Contact();
conObj.FirstName = 'test';
conObj.LastName = 'testLastname';
conObj.AccountId = accObj.Id;
conObj.Email = 'abc#gmail.com';
return conObj;
}
public static Id getTechTypeId(){
return Schema.SObjectType.Case.getRecordTypeInfosByName().get('Tech ').getRecordTypeId();
}
public static Case insertCase(String conId, String proId){
Case caseObj = new Case();
caseObj.Project__c = proId;
caseObj.ContactId = conId;
caseObj.Status = 'Open';
caseObj.Inquiry_Type__c = 'All';
caseObj.Subject = 'TestSubject';
caseObj.Description = 'TestDescription';
caseObj.Case_Is_Reopened__c = false;
caseObj.RecordTypeId = getTechTypeId();
return caseObj;
}
public static testmethod void testMethodExecution(){
AssignController asigncon = new AssignController ();
Project__c proObj = insertProject();
insert proObj;
System.assertEquals(proObj.Status__c,'Active');
Account accObj = getAccount();
insert accObj;
System.assertNotEquals(accObj.Id,null);
Contact conObj = insertContact(accObj);
insert conObj;
System.assertNotEquals(conObj.Id,null);
Case caseObj = insertCase(conObj.Id, proObj.Id);
insert caseObj;
system.debug(caseObj);
//Set baseURL & case ID
PageReference pageRef = Page.Assign;
pageRef.getParameters().put('id',caseObj.id+',');
AssignController asigncon1 = new AssignController ();
asigncon1.getProjects();
asigncon1.assignProjectToCases();
}}
If you are referring if(cases.size() > 0) this statement, then surely there is problem of inserting the case. Make sure that insert caseObj; is working and inserts data in Salesforce backend.
If there is no data in case object, the test method cannot cover the if statement.
Getting the error in line " taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;" becasue the ownerid field is on contact.
Contact is the parent of benefit, Here I am getting all the benefits in start method. I want to add contactid only once if it has more than one child for that I used SET. I want to use maps as I need to get the contact OwnerId field from contact object which I am fetching in the query in start method. How do I Access contact.ownerId field using a map? below is the code.
global Database.QueryLocator start(Database.BatchableContext bc) {
Query='select contact__r.ownerId, contact__c, Task_creation_date__c, Status__c, task_created__c, type__c from Benefit__c Where Task_creation_date__c= TODAY AND Status__c IN (\'Active\',\'Pending\') AND Task_created__c =FALSE AND Type__c!=\'Short Term Medical\'';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc, List<Benefit__c> scope){
// process each batch of records
List<Contact> contacts = new List<Contact>();
List<Task> TaskList = new List<Task>();
set<id> conset = New set<id>();
Map<id,benefit__c> ConMap = new map<id,Benefit__c>();
for (Benefit__c b : scope) {
conset.add(b.contact__c);
ConMap.put(b.contact__c, b);
b.task_created__c = TRUE;
}
system.debug('contact and its benefit------'+ConMap);
recordsProcessed = conset.size();
//List<Contact> tempList = new List<Contact>();
// tempList = [Select Id,OwnerId, firstname from Contact where Id IN:(conset)];
if(!ConMap.isEmpty())
{
for(Benefit__c ben : ConMap.values())
{
Task taskObj = new Task();
taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;
I want to populate contact ownerid as the task ownerid but how do I access it from the map and keep the unique contact id in the map?
I see that the batch query does not have the filtering condition 'Contact__c != null'. So, it's possible that one of the benefit records is missing value in the 'Contact__c' field and you wouldn't find it in the map. You can solve this in two ways:
Add 'Contact__c != null' to the selector query if you don't care about those records.
(Or)
Check for 'null' value in the for loop as below:
if(!ConMap.isEmpty())
{
for(Benefit__c ben : ConMap.values())
{
if(String.isBlank(ben.Contact__c)){
/* continue;
or
throw exception()
*/
}
Task taskObj = new Task();
taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;
I re wrote the code to resolve this nd optimize the code as below.
public with sharing class MyBatch implements Database.Batchable<AggregateResult>{
public Iterable<AggregateResult> start(Database.BatchableContext context)
{
return [
SELECT Contact__c, Contact__r.OwnerId owner FROM Benefit__c
WHERE Contact__c != null AND ...
GROUP BY Contact__c, Contact__r.OwnerId
];
}
public void execute(Database.BatchableContext context, List<AggregateResult> scope)
{
Set<Id> contactIds = new Set<Id>();
List<Task> tasks = new List<Task>();
for (AggregateResult aggregate : scope)
{
Id ownerId = (Id)aggregate.get('owner');
Id contactId = (Id)aggregate.get('Contact__c');
contactIds.add(contactId);
tasks.add(new Task(OwnerId=ownerId, /*other fields*/));
}
insert tasks;
List<Benefit__c> benefits = [
SELECT Id FROM Benefit__c WHERE Contact__c IN :contactIds
];
for (Benefit__c benefit : benefits)
benefit.Task_Created__c = true;
update benefits;
}
public void finish(Database.BatchableContext context) { /*additional logic*/ }}
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');
}
}
}
}
}