Saturday, November 19, 2016

PabeBlockTable Functionality in Lightning Application

Step1: Create Apex Class

public class ContactController {
    @AuraEnabled
    public static List<Contact> getContacts() {
        return [Select Id, Name, Birthdate, AccountId, Account.Name, Email, Title, Phone
                From Contact order by LastModifiedDate desc
                limit 10];
    }
}



Step2: Create Lighting application


<aura:application controller="ContactController" access="GLOBAL" >
   
    <aura:attribute name="contacts" type="Contact[]" access="private"/>
    <aura:handler name="init" action="{!c.doInit}" value="{!this}" />
     <table class="table">
            <thead >
             
                    <tr class="slds-text-title--caps">
                      <th scope="col">
                        <div class="slds-truncate" title=" Name"> Name</div>
                      </th>
                   
                      <th scope="col">
                        <div class="slds-truncate" title="Amount">Phone</div>
                      </th>
                      <th scope="col">
                        <div class="slds-truncate" title="Date">Email</div>
                      </th>
                   
                      <th scope="col">
                        <div class="slds-truncate" title="Client">Client Name</div>
                      </th>
                       <th scope="col">
                        <div class="slds-truncate" title="Reimbursed?">Birthdate</div>
                      </th>
                    </tr>
              </thead>
            <tbody>
    <aura:iteration var="contacts" items="{!v.contacts}">
                <tr>
                    <td><a href="#"> {!contacts.Name}</a></td>
                   <td> {!contacts.phone}</td>
                   <td> {!contacts.Email}</td>
                   <td> {!contacts.Account.Name}</td>
                   <td> {!contacts.Birthdate}</td>
                </tr>
            </aura:iteration>
                  </tbody>    
        </table>
</aura:application>


Step3: Create controller for lightning application

