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
Jonas JúniorJonas Júnior 

Get id attribute from <li> element in Lightning Component

Hi guys,

I am building a new Lightining Component and need help, please. I have two columns in my main page. I have an Object called: Produtos__c. The left column needs show all Produtos__c.Category__c from the database (DONE). When the user to click in some category, I need show all records with the category clicked by user in right column (NEED HELP).

Something like this:
User-added image
As saw, all products are being shown.

Project details:

InfoSalesMain.cmp
<aura:component controller="InfoSalesController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction,lightning:isUrlAddressable" access="global" > 
    
    <aura:handler name="init" value="this" action="{!c.doInit}" />
    
    <aura:attribute name="idProduto" type="String" />
    <aura:attribute name="DetalheProduto" type="Boolean" default="false" />
    <aura:attribute name="Name" type="String"/>
    <aura:attribute name="listaProduto" type="List" default="[]"/>
    <aura:attribute name="listaProdutoCategoria" type="List" default="[]"/>
    <aura:attribute name="listaProdutoByCategory" type="List" default="[]"/>
    <aura:attribute name="produto" type="Object" />
    
    <div class="slds-grid slds-wrap">
        <div class="slds-size_1-of-6">
            <div class="slds-box slds-theme_default">
                Bem-vindo, {!v.Name}
                <br /><br />
                <b>CATEGORIAS EXISTENTES</b>
                <br /><br />
                <aura:iteration items="{! v.listaProdutoCategoria }" var="produto">
                    <ul class="slds-list_horizontal">
                        <li> <a onclick="{!c.categoriaSelecionada}" href="#">{! produto.Category__c }</a> </li>
                    </ul>
                </aura:iteration>
            </div>
        </div>
        <div class="slds-size_5-of-6">
            <div class="slds-box slds-theme_default">
                <lightning:card>
                    <div class="slds-p-left_medium slds-p-right_medium">
                        <ul class="slds-list_vertical slds-has-dividers_top-space">
                            <aura:iteration items="{! v.listaProduto }" var="produto" >
                                <!-- Activate the next line when discovered how get ProdutoByCategory -->
                                <!-- <aura:iteration items="{! v.listaProdutoByCategory }" var="produto" > -->
                                <li class="slds-list__item">
                                    <!-- Here will be the produto image -->
                                    <lightning:avatar size="large" src="/docs/component-library/app/images/examples/avatar2.jpg" initials="CR" fallbackIconName="standard:person_account" alternativeText="Cindy Rice" class="slds-m-right_small"/>
                                    <b>Descrição: </b> {! produto.Description__c }<br/>
                                    <b>Preço:</b> R$ {! produto.Price__c }
                                </li>
                            </aura:iteration>
                        </ul>
                    </div>
                </lightning:card>
            </div>
        </div>
    </div>
    <!-- NEXT SCREEN IS NOT COMPLETE -->
    <aura:if isTrue="{! v.DetalheProduto }">
        <c:DetalheProduto idProduto="{! v.idProduto }"/> 
    </aura:if>
</aura:component>
InfoSalesController.apxc
public class InfoSalesController {
    
    @AuraEnabled
    public static String saveProduto_CTRL(String jsonProduto){
        Produto__c produto = (Produto__c) Json.deserialize(jsonProduto, Produto__c.class);        
        UPSERT produto;
        return 'Produto inserido com sucesso';   
    }
    
    @AuraEnabled
    public static Produto__c getProdutoSObj(){
        Produto__c prod = [SELECT Id, Capacidade__c, Category__c, Description__c, Foto__c, Frequencia__c, Inches__c, Price__c, Socket__c, Storage__c FROM Produto__c];
        return prod;
    }
    
    @AuraEnabled
    public static String deleteProduto_CTRL(String jsonProduto){
        
        Produto__c produto = (Produto__c) Json.deserialize(jsonProduto, Produto__c.class);
        delete produto;
        return 'Produto excluído com sucesso';
    }
    
    @AuraEnabled
    public static List<Produto__c> getListProduto_CTRL(){
        List<Produto__c> listReturnProd = [SELECT Id, Description__c, Foto__c, Price__c, Category__c FROM Produto__c];
        listReturnProd.sort();
        System.debug('listReturnProd: '+listReturnProd);
        return listReturnProd;       
    }
    
    @AuraEnabled
    public static List<AggregateResult> getProdutoCategory_CTRL(){
        List<AggregateResult> listReturnCategoryProd =[SELECT Category__c FROM Produto__c GROUP BY Category__c ORDER BY Category__c ASC];
        return listReturnCategoryProd;
    }
    
    @AuraEnabled
    public static List<Produto__c> getProdutoByCategory_CTRL(String paramCtgSelecionada){
        List<Produto__c> listReturnProdutoByCategory = [SELECT Id, Description__c, Foto__c, Price__c, Category__c FROM Produto__c WHERE Category__c =: paramCtgSelecionada];
        return listReturnProdutoByCategory;
    }
    
