function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Olanre AwolowoOlanre Awolowo 

Trigger for tick "customer access" by default on files when record owner changes on an record

Trigger for tick "customer access" by defaulton Files
Hello, 

I am currently having an issue, we have a custom object in salesforce named Applications. I deally when that records gets created, it gets created with Files attached to the record. Then someone internally would manually change the owner of that record to a community plus user to have ownership of that record. the issue here is, once the record owner is changed the community plus user will have access to the record as the sharing model of the object is private. the issue is that even though the record owner is owned by a community plus user they do not have access to view the files attached to that record, because i am the owner of the file and the "customer access" is not checked automatically when the record owner is changed to that community user, there will be times when the Application record will be owned by an internal user and they will have access to view the files attached to the record,. but when the record is created  by an internal person and also when an internal perosn attach a file against the record , a community user wont have access to the files even if we make them the record owner. What i am trying to build is when the application record owner is changed to a community plus user or a community user, as they do have access to the record make them see the files attached to the record too. I logged this case with Salesforce and they said the only way is to build this Via a Trigger.
Would appreciate if someone could help me please build this.

Thanks
please see screenshot below. at the moment we have to do this manually to make them see the  files attached to that record once
Best Answer chosen by Olanre Awolowo
Christan G 4Christan G 4
Hey Olanre, I hope you are well. Below is my first draft of the code for your solution. Unfortunately, I was not able to test it thoroughly since I don't have any community licenses but it seems to be working. I usually do all of my work within free DEV orgs. Even though the code seems simple, finding what attribute controlled that "Customer Access" toggle took a very long time. I had to do a lot of research and unfortunately, Salesforce's documentation regarding files wasn't very clear. What I ended up having to do was upload various documents and analyze which sharing attribute changed when I changed that customer access toggle. Based on the results, I noticed that there was one attribute called "Visibility" which would change. Whenever that Customer Access toggle was switch off, it had a value of "InternalUsers". When I switched that toggle on and it had a value of "AllUsers".

Thus, the code I written below revolves around changing the visibility attribute of file(s) associated to an Opportunity record after a specific update has occurred to it. This update being if the owner is changed and the new owner has a license of either Community or Community Plus as you requested.

You mentioned that you were using a custom object called Applications so I assume its API name would be Applications__c. Beforehand, please make sure that my assumption is correct by viewing the object's API name in Setup. In the code below, you will have to replace everywhere that states "Opportunity" with that API name.


Apex Code:
/////////////////////////////////////////////////////////////////////////
//Purpose: Automate visibility to community users when owner is changed.
//Creator: Christan Gordon
//
//Version 1.0 - Draft Code - Date: 2/14/2020
//////////////////////////////////////////////////////////////////////////

public class AppTriggerHelper {

    public static void updateSharingAppFiles (Map <Id, Opportunity> oppNewMap, Map <Id, Opportunity> oppOldMap) {
    
    //Obtains all Related/Relevant Files
    List <ContentDocumentLink> relatedFiles = [SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility 
                                               FROM ContentDocumentLink 
                                               WHERE LinkedEntityId IN :oppNewMap.keyset() AND Visibility != 'AllUsers']; 
     
        
     List <ContentDocumentLink> updateFileList = new List <ContentDocumentLink>();
        
     //Map to get user license name   
     Map <ID, User> usrInfoMap = new Map <ID, User>([SELECT ID, Profile.UserLicense.Name FROM User]);
     
     //List to Store all Opp IDs from Trigger
     List <ID> oppNewIDs = new List <ID>(oppNewMap.keyset());
        
     for (ID oneOppID : oppNewIDs) {
            
     Opportunity newOpp = oppNewMap.get(oneOppID); //Updated Record with new Owner
     Opportunity oldOpp = oppOldMap.get(oneOppID); //Previous Record with previous Owner
        
            
     if ((newOpp.OwnerId != oldOpp.OwnerId) && 
         (usrInfoMap.get(newOpp.OwnerId).Profile.UserLicense.Name == 'Community' 
         || usrInfoMap.get(newOpp.OwnerId).Profile.UserLicense.Name == 'Community Plus')) {
                
           for  (Integer i = 0; i < relatedFiles.size(); i++) {
                 
                 if (relatedFiles[i].LinkedEntityID == oneOppID) {
                     
                     relatedFiles[i].Visibility = 'AllUsers';
                     updateFileList.add(relatedFiles[i]);
                 }
             }      
            }
        }     
        if (updateFileList.size() > 0) {
                 
                 update updateFileList;
             }
    }
}
Apex Trigger:
trigger AppTrigger on Opportunity (after update) {

    OppTriggerHelper.updateSharingOppFiles(Trigger.newMap,Trigger.oldMap);
    
}
Please test and inform me if you receive any errors.

