How to create an Account Share Record?
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'); Listaccounts = Database.query(query) ; List Any help?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;
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;