    @AuraEnabled
    public static String getUserName() {
        return userinfo.getName();
    }
    
}
InfoSalesMainController.js
({
 	doInit: function(component, event, helper) {
        helper.getUser(component);
        helper.getProdutos(component);
        helper.getCategoriaProduto(component);
    },
    categoriaSelecionada : function(component, event, helper) {
    	//helper.getCategoriaSelecionada(component);
    	var src = event.getSource();
        var name = src.get("v.value");
        component.set("listaProdutoByCategory",name);
    }
})
InfoSalesMainHelper.js
({
    getUser : function(component){
        var action = component.get("c.getUserName");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.Name", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    getProdutos : function(component) {
        var action = component.get("c.getListProduto_CTRL");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.listaProduto', response.getReturnValue());
            } else if (state === "ERROR") {
                alert('Erro: Lista vazia');
                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);
    },
    getCategoriaProduto : function(component) {
        var action = component.get("c.getProdutoCategory_CTRL");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.listaProdutoCategoria', response.getReturnValue());
            } else if (state === "ERROR") {
                alert('Erro: Lista vazia');
                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);
    },
    
	getCategoriaSelecionada : function(component) {
        var action = component.get("c.getProdutoByCategory_CTRL");
        action.setParams({ 
            paramCtgSelecionada : component.get("v.categoriaClicada")//How to pass this variable to apex?
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.listaProdutoByCategory', response.getReturnValue());
            } else if (state === "ERROR") {
                alert('Erro: Lista vazia');
                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);
    }
    
})
What I need to do? What I am forgetting?
Best Answer chosen by Jonas Júnior
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
Hi Jonas Júnior ,

Do these following changes and you should be able to achieve the required.

 InfoSalesMain.cmp
<aura:iteration items="{! v.listaProdutoCategoria }" var="produto">
		<ul class="slds-list_horizontal">
			<li> <a onclick="{!c.categoriaSelecionada}" href="#" data-produto="{!produto.Category__c}">{! produto.Category__c }</a> </li>
		</ul>
	</aura:iteration>

InfoSalesMainController.js
 
({
 	doInit: function(component, event, helper) {
        helper.getUser(component);
        helper.getProdutos(component);
        helper.getCategoriaProduto(component);
    },
    categoriaSelecionada : function(component, event, helper) {
    	helper.getCategoriaSelecionada(component, event, helper);
    },
})

InfoSalesMainHelper.js
 
getCategoriaSelecionada : function(component, event, helper) {
          //get target attribute through event.
	    var selectedCategory = event.target.getAttribute("data-produto");
		
        var action = component.get("c.getProdutoByCategory_CTRL");
        action.setParams({ 
            "paramCtgSelecionada" : selectedCategory//you can pass this variable to apex this way!
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.listaProdutoByCategory', response.getReturnValue());
            } else if (state === "ERROR") {
                alert('Erro: Lista vazia');
                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);
    }


Please mark this is as best answer if it works.That way others can benefit.

Regards,
Santosh.​

All Answers

Raj VakatiRaj Vakati
You can able to do it using the   lightningverticalnavigation easily .. .. please refer this link for same 

https://rajvakati.com/2018/03/08/lightningverticalnavigation-example/
Jonas JúniorJonas Júnior
Hi Raj,

Thanks for your help!
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
Hi Jonas Júnior ,

Do these following changes and you should be able to achieve the required.

 InfoSalesMain.cmp
<aura:iteration items="{! v.listaProdutoCategoria }" var="produto">
		<ul class="slds-list_horizontal">
			<li> <a onclick="{!c.categoriaSelecionada}" href="#" data-produto="{!produto.Category__c}">{! produto.Category__c }</a> </li>
		</ul>
	</aura:iteration>

InfoSalesMainController.js
 
({
 	doInit: function(component, event, helper) {
        helper.getUser(component);
        helper.getProdutos(component);
        helper.getCategoriaProduto(component);
    },
    categoriaSelecionada : function(component, event, helper) {
    	helper.getCategoriaSelecionada(component, event, helper);
    },
})

InfoSalesMainHelper.js
 
getCategoriaSelecionada : function(component, event, helper) {
          //get target attribute through event.
	    var selectedCategory = event.target.getAttribute("data-produto");
		
        var action = component.get("c.getProdutoByCategory_CTRL");
        action.setParams({ 
            "paramCtgSelecionada" : selectedCategory//you can pass this variable to apex this way!
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.listaProdutoByCategory', response.getReturnValue());
            } else if (state === "ERROR") {
                alert('Erro: Lista vazia');
                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);
    }


Please mark this is as best answer if it works.That way others can benefit.

Regards,
Santosh.​

This was selected as the best answer