+ Start a Discussion
Luciano RobertoLuciano Roberto 

How to pass an <Aura: id> to each record

Folks,

I'm setting up a toast alert in salesforce, where a list of alerts will be shown.
Each alert will have to have its own aura: id so that I can modify its behavior, such as alert type and the close button.
Below is my code as it is currently configured, it has the fixed aura id <div aura: id = "alert" role = "status">, needs to be dynamic.
I was thinking of getting the name of each alert object record to pass to the aura id, but I do not know how to do it.
Can anybody help me

Controller.js
-------------------------------------------------------------------

({

   doInit : function(component, event, helper)
    {
  var action = component.get( "c.getMsgs" );
        
        
         action.setCallback(this, function(response) 
                           {                               
                               var state = response.getState();
                               
                               if(state == 'SUCCESS')
                               {                                   
                                   var alertMsgList = response.getReturnValue();
                                   var lista = [ ];                                  
                                   
                                   
                                   if(alertMsgList.length > 0)
                                   {
                                       
                                       component.set("v.showToast", true);
                                              var tipoAlerta = component.find( "alerta" );        
                                              $A.util.addClass( tipoAlerta, "slds-notify" );
                                              $A.util.addClass( tipoAlerta, "slds-notify_toast" );  
                                                                       
                                   }
                                   
                       
                                   
                                   for(var i = 0; i < alertMsgList.length; i ++) 
                                   {                                       
                                       var alerta = alertMsgList[ i ].Alerta1__c;
                                       var tipo = alertMsgList[ i ].Tipo_de_Alerta__c;
                                       var titulo = alertMsgList[ i ].Name;                                       
                                       
                                      lista.push(alerta);
                         
                                       
      						       }
                                   
  									component.set("v.html",lista);                                  
     }
                               
                          else {
                                   console.log("Failed with state: " + state);
                               }
                           }); 
        
        
        $A.enqueueAction(action);
  
        
    },

   
   close: function(cmp, event, helper) 
    {
    $A.util.addClass(cmp.find('alerta'), "slds-hide");
    },
        
})
 
Alert.cmp

------------------------------------------------------------------------------------------


<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride,lightning:backgroundUtilityItem" access="GLOBAL" controller="AlertController">   

    
<aura:attribute name="html" type="List" />
    
    
<aura:attribute name="showToast" type="boolean" default="false"/>
    
  
    
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    
<aura:if isTrue="{!v.showToast}">
    
           <aura:iteration items="{!v.html}" var="lista">        
					<div class="demo-only" style="height: 4rem;">
		
   							 <div class="slds-notify_container slds-is-relative">    
				
        							<div aura:id="alerta" role="status">  
													<div  class="slds-notify__content">
                            
                                                                <h2 class="slds-text-heading_small ">                
                                                                     <aura:unescapedHtml value="{!lista}" />  
                                                                </h2>
                            
                                                    <lightning:buttonIcon iconName="utility:close" variant="bare" alternativeText="Close"
                                                     iconClass="{!v.type == 'warning' ? 'light' : 'dark'}" size="small"
                                                     class="slds-button slds-button_icon slds-notify__close slds-button_icon-inverse"
                                                     onclick="{!c.close}"/>      
    
													</div>
									</div>
							</div>
					</div>
			</aura:iteration>
    
    
    
    
    
</aura:if>
    
    
    
</aura:component>

Thanks
Best Answer chosen by Luciano Roberto
Luciano RobertoLuciano Roberto
Thanks Khan Anas  by help me.

I was able to solve the following, I did not need to put the ID in the DIV, instead I put the class directly bringing the alert type formatting in it

My code looks like this, if someone needs to:

Component.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride,lightning:backgroundUtilityItem,force:appHostable,flexipage:availableForAllPageTypes" access="GLOBAL" controller="AlertController"> 
    
    <aura:attribute name="html" type="List" />
    <aura:attribute name="showToast" type="boolean" default="false"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
     
    <div>
	
        <aura:if isTrue="{!v.showToast}">
         <aura:iteration items="{!v.html}" var="lista">
                <div class="slds-notify_container slds-is-relative" id="{! 'divtoHide-'+lista.Name}">
                    <div class="{! 'slds-notify'+ ' ' +'slds-notify_toast'+ ' ' + 'slds-theme_'+''+lista.Tipo_de_Alerta__c}" role="status">
                     <lightning:icon iconName="{! 'utility:'+''+lista.Tipo_de_Alerta__c}" alternativeText="Info!" variant="inverse" class="slds-m-right_small"/>   
                     <div class="slds-notify__content">
                        <h2 class="slds-text-heading_small">{!lista.Alerta1__c}</h2>
                      </div>  
                      <div class="slds-notify__close">
                       <button id="{! lista.Name}" class="slds-button slds-button_icon slds-button_icon-inverse" title="Close" onclick="{!c.closeToast}">
                           <lightning:icon iconName="utility:close" alternativeText="Close" variant="inverse" />   
                       </button>
                      </div>  
                  </div>
	        	</div>
           </aura:iteration>  
        </aura:if>
            
        </div>
         