Thank you for taking the time to read this message and I look forward to hearing back from you soon!

 

All Answers

rohit chauhan 25rohit chauhan 25
It is appropriate time to make a few plans for the longer
term and it’s time to be happy. I’ve learned this submit and if I could I desire
to counsel you few fascinating issues or suggestions. Perhaps you could write subsequent articles regarding this article.
I desire to learn more issues about it!

also see
view your deal (https://tryodeal.com/view-your-deal/)
Christan G 4Christan G 4
Hi Olanre, I am currently looking into this issue and seeing if there is a way to resolve it. I don't have a lot of experience with Communities though but do have a lot of experience with Apex. I will most likely have a draft of some sort hopefully by end of today to tomorrow the latest. I will keep you posted. 

I have a few questions: 
  1. Are these community plus or community users apart of your Salesforce org or are they external users?
  2. Are these files stored as attachments to a record?
  3. Where is "customer access" checkbox located?
Olanre AwolowoOlanre Awolowo
Hi christian, 
Thanks for your help, 
your answers are:
  1. The users who uses community/community plus licences are external users (they do not have our email domain)
  2. These files are attached to a record ( A record gets created via a form and users must attach a file against it) when created it creates the record as an Salesforce Admin user profile and also the file gets created as an salesforce admin user profile
  3.  The customer "access checkbox" can be seen by screenshots below: Click a record (Lightning) see the related list (File)User-added image
After clicked on any file, click on Share as below:

User-added image

Once clicked on Share you will see a drop down named "Wo Can Access", click that and you will see "customer access"



 User-added image

The Idea i would like will be when the record changes to a communtity user, the customer access should be ticked. 


 
Christan G 4Christan G 4
Thank you so much for this! This helped greatly. I think this will be fairly simple to code but we shall see.
Olanre AwolowoOlanre Awolowo
Thanks for your help ! Appreciate a lot . Hopefully it should be a non complex one to do
Christan G 4Christan G 4
Hey Olanre, I hope you are well. Below is my first draft of the code for your solution. Unfortunately, I was not able to test it thoroughly since I don't have any community licenses but it seems to be working. I usually do all of my work within free DEV orgs. Even though the code seems simple, finding what attribute controlled that "Customer Access" toggle took a very long time. I had to do a lot of research and unfortunately, Salesforce's documentation regarding files wasn't very clear. What I ended up having to do was upload various documents and analyze which sharing attribute changed when I changed that customer access toggle. Based on the results, I noticed that there was one attribute called "Visibility" which would change. Whenever that Customer Access toggle was switch off, it had a value of "InternalUsers". When I switched that toggle on and it had a value of "AllUsers".

Thus, the code I written below revolves around changing the visibility attribute of file(s) associated to an Opportunity record after a specific update has occurred to it. This update being if the owner is changed and the new owner has a license of either Community or Community Plus as you requested.

You mentioned that you were using a custom object called Applications so I assume its API name would be Applications__c. Beforehand, please make sure that my assumption is correct by viewing the object's API name in Setup. In the code below, you will have to replace everywhere that states "Opportunity" with that API name.


Apex Code:
/////////////////////////////////////////////////////////////////////////
//Purpose: Automate visibility to community users when owner is changed.
//Creator: Christan Gordon
//
//Version 1.0 - Draft Code - Date: 2/14/2020
//////////////////////////////////////////////////////////////////////////

public class AppTriggerHelper {

    public static void updateSharingAppFiles (Map <Id, Opportunity> oppNewMap, Map <Id, Opportunity> oppOldMap) {
    
    //Obtains all Related/Relevant Files
    List <ContentDocumentLink> relatedFiles = [SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility 
                                               FROM ContentDocumentLink 
                                               WHERE LinkedEntityId IN :oppNewMap.keyset() AND Visibility != 'AllUsers']; 
     
        
     List <ContentDocumentLink> updateFileList = new List <ContentDocumentLink>();
        
     //Map to get user license name   
     Map <ID, User> usrInfoMap = new Map <ID, User>([SELECT ID, Profile.UserLicense.Name FROM User]);
     
     //List to Store all Opp IDs from Trigger
     List <ID> oppNewIDs = new List <ID>(oppNewMap.keyset());
        
     for (ID oneOppID : oppNewIDs) {
            
     Opportunity newOpp = oppNewMap.get(oneOppID); //Updated Record with new Owner
     Opportunity oldOpp = oppOldMap.get(oneOppID); //Previous Record with previous Owner
        
            
     if ((newOpp.OwnerId != oldOpp.OwnerId) && 
         (usrInfoMap.get(newOpp.OwnerId).Profile.UserLicense.Name == 'Community' 
         || usrInfoMap.get(newOpp.OwnerId).Profile.UserLicense.Name == 'Community Plus')) {
                
           for  (Integer i = 0; i < relatedFiles.size(); i++) {
                 
                 if (relatedFiles[i].LinkedEntityID == oneOppID) {
                     
                     relatedFiles[i].Visibility = 'AllUsers';
                     updateFileList.add(relatedFiles[i]);
                 }
             }      
            }
        }     
        if (updateFileList.size() > 0) {
                 
                 update updateFileList;
             }
    }
}
Apex Trigger:
trigger AppTrigger on Opportunity (after update) {

    OppTriggerHelper.updateSharingOppFiles(Trigger.newMap,Trigger.oldMap);
    
}
Please test and inform me if you receive any errors.

Thank you for taking the time to read this message and I look forward to hearing back from you soon!

 
This was selected as the best answer
Olanre AwolowoOlanre Awolowo
thanks a lot, i am trying this now, will let you know as soon as possible Olanre
Olanre AwolowoOlanre Awolowo
Tested it and it does not work. Here is my code below: public class AppTriggerHelper { public static void updateSharingAppFiles (Map oppNewMap, Map oppOldMap) { //Obtains all Related/Relevant Files List relatedFiles = [SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN :oppNewMap.keyset() AND Visibility != 'AllUsers']; List updateFileList = new List (); //Map to get user license name Map usrInfoMap = new Map ([SELECT ID, Profile.UserLicense.Name FROM User]); //List to Store all Opp IDs from Trigger List oppNewIDs = new List (oppNewMap.keyset()); for (ID oneOppID : oppNewIDs) { Application__c newOpp = oppNewMap.get(oneOppID); //Updated Record with new Owner Application__c oldOpp = oppOldMap.get(oneOppID); //Previous Record with previous Owner if ((newOpp.OwnerId != oldOpp.OwnerId) && (usrInfoMap.get(newOpp.OwnerId).Profile.UserLicense.Name == 'Customer Community Plus Login')) { for (Integer i = 0; i < relatedFiles.size(); i++) { if (relatedFiles[i].LinkedEntityID == oneOppID) { relatedFiles[i].Visibility = 'AllUsers'; updateFileList.add(relatedFiles[i]); } } } } if (updateFileList.size() > 0) { update updateFileList; } } } Steps i did is: 1. Added the code as apex class changing the API name to the correct object Application__c and also updates the user Profile.UserLicense.Name == 'Customer Community Plus Login' 2. created a record and added files to the record 3. logged into the community as the test user does not work see my screenshot Thanks Olanre
Olanre AwolowoOlanre Awolowo
Tested it and it does not work. Here is my code below:


public class AppTriggerHelper {

    public static void updateSharingAppFiles (Map <Id, Application__c> oppNewMap, Map <Id, Application__c> oppOldMap) {
   
    //Obtains all Related/Relevant Files
    List <ContentDocumentLink> relatedFiles = [SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility
                                               FROM ContentDocumentLink
                                               WHERE LinkedEntityId IN :oppNewMap.keyset() AND Visibility != 'AllUsers'];
     
       
     List <ContentDocumentLink> updateFileList = new List <ContentDocumentLink>();
       
     //Map to get user license name  
     Map <ID, User> usrInfoMap = new Map <ID, User>([SELECT ID, Profile.UserLicense.Name FROM User]);
     
     //List to Store all Opp IDs from Trigger
     List <ID> oppNewIDs = new List <ID>(oppNewMap.keyset());
       
     for (ID oneOppID : oppNewIDs) {
           
     Application__c newOpp = oppNewMap.get(oneOppID); //Updated Record with new Owner
     Application__c oldOpp = oppOldMap.get(oneOppID); //Previous Record with previous Owner
       
           
     if ((newOpp.OwnerId != oldOpp.OwnerId) &&
         (usrInfoMap.get(newOpp.OwnerId).Profile.UserLicense.Name == 'Customer Community Plus Login')) {
               
           for  (Integer i = 0; i < relatedFiles.size(); i++) {
                 
                 if (relatedFiles[i].LinkedEntityID == oneOppID) {
                     
                     relatedFiles[i].Visibility = 'AllUsers';
                     updateFileList.add(relatedFiles[i]);
                 }
             }      
            }
        }    
        if (updateFileList.size() > 0) {
                 
                 update updateFileList;
             }
    }
}

Steps i did is: 
Added the code as apex class changing the API name to the correct object  Application__c and also updates the user  Profile.UserLicense.Name == 'Customer Community Plus Login'
created a record and added files to the record
logged into the community as the test user 
does not work

see my screenshot 
Thanks 
Olanre
User-added image
Christan G 4Christan G 4

Hey Olane, thank you for your feedback. I have a few questions regarding how you tested this:

Did you do the following steps - The code I was wrote was designed to work this way:
1 - Create an application record as a non Customer Community Plus Login User first and added the files to it.
2 - After the record was created, changed the ownership of the record to a Customer Community Login Plus user.
3 - Logged in as a Customer Community Login Plus user, and see if the customer access toggle was already checked?

Or did you:
1 - Create an application record as a Customer Community Plus Login User and added the files to it.
2 - While logged in as the Customer Community Login Plus user, checked to see if the customer access toggle was already checked?

Or did you:
1 - Create an application record as a non Customer Community Plus Login User first and added the files to it.
2 - Logged in as the Customer Community Login Plus user, and see if the customer access toggle was already checked?

Based on your answer, I may have to make a few more changes to the code. Thanks in advance!

Olanre AwolowoOlanre Awolowo
Hi Christian, 
thanks for your response. The way I created the record is :
  1. created the record as a NON customer community login plus user 
  2. added the files as a NON customer community login plus user
Then I changed that record I created to a Customer community login plus user 
once changed , then I logged into the community AS the customer community login plus user. 

I had access to the record as is owned by the customer community plus user, but I could not see the files attached to the record 

I did checked the access toggle and was not enabled . 


so what I did was the same way as your question below:

1 - Create an application record as a non Customer Community Plus Login User first and added the files to it.
2 - After the record was created, changed the ownership of the record to a Customer Community Login Plus user.
3 - Logged in as a Customer Community Login Plus user, and see if the customer access toggle was already checked? (Could not see the access toggle as the community login plus user could not see files)
had to check it on my as my self and was not checked 

Olanre AwolowoOlanre Awolowo
Hi Christian, thanks for your response. The way I created the record is : 1. created the record as a NON customer community login plus user 2. added the files as a NON customer community login plus user Then I changed that record I created to a Customer community login plus user once changed , then I logged into the community AS the customer community login plus user. I had access to the record as is owned by the customer community plus user, but I could not see the files attached to the record I did checked the access toggle and was not enabled . so what I did was the same way as your question below: 1 - Create an application record as a non Customer Community Plus Login User first and added the files to it. 2 - After the record was created, changed the ownership of the record to a Customer Community Login Plus user. 3 - Logged in as a Customer Community Login Plus user, and see if the customer access toggle was already checked? (Could not see the access toggle as the community login plus user could not see files) had to check it on my as my self and was not checked
Christan G 4Christan G 4
Thank you Olane for your response. I am going to troubleshoot this issue more and see why it may not be working in my personal org. When possible, can you also copy and paste the code from your Apex trigger. Thanks in advance! I hope to have an answer by tomorrow the latest.
Christan G 4Christan G 4
Just to be sure. You created a Apex Class and an Apex Trigger correct?
Olanre AwolowoOlanre Awolowo
I copied all the code into an apex class... did not created a separate apex trigger. Just to be clear are this 2 codes? Apex class and apex trigger?
Christan G 4Christan G 4
Hi Olane, thank you for the quick response. Yes there are two components for the code. In the post with my code, you will see that there is a section which states Apex Class and another section that states Apex Trigger. Sorry for not clarifying this earlier. All the code under Apex class is supposed to go only in an Apex class. All the code under Apex Trigger is supposed to go only in an Apex Trigger. You can create an Apex Trigger vía Developer Console, by clicking on File -> New -> Apex Trigger. It will ask you to name the Apex Trigger. Put “AppTrigger” and when selecting the sObject, make sure you choose the Application object. Afterwards, copy and paste the Apex Trigger code into that section and save it. Finally, try testing again. The way how the trigger works is after an update is made to the a record within the Application object, the Apex Trigger code executes and calls the method I created from the AppTriggerHelper. It then checks the if the condition within the method and if it returns true, processes changes I specified within the code to the files belonging to those records. Without the Apex Trigger, the code within Apex Class will never get since there is no association to the Application object. The trigger creates this association. Sorry again for not clarifying this earlier. Please retest after making these changes and see what the outcome is. Hopefully, this will resolve your issues. If you still have issues, please feel free to reach out to me. Thank you again for your patience!
Christan G 4Christan G 4
When copying and pasting the Apex Trigger code, don’t copy the Opportunity part
Olanre AwolowoOlanre Awolowo
Thanks a Lot Christian. The Apex Class and Trigger Works perfectly now. I will work on the test class on my own!!
Thanks again for your help.!
I will post on here again if i need any help
Olanre
Christan G 4Christan G 4
Anytime Olanre! I am very happy that the solution I provided worked! I will be more than happy to assist if you need help with writing a test class for this. When you are ready, please feel free to mark the answer I provided with the Apex class and trigger codes as the best solution so that this issue can be marked as solved. Thanks again for your patience!
Olanre AwolowoOlanre Awolowo
Thanks. i have marked your answer you sent. if you can write the test for the apex class please do. Thanks
Christan G 4Christan G 4
Okay. I will try to have a draft of the test code by tomorrow the latest.
Christan G 4Christan G 4
Hi Olanre, I hope you are well. Thankfully, I was able to write the test class earlier than expected. I guess after writing so much code, I have become faster at doing it lol. Below is test class for you to use. It will provide you 100% coverage on the Apex Trigger, as well as, 100% coverage on the Apex Class code I written.

Please note that before deploying to Production, you must have an overall code percentage of at least 75% within your org. If you don't have at least 75%, you will not be able to migrate the code.

In the test class, you will have to replace all references of "Opportunity" with the API name of the your Application object. Also, I am not sure if your application object had required fields when creating a new record. If it does, you must mention these fields in the code or else it'll throw an exception. 

To use the code, copy and paste it into a new Apex class in Developer Consolve. Make the necessary changes mentioned above and save it. After saving it, you will see a run test button on the top right. Click on it for the test to begin. It may take awhile for the test to begin since a lot of code is being executed. After it is finished, click on the "Test' tab within Developer Console and sure that there is a check next to "TestRun". Also, ensure on the bottom right, that the test code coverage for both the trigger and class is 100%. Sorry for there being so many comments within the test code. The comments help me organize the code and ensure I fulfill all necessary steps.

If you have any questions or concerns, please feel free to reach out to me.

Apex Test Class Code:
@isTest
public class AppTriggerTest {

    @isTest static void updateSharingOppFilesTest() {
       
           //Create test NON Community user
           User regUsr = new User(LastName = 'LastName Reg',
                                  Alias = 'UsrR',
                                  Email = 'ClasstestReg@curious-fox.com',
                                  Username = 'ClasstestReg@test.com',
                                  CommunityNickname = 'ClassTestReg',
                                  ProfileId = [SELECT Id from Profile WHERE Name = 'Standard User' LIMIT 1].id,
                                  FirstName = 'Test Reg',
                                  TimeZoneSidKey = 'America/Los_Angeles', 
                                  LocaleSidKey = 'en_US',
                                  EmailEncodingKey = 'UTF-8', 
                                  LanguageLocaleKey = 'en_US'); 

             
          insert regUsr; //Temporarily commit user to the database
        
          //Create test community user
          User comUsr = new User(LastName = 'LastName Com',
                                  Alias = 'UsrC',
                                  Email = 'ClasstestCom@curious-fox.com',
                                  Username = 'ClasstestCom@test.com',
                                  CommunityNickname = 'ClassTestCom',
                                  ProfileId = [SELECT Id from Profile WHERE Name = 'Journey Assessor' LIMIT 1].id,
                                  //ProfileId = [SELECT ID from Profile WHERE Name = 'Standard Platform User'].id,
                                  FirstName = 'Test Com',
                                  TimeZoneSidKey = 'America/Los_Angeles', 
                                  LocaleSidKey = 'en_US',
                                  EmailEncodingKey = 'UTF-8', 
                                  LanguageLocaleKey = 'en_US');
        
        insert comUsr; //Temporarily commit user to database
        
        
        //Create test Opportunity records - REPLACE THIS WI
        List <Opportunity> testOpps = new List <Opportunity>();
        
        for (Integer i = 0; i < 200; i++) {
            
            //REPLACE THE CODE BELOW WITH THE FIELDS FROM YOUR APPLICATION OBJECT AND ASSIGN TEST VALUES
            testOpps.add(new Opportunity(Name = 'Test Opp #' + i,
                                         CloseDate = date.today().addDays(360),
                                         StageName = 'Prospecting',
                                         OwnerID = regUsr.id));
  
        }
        
        insert testOpps; //Temporarily commit test records to database
        
        //Create a map of old records - REQUIRED FOR TESTING!
        Map <ID, Opportunity> oldOppMap = new Map <ID, Opportunity>(testOpps);
        
        //Create list to hold test Files
        List <ContentVersion> testFile = new List <ContentVersion>();
        
        List <ContentDocumentLink> testFileLinks = new List <ContentDocumentLink>();

        for (Integer i = 0; i < 200; i++) {
                
               testFile.add(new ContentVersion(Title = 'Cats #' + i,
             				                   PathOnClient = 'Cats' + i +'.jpg',
                                               VersionData = Blob.valueOf('Test Content'),
                                               IsMajorVersion = true)); 

        }
        
        insert testFile; //Commit Temporary Files to Database
        
        List <ContentDocument> testFileDocs = [SELECT ID, Title FROM ContentDocument];
        
        System.assertEquals(200, testFileDocs.size()); //Checks to ensure that there are 200 records in the above list
        
        //Create test File Links - This controls file sharing - IMPORTANT!
        List <ContentDocumentLink> testFileLink = new List <ContentDocumentLink>();
        
        //Create test File Links
        for (Integer i = 0; i < 200; i++) {
            
            //Intentionally made Visibility = 'InternalUsers' since this untoggles Customer Access
            //If test is successful, visibility for these file links should change to 'AllUsers'
            testFileLink.add(new ContentDocumentLink(LinkedEntityID = testOpps[i].id,
                                                     ContentDocumentID = testFileDocs[i].id,
                                                     Visibility = 'InternalUsers',
                                                     ShareType = 'V'));
            
            
        }
        
        insert testFileLink; //Commit temporary file links to database
        
       
        //All necessary components configured. Perform record updates for testing
        
        //Create list to hold updated records
        List <Opportunity> updatedTestOpps = new List <Opportunity>();
        
        for (Opportunity oneTestOpp : testOpps) {
            
            oneTestOpp.OwnerID = comUsr.id;
            updatedTestOpps.add(oneTestOpp);  
            
        }
        
        //Initiate Testing
        System.Test.startTest();
        update updatedTestOpps; //This will provide test coverage for Apex trigger
        
        //Create Map for new updated Records - REQUIRED FOR TESTING!
        Map <ID, Opportunity> newOppMap = new Map <ID, Opportunity>(updatedTestOpps); 
        
        OppTriggerHelper.updateSharingOppFiles(newOppMap,oldOppMap); //This will provide test coverage for Apex Class method
    
        
        //End Testing
        System.Test.stopTest();
        
        //Evaluate Testing Results
        
        //Queries all related file Links associated with test Opp Records
        List <ContentDocumentLink> relatedTestFiles = [SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility 
                                               	   	   FROM ContentDocumentLink 
                                                       WHERE LinkedEntityId IN :newOppMap.keyset() AND Visibility != 'AllUsers']; 
        
        //In the SOQL above, I filtered file links on those that had Visibility not equal to 'AllUsers'
        //However, if the test code changed the visibility of all those file links from 'InternalUsers' to 'AllUsers' 
        //Then, this SOQL should have 0 records within it. Thus, this ensures that testing was a success!
        System.assertEquals(true, relatedTestFiles.size() == 0);
           
    }
    
}
Olanre AwolowoOlanre Awolowo
Thanks for the code provided 
i got stuck in this section: 
testOpps.add(new Opportunity(Name = 'Test Opp #' + i,
046                                         CloseDate = date.today().addDays(360),
047                                         StageName = 'Prospecting',
048                                         OwnerID = regUsr.id));





I reppaced my code with the below:

 testOpps.add(new Application__c(first Name = 'Test Opp #' + i, 
                                             Last Name = 'JeremyTest',
                                             Email = 'Jeremy@test.com', 
                                             OwnerID = regUsr.id));

was not getting why the error came up



User-added image

Olanre
 
Christan G 4Christan G 4
Good Morning Olanre, I hope you are well. I believe the reason this error is coming up is due to not putting the correct API name. In your org, go to Setup and search, “objects” in the quick find search box on the left. Then, click on “Object Manager”. You’ll see a list of objects. Click on the Application object. Then, click on the “Fields & Relationship” tab. You will see two sections. One called Field Label and another called “Field Name”. The system refers to the Field Names associated with the Field Label. Thus, we have to use those instead of Field Label. The field labels only represent what is shown to the user on the screen when viewing a record. Replace the fields mentioned with their associated field name in the code. This should hopefully resolve your issue.
Arthur Affonso SahibArthur Affonso Sahib
Hi guys! 
I want to use this amazing code you guys come up with for my cases object. Basically I need my customer community users to be able to see files related to cases. 
I adapted the code for the cases object but I have a question: could this code be for: everytime the contact name is a customer community user, to toggle the customer access to the files related to the record? 
I'm sorry, I'm very bad at coding, that's why I am asking here.

Thanks in advance :) 
Christan G 4Christan G 4
Hi Arthur, I am glad that the code I provided was able to help your use case as well. In regards to your question, yes the code can be adapted for the contact criteria you mentioned.

How are contacts identified as a customer community user in your org? Is there a picklist or checkbox field which indicates that?
Arthur Affonso SahibArthur Affonso Sahib
Hi Christian! Yes, there is a checkbox field that indicates that. Could you help me adapt the code to this criteria? :) 
The new code I have is like this:

Apex Code:
public class AppTriggerHelper {

    public static void updateSharingAppFiles (Map <Id, Case> caseNewMap, Map <Id, Case> caseOldMap) {
    
    //Obtains all Related/Relevant Files
    List <ContentDocumentLink> relatedFiles = [SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility 
                                               FROM ContentDocumentLink 
                                               WHERE LinkedEntityId IN :caseNewMap.keyset() AND Visibility != 'AllUsers']; 
     
        
     List <ContentDocumentLink> updateFileList = new List <ContentDocumentLink>();
        
     //Map to get user license name   
     Map <ID, User> usrInfoMap = new Map <ID, User>([SELECT ID, Profile.UserLicense.Name FROM User]);
     
     //List to Store all Case IDs from Trigger
     List <ID> caseNewIDs = new List <ID>(caseNewMap.keyset());
        
     for (ID oneCaseID : caseNewIDs) {
            
     Case newCase = caseNewMap.get(oneCaseID); //Updated Record with new Owner
     Case oldCase = caseOldMap.get(oneCaseID); //Previous Record with previous Owner
        
            
     if ((newCase.OwnerId != oldCase.OwnerId) && 
         (usrInfoMap.get(newCase.OwnerId).Profile.UserLicense.Name == 'Community' 
         || usrInfoMap.get(newCase.OwnerId).Profile.UserLicense.Name == 'Community Plus')) {
                
           for  (Integer i = 0; i < relatedFiles.size(); i++) {
                 
                 if (relatedFiles[i].LinkedEntityID == oneCaseID) {
                     
                     relatedFiles[i].Visibility = 'AllUsers';
                     updateFileList.add(relatedFiles[i]);
                 }
             }      
            }
        }     
        if (updateFileList.size() > 0) {
                 
                 update updateFileList;
             }
    }
}


Apex Class:
trigger AppTrigger on Case (after update) {

    AppTriggerHelper.updateSharingAppFiles(Trigger.newMap,Trigger.oldMap);
    
}


Thanks in advance.

 
Christan G 4Christan G 4
Hi Arthur and sure! I just want to ensure that I understand your org's data model and use case before I proceed. I know you mentioned that there is a checkbox on the Contacts object that indicates whether a contact is a Community Plus Member or not. However, I am having difficulty to seeing how these contacts are associated to the records with the files that you want to expose. 

When possible can you provide me with an example use case scenario to see how these records correspond to one other and what is it you want to achieve in the end. It doesn't have to be elaborate.

Thanks so much for your reply and look forward to hearing back from you soon!
rohit chauhan 25rohit chauhan 25
Hello! This is kind of off-topic but I need some help from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any ideas or suggestions? Thank you dnf codes for gta 5 (https://promocodedeal.com/dnf-codes-for-gta-5/)
rohit chauhan 25rohit chauhan 25

Hello there, You have done a great job. I will definitely digg it and personally suggest it to my friends. I’m confident they’ll be benefited from this website. Visit Our Site At:

Clash Of Clan Codes (https://promocodedeal.com/clash-of-clan-codes/)

Simone RiccoSimone Ricco
Hi Christan, I think this code is the solution to my problem. But I need to shape it and I don’t know if it will be feasible. My end result will be that Administrator users, must publish files within the Salesforce Libraries (ContentDocument) and automatically the file must be shared and visible to users with Community Profile. Unfortunately I don’t have an object to define as Opportunity or in the case of Olanre a custom "application". Can this code work if properly modeled ?
Thank
Christan G 4Christan G 4
Good Morning Simone, I hope you are well. It should be possible to customize the code for your use case. I just want to make sure I understand the requirement fully before investigating more. To confirm, you want when an Administrator publishes a file within a Salesforce Library, that file must be automatically shared and visible to users with a Community profile license? If yes, it is possible for an Admin to unpublish a file and when that occurs, should that file be automatically unshared and not visible to the community users?