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
Jeff GillisJeff Gillis 

Linking ContentDocuments to Products

I am looking to associate ContentDocuments to Product2 records based on values in the ContentVersion record. For example I am uploading a new File record in Salesforce that is a document about Product A. When the record is created it will create a ContentDocument and ContentVersion. In the ContentVersion there are two custom fields called "Product Family" and "Product Type". On Product2 there are also two custom fields called "Product Family" and "Product Type".
I would like to create a ContentDocumentLink record that links the document to the product if the fields match up.
The apex trigger that I am writing right now is as follows (I'm new to Apex!)
 
trigger documentLinking on ContentVersion (after insert, after update) {

//Build a list of ContentVersion Ids that do not have a blank Product Family or Product Type for records in trigger.new
List<Id> listOfContentVersionId = new List<Id>();
List<String> listOfProductFamily = new LIst<String>();
List<String> listOfProductType = new List<String>();
for(ContentVersion cv : Trigger.new) {
    if(cv.Product_Family__c != null && cv.Product_Type__c != null)
    {
        listOfContentVersionId.add(cv.Id);
        listOfProductFamily.add(cv.Product_Family__c);
        listOfProductType.add(cv.Product_Type__c);

        System.debug('List size' + strings.size());
    }
}

if(listOfContentVersionId.size()>0)
{
    //Query for Product records that have the same Product Family and Product Type as the document that is being added/updated
    List<String> matchingProducts =    [SELECT Id
                                        FROM Product2
                                        WHERE Product_Family__c = :cv.Product_Family__c
                                        AND Product_Type__c = :cv.Product_Type__c];

                                        System.debug('List size' + strings.size());
}

//Pull in the matching Product records to then create a ContentDocumentLink record to them
for(Product p : matchingProducts){
    ContentDocumentLink cdl = new ContentDocumentLink   (ContentDocumentId = cv.ContentDocumentId,
                                                        LinkedEntityId = matchingProducts.Id,
                                                        ShareType = 'V');


insert p; 
}

}