</aura:component>


Controller.js
({

    
    doInit : function(component, event, helper) {
        console.log('function loaded...');
		 var action = component.get("c.getMsgs");
        action.setCallback(this, function(response)
        {
            var state = response.getState();
            
         if(state == 'SUCCESS'){
                var alertMsgList = response.getReturnValue();
                var lista = [ ];
             
             if(alertMsgList.length > 0){
                component.set("v.showToast", true); 
             }

            for(var i = 0; i < alertMsgList.length; i ++){
                lista.push(alertMsgList[i]);
            }
         }else{
                
                 console.log("Failed with state: " + state);

            } 
            
                 component.set("v.html",lista);
          
        });
       $A.enqueueAction(action);  
	},
    
    
    
    closeToast : function(component, event, helper)
    {
        var whichOne = 'divtoHide-'+event.currentTarget.id;
        var elements = document.getElementById(whichOne);
        $A.util.toggleClass(elements, "slds-hide");
    },
    
})

 

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Luciano,

Greetings to you!

You can not dynamically set aura:id for any component, it should always point to the hardcoded string value.
It is an idea to allow dynamic aura:id attribute for Lightning Components: https://success.salesforce.com/ideaView?id=0873A000000E8fBQAS

According to Salesforce doc (https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_ids.htm):

aura:id doesn't support expressions. You can only assign literal string values to aura:id.

However, you can use (but it is an anti-pattern in lightning):
<div id="{!v.whatever}" >

And in your controller, you'll have to use document.getElementById instead of component.find()

Also, please refer to the below link which might help you further with the above requirement.

https://bugcoder.it/?p=174

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Luciano RobertoLuciano Roberto

Thanks Khan  for your help, but I still can not get it to work.
I'm starting as a programmer I'm still crawling.
I will inform the code below with the comments to see if you can help me.
Basically, what I need is that for each alert found and passed to it, its alert (Alert1__c), its id (Name), CSS settings (Warning, Error, Success, etc) and a button to close it .
I do not know if my code is a bit confusing, but if you can help me, I'll be very grateful.

Controller.js 



({


   doInit : function(component, event, helper)
    {

  var action = component.get( "c.getMsgs" );

         action.setCallback(this, function(response) 
                           {                               
                             
                               var state = response.getState();

                               if(state == 'SUCCESS')
                               {                                   
                                   var alertMsgList = response.getReturnValue();
                                   var lista = [ ];                                  
                                   
                                   
                                   if(alertMsgList.length > 0)
                                   {                                       
                                       component.set("v.showToast", true);                             
                                   }
                                 
                                   
                                   
                                   for(var i = 0; i < alertMsgList.length; i ++) 
                                   {                                       
                                       var alerta = alertMsgList[ i ].Alerta1__c;
                                       var tipo = alertMsgList[ i ].Tipo_de_Alerta__c;
                                       var titulo = alertMsgList[ i ].Name;                                       
                                       
                                       // Stores all the alert records found in the database
                                      lista.push(alertMsgList[i]);

      						       }
                                   
                                   // sends to the <aura:attribute name="html" type="List" /> the list of retrieved alerts

                                   component.set("v.html",lista);
                                 
                                    //  var tipoAlerta = component.find( "alerta" );
                                   
                                   // I need to configure each alert according to its type, according to its id
                                   var tipoAlerta = document.getElementById("!v.Alert.Name");
                              
                               //This is the CSS configuration that will be sent to each alert, however it needs to check the type of alert, it is in the registry (if Warning, sucess, error, etc). I believe that it would have to be inside the for                                 
                                              $A.util.addClass( tipoAlerta, "slds-notify" );
                                              $A.util.addClass( tipoAlerta, "slds-notify_toast" );  
                                              $A.util.addClass( tipoAlerta, "slds-theme_success" );  
   
                                   
     }
                               
               
                          else {
                                   console.log("Failed with state: " + state);
                               }
                           }); 
        
        
        $A.enqueueAction(action);
        
  
        
    },

   
    //THIS FUNCTION HIDE ALERT BY ID - I believe that it would have to be inside the for
   close: function(cmp, event, helper) 
    {
 //   $A.util.addClass(cmp.find('alerta'), "slds-hide");
        $A.util.addClass(document.getElementById('{!v.lista.Name}'), "slds-hide");
    },
   
   
       
    
})
 
