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
Vani KumariVani Kumari 

Aura component with Dynamic search functionality with Preview and Hyperlink options

Hello Guys

I need a small help, I am trying to design an aura component for my client where he needs to access the content documents while creating the new case, I have overridden the button and tried to show the aura component with Dynamic search functionality, Now my Issue is that when i search with the keyword,  I am not getting the documents with Preview and hyperlink options,I have referred several website links but could not find the solution

https://sfdcmonkey.com/2018/10/29/open-files-lightning-component/

https://www.forcetalks.com/blog/implementation-of-dynamic-search-in-lightning-component/

My Component
 
<aura:component controller="FilesListApexController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:actionOverride" access="global">
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchListOfRecordTypes}"/>
    
    <aura:attribute name="lstOfRecordType" type="String[]" />
    <aura:attribute name="isOpen" type="boolean" default="false" />
    <div style="font-size: 30px;">
    <div class="slds-align_absolute-center">Welcome to the Case Portal</div>
    </div>
     <h1 class="slds-page-header__title slds-m-right_small slds-align-middle slds-truncate"  title="Case Help Documents">Please click the below button to create a New Case</h1>
  <div class="slds-m-around--x-large">
    <lightning:button label="Create a Case" onclick="{!c.openModal}" />
  </div>   
    
    <h1 class="slds-page-header__title slds-m-right_small slds-align-middle slds-truncate"  title="Case Help Documents">Case Help Documents</h1>
   <!-- Model Box Start -->    
    <aura:if isTrue="{!v.isOpen}">
        <div role="dialog" tabindex="-1" aria-labelledby="header43" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <div class="slds-modal__header">
                    <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="{!c.closeModal}">
                        X<span class="slds-assistive-text">Cancel</span>
                    </button>
                    <h2 id="header43" class="slds-text-heading--medium">New Case</h2>
                </div>
                
                <div class="slds-modal__content slds-p-around--medium">
                    <div class="slds-grid slds-wrap">
                        <div class="slds-size--1-of-2 slds-large-size--1-of-2">
                             <div class="slds-align--absolute-center">Select a Record Type</div>                            
                        </div>
                        <div class="slds-size--1-of-2 slds-large-size--1-of-2">
                            <ui:inputSelect aura:id="selectid">
                                <aura:iteration items="{!v.lstOfRecordType}" var="Cases__c">                            
                                    <ui:inputSelectOption text="{!Cases__c}" label="{!Cases__c}"  />
                                </aura:iteration>
                            </ui:inputSelect>
                        </div>&nbsp; &nbsp;
                    </div>                  
                </div>
                
                <div class="slds-modal__footer">
                    <lightning:button class="slds-button slds-button--neutral" onclick="{!c.closeModal}">Cancel</lightning:button>
                    <lightning:button class="slds-button slds-button--brand" onclick="{!c.createRecord}">Next</lightning:button>
                </div>
            </div>
        </div>
        <div class="slds-backdrop slds-backdrop--open"></div>
    </aura:if>
    
    <aura:attribute name="Documents" type="List" />
    <aura:attribute name="key" type="String" /> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />        
    <lightning:input type="text" name="searchKey" aura:id="searchKey" onchange="{!c.searchKeyChange}" placeholder="Search" />          
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
        <thead>
            <tr class="slds-text-heading_label">              
                <th scope="col"><div class="slds-truncate" title="Name">Title</div></th>
                <th scope="col"><div class="slds-truncate" title="File Type">FileType</div></th>         
                <th scope="col"><div class="slds-truncate" title="Created By">Created By</div></th>            
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.Documents}" var="Document">
                <tr>  
                    <td><div class="slds-truncate" title="{!Document.Title}">{!Document.Title}</div></td>
                    <td><div class="slds-truncate" title="{!Document.Type}">{!Document.FileType}</div></td>                   
                    <td><div class="slds-truncate" title="{!Document.CreatedBy.Name}">{!Document.CreatedBy.Name}</div></td>                    
                </tr>
            </aura:iteration>
        </tbody>
    </table>    
    
    <aura:if isTrue="{!v.hasModalOpen}">
        <section onclick="{!c.closeModel}"
                 role="dialog"
                 aria-modal="true"
                 class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <div class="slds-modal__content slds-p-around_medium slds-text-align_center"
                     style="background: transparent;">
                    <div style="width: 50%; margin: 0 auto; text-align: left">
                        <!--<lightning:fileCard> to preview file using content document Id -->
                        <lightning:fileCard fileId="{!v.Documents}"/>
                    </div>
                </div>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </aura:if>
    
    
</aura:component>

My Controller
 
