Some existing product code that creates ContentVersion instances is now being called from a community and the code fails with:

INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.: [NetworkId]

The ContentVersion documentation says:

Customer and Partner Portal users must also supply the NetworkId of the community in the request.

So code like this is needed where the NetworkId is set:

insert new ContentVersion(
    Title = ...,
    VersionData = ...,
    PathOnClient = ...,
    FirstPublishLocationId = ...,
    NetworkId = Network.getNetworkId()

and this does fix the problem.

But looking at other posts here e.g. Testing with Community User, getNetworkId = null it seems like in unit tests Network.getNetworkId() always returns null, including when System.runAs is used with a community user. So I assume that to have code that works for both unit tests and production I would need a method that looks something like this:

public static String getNetworkId() {
    // In tests Network.getNetworkId() returns null so use this alternative
    if (Test.isRunningTest()) {
        // If multiple memberships take newest
        for (NetworkMember m : [
                select NetworkId
                from NetworkMember
                where MemberId = :UserInfo.getUserId()
                order by Id desc
                limit 1
                ]) {
            return m.NetworkId;
        return null;
    } else {
        return Network.getNetworkId();

If you have solved this problem do share your solution.

2 Answers 2

User portalUser = getPortalUser();

// Ran as system
Id networkId = [
      SELECT NetworkId, MemberId
      FROM NetworkMember
      WHERE MemberId = :customerPortalUser.Id

System.runAs(portalUser) {
   insert new ContentVersion(
         Title = 'Title',
         PathOnClient = 'Path on client',
         VersionData = Blob.valueOf('Version Data'),
         NetworkId = networkId

There is an easier way to do that:

Network netId = [Select id from network where name = 'your portal name']

This will give you the id of the network. We can use this in the contentversion:

Contentversion cv = new contentversion();
Cv.networkId = netId.id;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .