+ Start a Discussion
Kumar GKumar G 

Attachment functionality is not working in Lightning

While saving the case record attachment will not attached to the case record , please find the component code in code sample and suggest me.
Component Code :

<aura:component controller="ctssupportform" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction">
    
    <aura:attribute name="pageHeading" type="string" default="CEP Helpdesk"/>
    <aura:attribute name="userCreation"  type="boolean" default="false"/>
    <aura:attribute name="UserTermination" type="boolean" default="false"/>
    <aura:attribute name="updatePermission" type="boolean" default="false"/>
    <aura:attribute name="isDataSubmitted" type="Boolean" default="true" />
    <aura:attribute name="Isforsecond" type="Boolean" default="false"/> 
    <aura:attribute name="radioSelect" type="String" default=""/> 
    <aura:attribute name="Nxtbuttonvalidate" type="boolean" default="false"/>   
    <aura:attribute name="frameWidth" type="String" default="200" /><!--250-->
    <aura:attribute name="frameHeight" type="String" default="80" /><!--30-->  
    <aura:attribute name="recordId" type="Id" default="'sobjectType':'attachment','Id':''"/>
    
    <!-- Needed to send messages to VF page. But we will get it from VF itself -->
    <aura:attribute name="vfHost" type="String" default="" />
    <!-- Domain of LC for VF to send message -->
    <aura:attribute name="lcHost" type="String" />
    <aura:attribute name="body" type="string" default=""/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <aura:attribute name="frameSrc" type="String" />
    
    
    
    <aura:attribute name="applicationdata" type="string[]" default="--None--,Please select an application,
                                                                    CTS,
                                                                    Support-ECOs,
                                                                    Knowledge Base,
                                                                    Lithium(Community),
                                                                    Support-LMS,
                                                                    My net,
                                                                    Support Site,
                                                                    Yapper,
                                                                    Support-IVR or dial tone call Routing,
                                                                    Support-Telco line Issue,
                                                                    Support-Others,
                                                                    Support-User Creation,
                                                                    Support-User Termination,
                                                                    Support-User Update Permissions,Chat"/>
    
    <aura:attribute name="urgdata" type="string[]" default="Low,Medium,High"/>
    <aura:attribute name="Impactdata" type="string[]" default="Low,Medium,High"/>
    <aura:attribute name="casedata" type="Case" default="{'sobjectType':'Case'}"/>
    <aura:attribute name="options" type="List" default="[
                                                        {'label': 'I want to report a down time with an application', 'value': 'I want to report a down time with an application'},
                                                        {'label': 'I want to request a new user account / update permissions to an existing account/terminate an existing account', 'value': 'I want to request a new user account / update permissions to an existing account/terminate an existing account'},
                                                        {'label': 'I want to report a bug / issue', 'value': 'I want to report a bug / issue'},
                                                        {'label': 'I want to request a new report', 'value': 'I want to request a new report'},
                                                        {'label': 'I want to request a new functionality / project', 'value': 'I want to request a new functionality / project'},
                                                        {'label': 'I want to report a telco issue', 'value': 'I want to report a telco issue'},
                                                        {'label': 'I want to request technical assistance', 'value': 'I want to request technical assistance'}]"
                    />
    
    <aura:handler event="aura:waiting" action="{!c.waiting}"/>
    <aura:handler event="aura:doneWaiting" action="{!c.doneWaiting}"/>
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">
                    <div class="slds-media">
                        <div class="slds-media__figure">
                            <span class="slds-icon_container slds-icon-standard-opportunity" title="Description of icon when needed">
                                
                            </span>
                        </div>
                        <div class="slds-media__body">
                            <h1 class="slds-page-header__title slds-truncate slds-align-middle" title="Rohde Corp - 80,000 Widgets">{!v.pageHeading}</h1>
                            
                        </div>
                    </div>
                </div>
                
            </div>
            
            <br/><br/>
            <div class="slds-align--absolute-center">
                <div class="slds-size--3-of-8">
                    
                    <!-- <lightning:accordion activeSectionName="Page1">
          <lightning:accordionSection name="page1" label="Select the type of ticket:">-->
                    <lightning:radioGroup aura:id="mygroup" name="radioButtonGroup" label="" options="{! v.options }" value="{! v.casedata.Type_Of_Ticket__c}" onchange="{!c.handleChange }">  </lightning:radioGroup><br/>
                    
                    <div class="setcolorwhite">
                        <lightning:select label="Please select one Applications" name="mySelect" value="{!v.casedata.Applications__c}" aura:id="mySelect" class="labelcolor"  onchange="{!c.toggle}">
                            <aura:iteration items="{!v.applicationdata}" var="appl" >
                                <option value="{!appl}" text="{!appl}"/>
                            </aura:iteration>
                        </lightning:select>
                    </div>
                    
                    //Excel form will display based on the picklist value
                    <aura:if isTrue="{!and(v.options, v.userCreation)}">
                        <div aura:id="Support-User Creation" class="slds-grid slds-wrap slds-p-vertical_medium">
                            <span class="excel_format" style="display:inline;">
                                <a href='https://help.net-support.com/User_Management_template_version1.0.xlsx' target="_blank">Download sample and attach to ticket</a>
                            </span>
                        </div>
                    </aura:if>
                    
                    <aura:if isTrue="{!and(v.options, v.UserTermination)}">
                        <div aura:id="Support-User Termination" class="demo-only demo-only--sizing slds-grid slds-wrap slds-p-vertical_medium">
                            <span class="excel_format" style="display:inline;">
                                <a href='https://help.net-support.com/User_Management_template_version1.0.xlsx' target="_blank">Download sample and attach to ticket</a>
                            </span>
                        </div>
                    </aura:if>
                    <aura:if isTrue="{!and(v.options, v.updatePermission)}">
                        <div aura:id="Support-User Update Permissions" class="demo-only demo-only--sizing slds-grid slds-wrap slds-p-vertical_medium">
                            <span class="excel_format" style="display:inline;">
                                <a href='https://help.net-support.com/User_Management_template_version1.0.xlsx' target="_blank">Download sample and attach to ticket</a>
                            </span>
                        </div>
                    </aura:if>
                    
                    <div class="slds-m-top_large">
                        <lightning:button type="button" class="slds-button slds-button_brand" label="NEXT" onclick="{!c.nextButtonClickHandler}"/>
                    </div>  
                    
                    
                    <!--<lightning:accordionSection name="page2" label="Please fill out the following form :">-->
                    <aura:if isTrue="{!v.Isforsecond}">
                        <lightning:input label="Subject" name="myname" value="{!v.casedata.Subject}"/>
                        
                        <lightning:select label="Urgency" name="urgency" value="{!v.casedata.Urgency__c}">
                            <aura:iteration items="{!v.urgdata}" var="urg">
                                <option value="{!urg}" text="{!urg}"/>
                            </aura:iteration>
                        </lightning:select>
                        
                        <lightning:select label="Impact" name="impact" value="{!v.casedata.Impact__c}">
                            <aura:iteration items="{!v.Impactdata}" var="imd">
                                <option value="{!imd}" text="{!imd}"/>
                            </aura:iteration>
                        </lightning:select>
                        
                        <lightning:input label="Description" name="string" value="{!v.casedata.Description}"/>       
                        <lightning:input label="Justification" name="justify" value="{!v.casedata.Justification__c}"/><br/>
                        
                        <div class="file-upload">
                            <div aura:id="uiMessage">{!v.body}</div>
                            <iframe aura:id="vfFrame" src="{!v.frameSrc}" width="{!v.frameWidth}" height="{!v.frameHeight}" class="vfFrame" frameBorder="0"  scrolling="no"/>
                        </div>
                        <div class="slds-m-top_large">
                            <lightning:button type="button" class="slds-button slds-button_brand" label="next" onclick="{!c.handleFormSubmit}" disabled="true" aura:id="uploadFileButton"/>
                        </div>
                        
                           <div class="slds-m-top_large">
                            <p><lightning:button iconName="utility:Submit" class="slds-button slds-button_brand" label="Submit" variant="border-filled" onclick="{!c.doSubmit}"/></p>
                            <br/>
                        </div>
                    </aura:if>  
                    
                    
                </div>
                
                
            </div>
        </div>
    </div>
    
