How to create an Account Share Record?

246    Asked by elonji_3393 in Salesforce , Asked on May 12, 2023

 I have a requirement to create sharing records for accounts. But When i try to create AccountSHare record it gives me an error DML Operation not allowed.

Here is the code

String query =' Select Id FROM Account WHERE '+String.join(whereClause,'AND'); List accounts = Database.query(query) ; List share = new List(); for(Account a:accounts){ AccountShare accountShare = new AccountShare(); accountShare.AccountId = a.Id; accountShare.UserOrGroupId = groupId; accountShare.AccountAccessLevel = 'Edit'; accountShare.ContactAccessLevel = 'Edit'; accountShare.OpportunityAccessLevel = 'Edit'; share.add( accountShare); } insert share;
Any help?

Answered by Ella Clarkson
My first suggestion would be to modify String.join(whereClause,'AND') to String.join(whereClause,' AND ') [adding spaces before and after AND] otherwise your where clause would yield 'WHERE Id = IdANDName = NameANDField__c = FieldMy second suggestion would be to add accountShare.CaseAccessLevel = 'Edit'; to your record since AccountShare has all four
String query = 'SELECT Id FROM Account WHERE ' + String.join(whereClause,' AND '); List accounts = Database.query(query); List share = new List(); for(Account acc : accounts){ AccountShare accountShare = new AccountShare(); accountShare.AccountId = acc.Id; accountShare.UserOrGroupId = groupId; accountShare.AccountAccessLevel = 'Edit'; accountShare.ContactAccessLevel = 'Edit'; accountShare.CaseAccessLevel = 'Edit'; accountShare.OpportunityAccessLevel = 'Edit'; share.add(accountShare); } insert share;

Your Answer

Interviews

Parent Categories