1

My code generates the 'ui:inputText' components dynamically using $A.createComponent.

But i am not able to get the value of this dynamically generated text field in Client Side Controller, it gives below error

uncaught Action failed: c$ApplicationCreationComponentForm$controller$createApplication [TypeError: Cannot read property 'get' of undefined]

Please suggest on this.

COMPONENT CODE :

<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system.min.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system-ltng.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system-ltng.min.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system-scoped.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system-scoped.min.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system-vf.css"/>
<ltng:require styles="/resource/SLDS090/assets/styles/salesforce-lightning-design-system-vf.min.css"/>

<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
 <aura:attribute name="courseName" type="String" />
<aura:attribute name="courseId" type="String" />
<!--<aura:attribute name="AttachmentCounter" type="Integer" default="2"/>-->


<div class="container">
    <form class="slds-form--stacked">

             <div class="slds-form-element" >
                <div class="slds-form-element__control">
                    <ui:inputText aura:id="applicationName" placeholder="Application Name"
                                  class="slds-input"  value="" />
                </div>
            </div>  
            <div class="slds-form-element slds-is-disabled" >
                <div class="slds-form-element__control">
                    <ui:outputText aura:id="courseName" 
                                   class="slds-input"  value="{!v.courseName}"/>
                </div>
            </div>        
            <div class="slds-form-element slds-is-required">
                <div class="slds-form-element__control">

                    <div aura:id="AddAttachmentElementsHere">


                        <input aura:id="application_attachment_1" type="file" 
                                    class="slds-input"
                                    labelClass="slds-form-element__label"
                                    value=""
                                    required="true"/>  


                    </div>                          

                 </div>
            </div>       
            <div class="slds-form-element">
                <ui:button label="Add Text" 
                           class="slds-button slds-buttonneutral"
                           labelClass="label"
                           press="{!c.addAnotherAttachment}"/>
                <ui:button label="Apply" 
                           class="slds-button slds-button--neutral"
                           labelClass="label"
                           press="{!c.createApplication}"/>

            </div>        
    </form>

     <div class="spinnerContainer" aura:id="spinnerDivId">
         <center><ui:spinner aura:id="spinner" class="spinnerCls "/></center>
     </div>

CLIENT SIDE CONTROLLER CODE :