</aura:component>

Controller :

({
		doSubmit : function(cmp, evt, hlpr) {
		//  call apex function SaveRegistrationDetail to save data in reg form 
		//  also we have to pass RegForm as a parameter
		var casedata = cmp.get("v.casedata");
        
         // create a one-time use instance of the SaveRegistrationDetail action
        // in the server-side controller
        var action = cmp.get("c.Savesupportform");
            
        action.setParams({ casedata  : casedata });

        // Create a callback that is executed after 
        // the server-side action returns
        action.setCallback(this, function(response) {
            var state = response.getState();
             if (state === "SUCCESS") {
                // Alert the user with the value returned 
                // from the server
                          cmp.set("v.isDataSubmitted", 'True');
                          var parentId = response.getReturnValue();
                          cmp.set("v.RegistrationRecordId",parentId);
                               alert('Record created succesfully'+''+ parentId);
                         				
                           }
           
            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 adds the server-side action to the queue.
        var radio=cmp.get('c.handleChange');
            
        $A.enqueueAction(action,radio);  
                      
	},
    
    handleClick : function (component ,event,helper){
        
        var nxtbtnonRadio=component.get("v.options");
        var nxtbtonSelect=component.find("mySelect");
        
        var nxtSelect=nxtbtonSelect.get("v.value");
           
        if(nxtbtnonRadio != null && nxtSelect.trim() != null ){
            component.set("isDataSubmitted", true);
        }
       
    },
    
    handleChange: function (cmp, event) {
        var changeValue = event.getParam("value");
        console.log("On change : "+changeValue);
        cmp.set("v.radioSelect", changeValue);
        alert(changeValue);       
		//var actn=component.get("c.handleClick");
           //actn.$meth$();
                
    },
    
   toggle: function (component, event, helper) {
    
    var sel = component.find("mySelect");
    var nav = sel.get("v.value");
    
    if (nav.trim() == "Support-User Creation") {
    component.set("v.userCreation", true);
      
        }
        else{
            component.set("v.userCreation", false);
        }
        if(nav.trim() == "Support-User Termination"){
        component.set("v.UserTermination", true);
       }
        else{
            component.set("v.UserTermination", false);
        }
         if(nav.trim() == "Support-User Update Permissions"){
                component.set("v.updatePermission" , true);
            }
        else{
            component.set("v.updatePermission" , false);
        }
    },
    
    nextButtonClickHandler : function(component, event, helper){
    var sel = component.find("mySelect");
    var nav = sel.get("v.value");
        if(nav !== '--None--' && component.get("v.radioSelect") !== '') {
            component.set("v.Isforsecond", true);  
        }
    },
    
    doInit : function(component, event, helper) {
        
        //Send LC Host as parameter to VF page so VF page can send message to LC; make it all dynamic
        component.set('v.lcHost', window.location.hostname);

        var frameSrc = '/apex/UploadFilePage?id=' + component.get('v.recordId') + '&lcHost=' + component.get('v.lcHost');
        console.log('frameSrc:' , frameSrc);
        component.set('v.frameSrc', frameSrc);

        //Add message listener
        window.addEventListener("message", function(event) {

            console.log('event.data:', event.data);

            // Handle the message
            if(event.data.state == 'LOADED'){
                //Set vfHost which will be used later to send message
                component.set('v.vfHost', event.data.vfHost);
                alert('file loaded');
            }

            if(event.data.state == 'uploadFileSelected'){
                component.find('uploadFileButton').set('v.disabled', false);
                alert('upload file selected');
                
            }

            if(event.data.state == 'fileUploadprocessed'){
                var uiMessage = component.find('uiMessage');
                //Disable Upload button until file is selected again
                component.find('uploadFileButton').set('v.disabled', true);
                alert('file upload is true');

          $A.createComponents([
                        ["markup://ui:message",{
                            "body" : event.data.message,
                            "severity" : event.data.messageType,
                        }]
                    ],
                    function(components, status, errorMessage){
                       alert('create component');
                        if (status === "SUCCESS") {
                            var message = components[0];
                            // set the body of the ui:message to be the ui:outputText
                            component.find('uiMessage').set("v.body", message);
                        }
                        else if (status === "INCOMPLETE") {
                            console.log("No response from server or client is offline.")
                            // Show offline error
                        }
                        else if (status === "ERROR") {
                            console.log("Error: " + errorMessage);
                            // Show error message
                        }
                    }
                );
            }
        }, false);
    },
    sendMessageone: function(component, event, helper) {
        //Clear UI message before trying for file upload again
        component.find('uiMessage').set("v.body",[]);

        //Prepare message in the format required in VF page
        var message = {
            "uploadFile" : true
        } ;
        //Send message to VF
        var sndmsg=component.set("v.sendmsg", true);
       
        helper.sendMessage(component, message);
    },
    setIframeCaseId : function(component, event, helper) {
        component.set("v.formSubmitStatus", "");
        var message = {
            "recordId" : event.target.value
        };
        helper.sendMessage(component, helper, message);
    },
    handleFormSubmit: function(component, event, helper) {
        alert('file is uploading');
        console.log('file is uploading');
        var message = {
            "uploadFile" : true
        };
        helper.sendMessage(component, helper, message);
    }
})

Helper :

({
    
    sendMessage: function(component, helper, message){
        alert('send message1');
        //Send message to VF
        message.origin = window.location.hostname;
        var vfWindow = component.find("vfFrame").getElement().contentWindow;
        vfWindow.postMessage(message, component.get("v.vfHost"));
        console.log('file load data' , vfWindow);
		},