({
    
    /* On the component Load this function call the apex class method,
    * which is return the list of RecordTypes of object
    * and set it to the lstOfRecordType attribute to display record Type values
    * on ui:inputSelect component. */
    
    fetchListOfRecordTypes: function(component, event, helper) {
        var action = component.get("c.fetchRecordTypeValues");
        action.setCallback(this, function(response) {
            component.set("v.lstOfRecordType", response.getReturnValue());
        });
        $A.enqueueAction(action);
    },
    
    /* In this "createRecord" function, first we have call apex class method
    * and pass the selected RecordType values[label] and this "getRecTypeId"
    * apex method return the selected recordType ID.
    * When RecordType ID comes, we have call  "e.force:createRecord"
    * event and pass object API Name and
    * set the record type ID in recordTypeId parameter. and fire this event
    * if response state is not equal = "SUCCESS" then display message on various situations.
    */
    createRecord: function(component, event, helper) {
        component.set("v.isOpen", true);
        
        var action = component.get("c.getRecTypeId");
        var recordTypeLabel = component.find("selectid").get("v.value");
        action.setParams({
            "recordTypeLabel": recordTypeLabel
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var createRecordEvent = $A.get("e.force:createRecord");
                var RecTypeID  = response.getReturnValue();
                createRecordEvent.setParams({
                    "entityApiName": 'Cases__c',
                    "recordTypeId": RecTypeID
                });
                createRecordEvent.fire();
                
            } else if (state == "INCOMPLETE") {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Oops!",
                    "message": "No Internet Connection"
                });
                toastEvent.fire();
                
            } else if (state == "ERROR") {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Error!",
                    "message": "Please contact your administrator"
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);
    },
    
    closeModal: function(component, event, helper) {
        // set "isOpen" attribute to false for hide/close model box
        component.set("v.isOpen", false);
    },
    
    openModal: function(component, event, helper) {
        // set "isOpen" attribute to true to show model box
        component.set("v.isOpen", true);
    },
    
    doInit: function(component, event, helper) {
        helper.getDocumentList(component);
    },
    searchKeyChange: function(component, event) {
        var searchKey = component.find("searchKey").get("v.value");
        console.log('searchKey:::::'+searchKey);
        var action = component.get("c.findByTitle");
        action.setParams({
            "searchKey": searchKey
        });
        action.setCallback(this, function(a) {
            component.set("v.Documents", a.getReturnValue());
        });
        $A.enqueueAction(action);
    },   
     getSelected : function(component,event,helper){
        // display modle and set seletedDocumentId attribute with selected record Id   
        component.set("v.hasModalOpen" , true);
        component.set("v.Documents" , event.currentTarget.getAttribute("data-Id")); 
        
    },
    closeModel: function(component, event, helper) {
        // for Close Model, set the "hasModalOpen" attribute to "FALSE"  
        component.set("v.hasModalOpen", false);
        component.set("v.Documents" , null); 
    },
    
    doInit : function(component, event, helper) {
        var action = component.get("c.getDocuments");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.Documents', response.getReturnValue());
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
                else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
        });
        $A.enqueueAction(action);  
    },
    getSelected : function(component,event,helper){
        // display modle and set seletedDocumentId attribute with selected record Id   
        component.set("v.hasModalOpen" , true);
        component.set("v.Documents" , event.currentTarget.getAttribute("data-Id")); 
        
    },
    closeModel: function(component, event, helper) {
        // for Close Model, set the "hasModalOpen" attribute to "FALSE"  
        component.set("v.hasModalOpen", false);
        component.set("v.Documents" , null); 
    },
    
})

My Helper
 
({      
    getDocumentList: function(component) {
        var action = component.get('c.getDocuments');
        var self = this;
        action.setCallback(this, function(actionResult) {
            component.set('v.Documents', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})

My Apex codee
 
public class FilesListApexController {
    
    @AuraEnabled
    public static Cases__c getsharechatcases(String recordId){
        Cases__c c = [SELECT Id,Name,Status__c,Parent_cases__c,OwnerId,Priority__c,Email__c,
                      RecordTypeId,Problem_Description__c,Internal_comments__c,Asset_category__c,Case_closed_date__c,Other_Software_Details__c FROM Cases__c WHERE Id =: recordId];
        return c;
    }
    public static Map<Id, String> recordtypemap {get;set;}
    
   @AuraEnabled        
    public static List<String> fetchRecordTypeValues(){
        List<Schema.RecordTypeInfo> recordtypes = Cases__c.SObjectType.getDescribe().getRecordTypeInfos();    
        recordtypemap = new Map<Id, String>();
        for(RecordTypeInfo rt : recordtypes){
            if(rt.getName() != 'Master')
            recordtypemap.put(rt.getRecordTypeId(), rt.getName());
        }        
        return recordtypemap.values();
    }
    
    @AuraEnabled
    public static Id getRecTypeId(String recordTypeLabel){
        Id recid = Schema.SObjectType.Cases__c.getRecordTypeInfosByName().get(recordTypeLabel).getRecordTypeId();        
        return recid;
    }
    @AuraEnabled
    public static List <contentDocument> getDocuments(Id arecordId) {
        List<ContentDocumentLink> CDLs = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :arecordId];
        if (CDLs.size() < 1) return new List<ContentDocument>(); 

        // Make a List of ContentDocument IDs
        List <Id> CDIdList = new List <Id> ();
        for (ContentDocumentLink nextCDL : CDLs) {
            CDIdList.add(nextCDL.ContentDocumentId); }        

        List<ContentDocument> entries = [SELECT Id, Title, FileType FROM ContentDocument WHERE ContentDocument.Id IN :CDIdList];
        return entries;
    }
        
    @AuraEnabled
    public static List<contentDocument> findByTitle(String searchKey) {
        String Title =  + searchKey + '%';
        List<contentDocument> DocList = [Select id,Title,FileType,CreatedBy.Name,ContentSize From contentDocument WHERE Title LIKE :Title];
        return DocList;
    }
}

My Error Snapshot

User-added imageI need Preview, hyperlink, and download options just like we do in the files object​​​​​​​
 
Abhishek BansalAbhishek Bansal
Hi Vani,

Did you tried anything to make this work? If Yes, then please let us know what issue you are facung with that code. If not, then you can simply click on the preview button and check the URL which saleforce use to preview the files. 
You can try to generate the same URL and use it in your component. Let me know if you need some more details on this.

Thanks,
Abhishek Bansal.