({ doInit : function(component) {
component.set("v.courseName","MBA"); component.set("v.courseId","a0A2800000EqvCZEAZ"); $A.util.addClass(component.find("spinnerDivId"), "hideElement");
},

addAnotherAttachment : function(component, event, helper) {        
    var attachmentCounter = component.get("v.AttachmentCounter");
    attachmentCounter = attachmentCounter+1;
    component.set("v.AttachmentCounter",attachmentCounter);
     helper.addAnotherAttachment(component,attachmentCounter);    
},



createApplication : function(component, event, helper) {

   var dynamicTextFieldValue =   component.find("findableAuraId").get("v.value");

    $A.util.removeClass(component.find("spinnerDivId"), "hideElement");
    var toastMessage ='';
    var toastType ='';

    //-- STEP 1 :- FIELD VALIDATION : START 
    var isFieldValidationSuccess = true;
    var applicationNameComponent = component.find("applicationName");
    var applicationName = applicationNameComponent.get("v.value"); 
    if(applicationName!=null && applicationName.trim().length<=0){
        isFieldValidationSuccess = false;
        toastMessage = 'Application Name is required';
        toastType ='Error';
        //applicationNameComponent.set("v.errors", [{message:"Application Name is required "}]);            
    }


    var MAX_FILE_SIZE= 4000000;        
    var fileComponent = component.find("application_attachment_1");
    var fileInput = component.find("application_attachment_1").getElement(); 
    var file = fileInput.files[0]; 


    if(isFieldValidationSuccess && $A.util.isUndefined(file)){
         isFieldValidationSuccess = false;
        toastMessage = 'Please upload the document';
        toastType ='Error';
    }else if(isFieldValidationSuccess && file.size > MAX_FILE_SIZE) {
        isFieldValidationSuccess = false;     
        toastMessage = 'File size cannot exceed ' + MAX_FILE_SIZE + ' bytes.\n' +
            'Selected file size: ' + file.size;
        toastType ='Error';
    } 

    //-- If field validation fails then return
    if(!isFieldValidationSuccess){

         //-- Show the Error toast Message
        var showToast = $A.get('e.force:showToast');
        showToast.setParams(
            {
                'title': '',
                'message': toastMessage,                
                'type':toastType
            }
        );            
        showToast.fire();

        $A.util.addClass(component.find("spinnerDivId"), "hideElement");
        return;
    }else{         
        var fr = new FileReader();
        fr.onload = function() {

            var fileContents = fr.result;
            var base64Mark = 'base64,';

            var dataStart = fileContents.indexOf(base64Mark) + base64Mark.length;
            fileContents = fileContents.substring(dataStart);            
            var action = component.get("c.createApplicationRecord"); 

            action.setParams({
                applicationName:applicationName,
                courseId: component.get("v.courseId"),
                fileName: file.name,
                base64Data: encodeURIComponent(fileContents), 
                contentType: file.type
            });

             action.setCallback(this, function(response) {

                var state = response.getState();                
                if (state === "SUCCESS") {                        
                    //-- hide the spinner 
                    $A.util.addClass(component.find("spinnerDivId"), "hideElement");                        
                    //-- Show the success toast Message
                    var showToast = $A.get('e.force:showToast');
                    showToast.setParams(
                        {
                            'title': '',
                            'message': 'Application has been created',                            
                            'type':'success'
                        }
                    );            
                    showToast.fire();

                    //-- Reload the View
                    $A.get('e.force:refreshView').fire();
                    console.log("Successfully Processed");                 

                }else if (state === "INCOMPLETE") {
                     $A.util.addClass(component.find("spinnerDivId"), "hideElement");
                     $A.log("From server: INCOMPLETE");
                } else if (state === "ERROR") {                    
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                             $A.util.addClass(component.find("spinnerDivId"), "hideElement");
                            $A.log("Error messae: " +  errors[0].message);
                        }
                    } else {
                         $A.util.addClass(component.find("spinnerDivId"), "hideElement");
                         $A.log("From server : Unknown error");
                    }
                }
            });            
            $A.enqueueAction(action); 
            //sforce.one.navigateToSObject(component.get("v.applicationId"));  // redirecing to Opportunity detail Page
        };
        fr.readAsDataURL(file);
    }
},

})

HELPER JS CODE :

({ helperMethod : function() {

},


//-- Dynamically generate the Attachment browser component
addAnotherAttachment : function(cmp,attachmentCounter) {         
    var myCmp = $A.createComponent('ui:inputText', {'aura:id': 'findableAuraId'},
        function(myCmp) {                
            var divComponent = cmp.find("AddAttachmentElementsHere");
            var divBody = divComponent.get("v.body");
            divBody.push(myCmp);
            divComponent.set("v.body", divBody);            
        }
    );        
},


showToast : function(cmp,toastMessage,toastType) {         
    var showToast = $A.get('e.force:showToast');
    showToast.setParams(
        {
            'title': '',
            'message': toastMessage,                            
            'type':toastType
        }
    );            
    showToast.fire();
}

})

FOLLOWING CLIENT-SIDE CONTROLLER CODE TO GET THE VALUE OF DYNAMICALLY GENERATED TEXT FIELD DOES NOT WORK

component.find("findableAuraId").get("v.value");
4
  • Can you add full code ?Thanks Commented Sep 5, 2016 at 16:39
  • Hi Mohith, I have upadted the Question with complete code . Thanks. Commented Sep 6, 2016 at 6:24
  • At what point to you call component.find("findableAuraId").get("v.value"); ? Based on your code, it looks like you only create your component after the button press, if you try to find the component before the button is pressed, the component wouldn't have been created yet. Commented Sep 6, 2016 at 20:20
  • Hi Mohith, I have updated the CLIENT SIDE CONTROLLER in the Question , On CLick of Apply button i am trying to get the value of the field, which is giving me undefined.. Commented Sep 7, 2016 at 5:17

1 Answer 1

1

See comment from techbusinessman in this post:

Dynamically created component with aura:id, set as a Facet inside a parent component, is not found when calling find() and passing in aura:id

You can say:

var dynamicTextFieldValue = component.get("v.body")[0].get("v.value");

Might be a good idea to create a new facet for your dynamically generated field to ensure that it is always the first item in the list of components

You must log in to answer this question.

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