({
doInit : function(component, event, helper) {
        var action = component.get("c.getContacts");
        action.setCallback(this, function(data) {
            console.log(data.getReturnValue());
            component.set("v.contacts", data.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})


Sunday, November 13, 2016

Displaying Records in Lightning component

Step 1: Create apex class.

Public class expensesRecordsDisplay{

   @AuraEnabled
   public static List<Expense__c> getExpensesRecords(){
   
     return [Select id,name,amount__c,date__c,client__c,Reimbursed__c from Expense__c];
   }
}


Step 2:create lightning component...

<aura:component controller="expensesRecordsDisplay"> <p class="white" >Display Expenses Records</p > <aura:attribute name="Expenses" type="Expense__c[]" ></aura:attribute> <ui:button label="Get Expenses" press="{!c.getOpps}"/> <table class="table"> <thead > <tr class="slds-text-title--caps"> <th scope="col"> <div class="slds-truncate" title="Expenses Name">Expenses Name</div> </th> <th scope="col"> <div class="slds-truncate" title="Amount">Amount</div> </th> <th scope="col"> <div class="slds-truncate" title="Date">Date</div> </th> <th scope="col"> <div class="slds-truncate" title="Client">Client</div> </th> <th scope="col"> <div class="slds-truncate" title="Reimbursed?">Reimbursed?</div> </th> </tr> </thead> <tbody> <aura:iteration var="Expenses" items="{!v.Expenses}"> <tr> <td><a href="#"> {!Expenses.Name}</a></td> <td> {!Expenses.Amount__c}</td> <td> {!Expenses.Date__c}</td> <td> {!Expenses.Client__c}</td> <td> {!Expenses.Reimbursed__c}</td> </tr> </aura:iteration> </tbody> </table> </aura:component>

step 3: create a controller for component..

({ getOpps : function(component, event, helper) { var action = component.get("c.getExpensesRecords");// calling apex class action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { component.set("v.Expenses", response.getReturnValue()); } }); $A.enqueueAction(action); } })


Step 4: create Style component

.THIS.white  {
       font-family: "Times New Roman", Times, serif;
      background-color: lightblue;
}
.THIS.table  {
       font-family: "Times New Roman", Times, serif;
      background-color: pink;
      border: 1px solid black;
      border-collapse: collapse;
      width: 70%;
      height: 100%;
      text-align: left;
     vertical-align: bottom;

}


Step 5: create application for component...
<aura:application >
    <c:expensesRecordsDisplay />

</aura:application>

Sunday, November 6, 2016

Lightning component Create Record in custom object.

Step 1: Create custom object(Expnses__c) and associated fields.

Step 2: Create apex class as shown below(copy paste same code).

public class NewExpensesCreateRecord{

    @AuraEnabled// annotation indicates this method is enable for aura component(Lightning) 
    public static string createRecord1 (Expense__c newExpense){
        
        try{
            System.debug('CreateCandidateRecord::createRecord::candidate'+newExpense);
            
            if(newExpense!= null){
                insert newExpense;
            }
            
        } catch (Exception ex){
            
        }
        return newExpense.name;
    }  
}


Step 3: Create lightning component (expenses:component name)

<aura:component controller="NewExpensesCreateRecord" implements="force:appHostable,
flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes"
access="global"> <!-- PAGE HEADER --> <div class="slds-page-header" role="banner"> <div class="slds-grid"> <div class="slds-col"> <p class="slds-text-heading--label">Expenses</p> <h1 class="slds-text-heading--medium">My Expenses</h1> </div> </div> </div> <!-- / PAGE HEADER --> <!-- NEW EXPENSE FORM --> <aura:attribute name="expenses" type="Expense__c" default="{ 'sobjectType': 'Expense__c', 'Name': '', 'Amount__c': 0, 'Client__c': '', 'Date__c': '', 'Reimbursed__c': false }" /> <ui:inputText aura:id="expname" label="Name" value="{!v.expenses.Name}" class="slds-input" labelClass="slds-form-element__label"/> <ui:inputNumber aura:id="ExpAmount" label="Amount" value="{!v.expenses.Amount__c}" class="slds-input" labelClass="slds-form-element__label"/> <ui:inputText aura:id="ExpClient" label="Client" value="{!v.expenses.Client__c}" class="slds-input" labelClass="slds-form-element__label"/> <ui:inputDate aura:id="ExpDate" label="Date" value="{!v.expenses.Date__c}" displayDatePicker="true" class="slds-input" labelClass="slds-form-element__label"/> <ui:inputCheckbox aura:id="Expbox" label="Reimbursed?" value="{!v.expenses.Reimbursed__c}" class="slds-input" labelClass="slds-form-element__label"/> <ui:button label="Create Expense" press="{!c.create}"/> </aura:component>


Step 4: click on controller on right side of component and copy paste below code.

({ create : function(component, event, helper) { var newExpense=component.get("v.expenses");// getting label of attribute expenses object //calling apex method var action=component.get("c.createRecord1"); action.setParams({ newExpense : newExpense });// passing patameters to methods.
action.setCallback(this,function(a){ //get the response state var state = a.getState(); if (state === "SUCCESS") { var newExpense = {'sobjectType': 'Expense__c', 'name': '', 'amount__c': '', 'client__c': '', 'Reimbursed__c': '', 'date__c': '' }; //resetting the Values in the form component.set("v.expenses",newExpense); alert('Record is Created Successfully'+a.getReturnValue()); } else if(state == "ERROR"){ alert('Error in calling server side action'); } }); //adds the server-side action to the queue $A.enqueueAction(action); } })


Step 5 :Create lighting application and copy paste below code.

<aura:application extends="force:slds"> <c:expenses /> </aura:application>


after done above steps click on Preview button on right side of application.

Sunday, February 28, 2016

How To Call Apex class form JAVA Script button.

Java Script Button:

{!REQUIRESCRIPT(“/soap/ajax/24.0/connection.js”)}
{!REQUIRESCRIPT(“/soap/ajax/24.0/apex.js”)}
try{
var accountId='{!Account.Id}’;
var result = sforce.apex.execute(“UpdateAccount”, “updateEnable”,{accId: accountId});
                                                   {Controller}            {Method}
location.reload();
}
catch(err) {
txt=”There was an error on this page.\n\n”;
txt+=”Error description: ” + err.description + “\n\n”;
txt+=”Click OK to continue.\n\n”;
alert(txt);
}

======================================
Controller class start with global when you calling class from Javascript button.


global class UpdateAccount {
webService static string updateEnable(List<Id> accId){
try{
System.debug(‘Id–>’+accId);
if(accId != NULL && accId.size() > 0)
{
Account accUpdate = [SELECT Id, Enable__c from Account where Id =:accId];
accUpdate.Enable__c = ‘true’;
update accUpdate;
return ‘Updated successfully’;
}
}
catch(exception e){}
return null;
}
}

How to redirect the visualforce page based on the mobile user or browser user in salesforce

Visualforce page:
<apex:page action=”{!checkingAgent}” controller=”agentController”>
</apex:page>


Controller.

public class agentController {
public agentController() {
}
public PageReference checkingAgent() {
String userAgent = ApexPages.currentPage().getHeaders().get(‘User-Agent’);
if (userAgent.contains(‘iPhone’)) {
PageReference pr = Page.iPhoneFriendlyPage;
pr.setRedirect(true);
return pr;
} else if (userAgent.contains(‘iPad’)) {
PageReference pr = Page.iPadFriendlyPage;
pr.setRedirect(true);
return pr;
} else if (userAgent.contains(‘Salesforce’)) {
PageReference pr = Page.SalesforceFriendlyPage;
pr.setRedirect(true);
return pr;
} else if (userAgent.contains(‘BlackBerry’)) {
PageReference pr = Page.BlackBerryFriendlyPage;
pr.setRedirect(true);
return pr;
} else {
PageReference pr = Page.NormalFriendlyPage;
pr.setRedirect(true);
return pr;
}
return null;
}
}

======================
and please make sure to add the following meta tag in your visualforce page:
<apex:page showheader=”false”>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<title>Visualforce in Mobile View</title>
    <meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />
</head>
<body>
<h2>Visualforce in Mobile View:</h2>
</body>
</html>
</apex:page>

Friday, February 19, 2016

Tips for Salesforce

1.Email Template.

      When Record is meet the Criteria  send mail to User/Group/Role.

      By adding below one in email you can send link of the Record to User.

       Account Link :{!Account.Link}.

2. User utility class.


  public static user gtUser()
    {
    
        userProfile=[select id , profile.name from user where id=: userinfo.getuserid()];
        return userProfile;
    }
 
 

 

 

Triggers:How to avoid execution query multiple time in single transction.

1.Create Query Utility class.
  
public class Query_Util{
       public static List<Product2> prdList ;

  
     public static List<Product2> getProducts(){
       prdList  = New List<Product2>();
       prdList = [select id,Name,PRODUCT_CODE__c from Product2 where PRODUCT_CODE__c =111];
       return prdList ;
    }  


}

2.how to user above query in Trigger()

trigger queryUtility on Opportunity (before insert, before update) 
{
      List<Product2> prd;
        if(query_util.prdList ==null)  // Checking query_util.prdList is null for first time 
        {
            prd = Query_Util.getProducts();
        }
        else
        {
            prd = query_util.prdList;   //Using Existing Product list returned from query Util
            
        }
   if(Trigger.isInsert){
          for(Opportunity opp:Trigger.New){
              if(prd != null && prd.size() > 0 && opp.Name == '111' && opp.Product_Name__c == prd[0].id && System.Today() > ncd.Loan_Date__c){
                 system.debug('&&&&&&&&&'+opp.Product_Name__c);
                 opp.Name.addError('111 Opportunity cannot be created');
               }
        
             }
        }
        if(Trigger.isUpdate){
          for(Opportunity opp:Trigger.New){
              if(prd != null && prd.size() > 0 && opp.Name == '111' && opp.Product_Name__c == prd[0].id && opp.CreatedDate.Date() > ncd.Loan_Date__c){
                 system.debug('&&&&&&&&&'+opp.Product_Name__c);
                 opp.Name.addError('111 Opportunity cannot be created');
               }
        
             }
        }
}