Alert.cmp





<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride,lightning:backgroundUtilityItem" access="GLOBAL" controller="AlertController">   

    
<aura:attribute name="html" type="List" />
    
    
<aura:attribute name="showToast" type="boolean" default="false"/>
    
<aura:attribute name="Alert" type="Alert__c" default="{'sobjectType': 'Alert__c',
                         'Tipo_de_Alerta__c': '',
                         'Name': '',
                         'Alerta1__c': ''
                          }"/>
    
    
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    
<aura:if isTrue="{!v.showToast}">
    
           <aura:iteration items="{!v.html}" var="lista">        
					<div class="demo-only" style="height: 4rem;">
		
   							 <div class="slds-notify_container slds-is-relative">    
				
        							<!--<div aura:id="alerta" role="status">  -->
                                 
                                 <div id="{!Lista.Name}" role="status">  
													<div  class="slds-notify__content">
                            
                                                                <h2 class="slds-text-heading_small ">                
                                                                     <aura:unescapedHtml value="{!lista.Alerta1__c}" />  
                                                                </h2>
                            
                                                    <lightning:buttonIcon iconName="utility:close" variant="bare" alternativeText="Close"
                                                     iconClass="{!v.type == 'warning' ? 'light' : 'dark'}" size="small"
                                                     class="slds-button slds-button_icon slds-notify__close slds-button_icon-inverse"
                                                     onclick="{!c.close}"/>      
    
													</div>
									</div>
							</div>
					</div>
			</aura:iteration>
    
    
    
    
   

</aura:if>
    
    
    
</aura:component>

Thanks so much

 
Luciano RobertoLuciano Roberto
Thanks Khan Anas  by help me.

I was able to solve the following, I did not need to put the ID in the DIV, instead I put the class directly bringing the alert type formatting in it

My code looks like this, if someone needs to:

Component.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride,lightning:backgroundUtilityItem,force:appHostable,flexipage:availableForAllPageTypes" access="GLOBAL" controller="AlertController"> 
    
    <aura:attribute name="html" type="List" />
    <aura:attribute name="showToast" type="boolean" default="false"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
     
    <div>
	
        <aura:if isTrue="{!v.showToast}">
         <aura:iteration items="{!v.html}" var="lista">
                <div class="slds-notify_container slds-is-relative" id="{! 'divtoHide-'+lista.Name}">
                    <div class="{! 'slds-notify'+ ' ' +'slds-notify_toast'+ ' ' + 'slds-theme_'+''+lista.Tipo_de_Alerta__c}" role="status">
                     <lightning:icon iconName="{! 'utility:'+''+lista.Tipo_de_Alerta__c}" alternativeText="Info!" variant="inverse" class="slds-m-right_small"/>   
                     <div class="slds-notify__content">
                        <h2 class="slds-text-heading_small">{!lista.Alerta1__c}</h2>
                      </div>  
                      <div class="slds-notify__close">
                       <button id="{! lista.Name}" class="slds-button slds-button_icon slds-button_icon-inverse" title="Close" onclick="{!c.closeToast}">
                           <lightning:icon iconName="utility:close" alternativeText="Close" variant="inverse" />   
                       </button>
                      </div>  
                  </div>
	        	</div>
           </aura:iteration>  
        </aura:if>
            
        </div>
         
</aura:component>


Controller.js
({

    
    doInit : function(component, event, helper) {
        console.log('function loaded...');
		 var action = component.get("c.getMsgs");
        action.setCallback(this, function(response)
        {
            var state = response.getState();
            
         if(state == 'SUCCESS'){
                var alertMsgList = response.getReturnValue();
                var lista = [ ];
             
             if(alertMsgList.length > 0){
                component.set("v.showToast", true); 
             }

            for(var i = 0; i < alertMsgList.length; i ++){
                lista.push(alertMsgList[i]);
            }
         }else{
                
                 console.log("Failed with state: " + state);

            } 
            
                 component.set("v.html",lista);
          
        });
       $A.enqueueAction(action);  
	},
    
    
    
    closeToast : function(component, event, helper)
    {
        var whichOne = 'divtoHide-'+event.currentTarget.id;
        var elements = document.getElementById(whichOne);
        $A.util.toggleClass(elements, "slds-hide");
    },
    
})

 
This was selected as the best answer