Showing posts with label lightning. Show all posts
Showing posts with label lightning. Show all posts

How to Use Aura Iteration In Lightning Component

How to Use Aura Iteration In Lightning Component


In this article we will go through:

  • What is Aura Iteration
  • How to use simple Iteration
  • How to iterate over server side data

aura:iteration is used to iterate over a collection of items and renders the body of the tag for each item

Syntax
<aura:iteration items="{!v.account}" var="a">
The items attribute tells the component which  list to iterate
The var attribute let’s us name a variable that will contain the current element from the array we’re iterating over.
Simple Iteration
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
     <aura:attribute name="countries" type="String[]" default="['India','USA','Canada']"/>
     
    <h1>List of Countries</h1>
    <aura:iteration items="{!v.countries}" var="country">
        <ul>
            <li>{!country}</li>
        </ul>
    </aura:iteration>
</aura:component>
Output: Show List of Countries


The following example shows how to iterate over the server side data 

Lightning Component: DemoAccount.cmp
<aura:component controller="DemoHelper" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <!--retreive list of accounts -->
    <!--type=Account[] to hold account List-->
    <aura:attribute name="accountList" type="Account[]" />
        <lightning:button variant="brand" label="Show Account list"  onclick="{!c.myAction }" /> 
    
    <!-- Use iteration to display more than one record -->
    <aura:iteration items="{!v.accountList}" var ="a">
      <div class="slds-card">
        <div class="slds-media__figure">
            <lightning:icon iconName="action:approval" size="small"/>  
        </div>
        <div class="slds-card__header slds-grid">{!a.Name}</div>
        <div class="background">{!a.Phone}</div>
        <div class="background">{!a.Type}</div>
    </div>
        
    </aura:iteration>
</aura:component>

Apex Controller: DemoHelper.apxc
public class DemoHelper {
@AuraEnabled
    //return list of accounts from apex class
    //made static so that we dont need to create an instance.Can call using class name
    public static List<Account> checkMethod(){
        List<Account> acclist = [Select Name,Type,Fax,Phone From Account];
        return acclist;
    }
}
Javascript Controller: DemoAccountController.js
({
     myAction : function(component, event, helper) {
            //1.DEFINE ACTION
            //create variable to define action. Use var to store value 
            //If we use c inside javascript controller then it is apex controller
            var action = component.get("c.checkMethod");
            
            //2.SET CALLBACK
            //inside callback function we are getting list of accounts
            action.setCallback(this,function(response){

   //3.SET VALUE TO ATTRIBUTE 
   //the list of accounts we are setting to the attribute accountlist               
        component.set("v.accountList",response.getReturnValue());     
            });
            //4.ENQUE ACTION
            $A.enqueueAction(action);
 } 
})
DemoAccountApp.css
.THIS {
    background-color:blue;
    color:white;
}
.THIS .background{
    color:yellow;
}
Output- Click on a button to show list of Accounts 









We can add it in the Lightning tab



Output



Reference

Aura Iteration
https://rajvakati.com/2018/05/11/auraiteration/

Lightning Documentation
https://developer.salesforce.com/docs/component-library/bundle/lightning:button/example

Salesforce interview with McKesson Corporation

Salesforce interview with McKesson Corporation




1.In what ways we can achieve pagination?


We can add pagination to a page using a standard set controller by utilizing the next and previous actions. To control the number of records displayed on each page, use a controller extension to set the pageSize.
This approach gets records from cache if records are already iterated.

We can use pagination by using limit in offset query. It can be used to do more customization

Pagination

<apex:page standardController="Account" extensions="accPagination" recordSetVar="accounts">
<apex:pageBlock title="Viewing Accounts">
<apex:form id="theForm">
<apex:pageBlockSection >
<apex:dataList var="acc" value="{!accounts}">
{!acc.Name}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid columns="4">
<apex:commandLink action="{!first}">FIRST</apex:commandLink>
<apex:commandLink action="{!next}">NEXT</apex:commandLink>
<apex:commandLink action="{!previous}">PREVIOUS</apex:commandLink>
<apex:commandLink action="{!last}">LAST</apex:commandLink>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>
AccPagination Controller: To display only 5 records per page use PageSize
public class accPagination{
    public accPagination(ApexPages.StandardSetController controller) {
   
    }        
}
2. How to check how many records have passes or failed using batch apex? Get failure records ID in batch apex?

By default variables do not store values. Once the new transaction happens earlier state i.e. transaction passed or failed is removed. Batch apex can implement Database.stateful which allow variables to store previous state.

Database.SaveResult[] srList = Database.insert(scope, false); After it, in finish() method we can collect and process information for failed and successful records. Scope is set of records in that transaction, false is allowing partial transaction.

