Is it possible to add/change/delete Community members using Apex? I know how to do this via the UI (see picture below), but I'm looking to automate some things on the demo side of the business for our sales reps.
Although Salesforce says 'create' allowed on Network Member: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_networkmember.htm, but seems that not allowed using apex code. No worries, we can make a post REST call for the same:
First add your salesforce base url as remote site setting then add this code as part of your implementation:
String endpoint = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v47.0/sobjects/NetworkMemberGroup';
HttpRequest httpRequest = new HttpRequest();
httpRequest.setEndpoint(endpoint);
httpRequest.setMethod('POST');
httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
httpRequest.setHeader('Content-Type', 'application/json;charset=UTF-8');
//Change network id and profile/permission set Id
httpRequest.setBody('{"NetworkId":"0DB900000008Qga","ParentId":"00e90000001uNre"}');
Http http = new Http();
HttpResponse httpResponse = http.send(httpRequest);
A very detailed explanation is given here: https://sfdcian.com/manage-community-member-programmatically/
I feel you can simplify things using the permission set. You can give community access using permission sets.
And the best thing is we can assign permission sets using apex. Thus simplifying your work would be just assigning PS to the select user in apex.
PermissionSetAssignment psa = new PermissionSetAssignment
(PermissionSetId = communityAccessPS, AssigneeId = userId);
insert psa;
-
I don't think this technique can be used to change the sharing settings for external users to Public Read/Write. – Michael Sobczak Apr 14 '20 at 13:12
-
@MichaelSobczak but main question was how to add or remove community member via apex? And the above solution works? – Pranay Jaiswal Apr 14 '20 at 13:21
-
My mistake! I have two issues going on, both involve community settings. – Michael Sobczak Apr 14 '20 at 13:36
apex-mdapi
) - how are you creating these demo orgs? Can you run an MDAPI deployment as part of the process? – David Reed♦ Jan 13 '20 at 20:14