After it, in finish() method you can collect and process information for failed and successful records.

If DML Operation is Success Will Get Record Id From Database By Using getId()  Method in Database.SaveResult Class.

If any DML Operation Fails while Processing The Record no way to Get the Failure Record Id in Database.Error Class.

3.What is mixed DML operation and how to avoid it?

This error means that two Sobjects(setup & non-setup) that we are using in our
code can not mix during the same transactions. This restriction exists because
 some sObjects affect the user’s access to records in the org. 

For example, We cannot insert an account and then insert a user or a group 
member in a single transaction.

To avoid this error, we should perform DML operation on standard/custom object
 records in a different transaction.

Solution For Mixed DML Operartion.

1. Separate the Setup object and Non-Setup object dml operation using Future
Method.     
2. System.RunAs : Enclose mixed DML operations within System.runAs blocks 
to avoid the mixed DML error in test class.

4. What is the use of Test.Start, Test.Stop?

Test.startTest and Test.stopTest are used for asynchronous apex, like Batch Apex
and Future calls. Calling method(s) between Test.startTest and Test.stopTest 
ensure that any asynchronous transactions finish executing before Test.stopTest() exits. 

startTest()
Marks the point in our test code when our test actually begins. Use this method 
when we are testing governor limits.

stopTest()
Marks the point in our test code when our test ends. Use this method in 
conjunction with the startTest method.

5.Create field using apex? Is it possible?


We can create field using Metadata API.

MetadataService.CustomField customField = new MetadataService.CustomField();
customField.fullName = 'Test__c.TestField__c';
customField.label = 'Test Field';
customField.type_x = 'Text';
customField.length = 42;
MetadataService.AsyncResult[] results =   service.create(new List<MetadataService.Metadata> { customField }) 
10. Use case of Visualforce page? 

11. Difference between Visualforce and Lightning?
Visualforce components are page-centric and most of the work is done on the server. Lightning Components are client-side centric, which makes them more dynamic and mobile friendly.
12. Difference of using apex controller in lightning and Visualforce?

1. Methods in aura enabled are asynchronous. Methods in Visualforce Page is synchronous 

2. All the required variables declared in controller use getter,setter to display values in Vf page. 
Lightning have attribute which do not bind with controller variable directly. 

3.When redirecting from one page to another then visualforce we use pageReference. It send request to controller and it will provide new page.  

14.How is security enforced in lightning as compared to visualforce?

Shared Resources 

In Visualforce, we build complete pages. In Lightning, the basic building blocks are components, which are reusable and easily replaceable. A . 


In a Lightning application, components share key resources like the global window and JavaScript interpreter. We have to be careful about using functions that take control of the entire window, such as JavaScript alerts and global calls, or writing code that takes a great deal of JavaScript processing, as it will affect other components in the same window.


Data Security
Visualforce enforces the active user’s CRUD and FLS permissions when a page renders a Salesforce object. Lightning doesn’t do any client-side authorization, so it doesn’t respect these permissions. 

LockerService isolates individual Lightning components in their own containers so they can’t interact with one another directly except through tools provided by the framework, like Aura attributes or events. 


15.User dont have access to the fields and want to display in lightning? What need to be done?


16.Does OWD, profile, permission set which gets enforced when using with sharing ?

Only record level security is enforced with sharing. It does not take object level and field level security into consideration.

17.How to create test data for test classes? What are the ways we can get data?

18. We have three different objects. Delete records from all the three objects and they dont have any relation?


19. Write a batch to delete records for three unrelated object?


20. What is database.Stateful?


Database.Stateful in the class can maintain state across the transactions. When using Database.Stateful, only instance member variables hold or retain their values between transactions. Static member variables do not hold their values & values are reset between transactions.

 Maintaining state is useful for counting records as they’re processed.  It can be used for Capturing the failed record information in Execute method between all transactions and assigning to member. And use that member in Finish method.

Example
We want to perform logic like aggregate totals of the opportunity amounts as they were processed. We can use this count and send mail in final method to the users with job processed count and failure batch job count.


 If we don’t implement Database.Stateful, all static and instance member variables are reset that is set back to their original values.

21. Can class extend interface?

Class cannot extend interface but implement it.Also, one class can extend only one class.




Reference

https://salesforce.stackexchange.com/questions/82969/count-of-records-processed-during-batch

https://developer.salesforce.com/forums/?id=9060G000000I5tPQAS

https://www.salesforcecodecrack.com/2018/08/how-to-get-failure-record-ids-from.html

https://blog.webnersolutions.com/create-salesforce-custom-object-using-apex-code

Tooling API to create fields
https://tecknikh.com/create-custom-field-using-tooling-api-in-apex/