Tuesday, 20 March 2018

lightning - quick action on opportunity page to edit related list

Add a quick action associated with a lightning compoent on the opportunity mobile and salesforce1 actions list.


ProjectedRevenueRelatedList.cmp:
=========================

<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId" controller="ProjectedRenevueRelatedListController">
    <aura:attribute name="prlist" type="Object[]"  access="global" />
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="isOpen" type="boolean" default="true"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <ltng:require scripts=""
                  styles="{!join(',',
                          $Resource.projectRevenue)}" />
    <aura:if isTrue="{!v.isOpen}">
        <div style="height:500px">
            <div class="slds-modal__header">           
                <h2 id="header99" class="slds-text-heading--medium">Projected Revenues</h2>
                <p></p>
            </div>
            <aura:if isTrue="{!v.prlist.length > 0}">
                <div style="width:100%">
                    <table class="slds-table slds-table_bordered slds-max-medium-table_stacked-horizontal" style="margin-top:25px;width:100%">
                        <thead>
                            <tr class="slds-text-title_caps">
                                <th><div class="slds-truncate">Projected Revenue Name</div></th>
                                <th><div class="slds-truncate">Annual Projected Revenue</div></th>
                                <th><div class="slds-truncate">Fiscal Year</div></th>
                            </tr>
                        </thead>
                        <tbody>
                            <aura:iteration items="{!v.prlist}" var="pr">
                                <tr>
                                    <td class="slds-truncate">{!pr.Name}</td>
                                    <td class="slds-truncate"><ui:inputText value="{!pr.AnnualRevenue__c}"  placeholder="Initial"/></td>
                                    <td class="slds-truncate"><ui:inputText value="{!pr.Fiscal_Year__c}"  placeholder="Initial" change="{!c.validateFiscalYear}" />
                                        <aura:if isTrue="{!pr.Fiscal_Year__c.length!=4}">
                                            <p style="color:red">Fiscal Year must be of 4 digits</p>
                                        </aura:if>
                                    </td>       
                                </tr>
                            </aura:iteration>
                        </tbody>
                    </table>
                </div>
                <div class="slds-modal__footer">
                    <button class="slds-button slds-button--neutral" onclick="{!c.closeModel}" >Cancel</button>
                    <button class="slds-button slds-button--brand" id="savebtn" onclick="{!c.saveModel}">Save</button>
                </div>
                <aura:set  attribute="else">
                    No Projected Revenues Available to show.
                </aura:set>       
            </aura:if>
        </div>
    </aura:if>
</aura:component>





ProjectedRevenueRelatedListController.js
==============================

({
doInit : function(component, event, helper) {
console.log('doInit success');       
        var prlist=[];
        console.log('recordId: '+component.get("v.recordId"));
        var action = component.get("c.getProjectedRevenueList");
        action.setParams({ oppId : component.get("v.recordId") });       
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.prlist",JSON.parse( response.getReturnValue()));
                console.log('prlist: '+JSON.stringify(component.get('v.prlist')));
            }
        });
        $A.enqueueAction(action);
},
    closeModel: function(component, event, helper) {
      // for Hide/Close Model,set the "isOpen" attribute to "Fasle" 
        window.open('/'+component.get("v.recordId"),"_self");
   },
    saveModel: function(component, event, helper) {
        console.log('saving data to server');   
        console.log('data: '+JSON.stringify(component.get("v.prlist")));
        var action = component.get("c.saveProjectedRevenueList");
        action.setParams({ data : JSON.stringify(component.get("v.prlist")) });         
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log('data saved.');
            }                           
        window.open('/'+component.get("v.recordId"),"_self");
        });
        $A.enqueueAction(action);     
   },
     validateFiscalYear: function(component,event,helper){
        var ele=event.getSource();
        var eleval=ele.get("v.value");
         console.log('eleval: '+eleval);
         console.log('eleval length: '+(eleval.length!=4));
        if(eleval.length!=4){
           document.getElementById("savebtn").disabled = true;
        }
        else{
           document.getElementById("savebtn").disabled = false;
        }
    }
})







projectedRevenue.css
================

h1 {
    color : red;
}

#myClass {
    color : blue;
}
.slds-modal__container{
       max-width: 60rem !important;
       width:60% !important;
}
.slds-modal__content {
    height: 400px !important;
    max-height: 400px !important; 
}




ProjectedRenevueRelatedListController.cls
===============================

public class ProjectedRenevueRelatedListController {
    @AuraEnabled
    public static String getProjectedRevenueList(String oppId){
        List<Projected_Revenue__c> prlist=new List<Projected_Revenue__c>();
        prlist=[SELECT Id, Name, AnnualRevenue__c, Fiscal_Year__c
              FROM Projected_Revenue__c
                WHERE Opportunity__c=:oppId];
        return JSON.serialize(prlist);
    }
   
    @AuraEnabled
    public static void saveProjectedRevenueList(String data){
        System.debug('saveProjectedRevenueList success');
        List<Projected_Revenue__c> prlist=new List<Projected_Revenue__c>();
        try{
        prlist=(List<Projected_Revenue__c>)JSON.deserialize(data, LIst<Projected_Revenue__c>.class);
        }catch(JSONException ex){
            System.debug('Deserialization Exception >>> '+ex);
        }
        update prlist;
    }
}



Tuesday, 13 March 2018

Javascript - get soundex value for a string

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">
function getsoundex(){
   var inptxt=document.getElementById('inp').value;
  // alert('inptxt: '+inptxt);
  document.getElementById('result').innerHTML='Soudex value: '+soundex(inptxt);
}
var soundex = function(s) {
    var a = s.toLowerCase().split(''),
        f = a.shift(),
        r = '',
        codes = { a: '', e: '', i: '', o: '', u: '', b: 1, f: 1, p: 1, v: 1, c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2, d: 3, t: 3, l: 4, m: 5, n: 5, r: 6 };

    r = f +
        a
        .map(function(v, i, a) {
            return codes[v]
        })
        .filter(function(v, i, a) {
            return ((i === 0) ? v !== codes[f] : v !== a[i - 1]);
        })
        .join('');

    return (r + '000').slice(0, 4).toUpperCase();
};
</script>
</head>
<body>

<h1>Enter some letters below</h1>
<input type="text" id="inp" />
<button onclick="getsoundex()">get Soudex value</button>
<p id="result"></p>
</body>
</html>








Reference:
========

Angular.js - toggle popup message with ng-click




<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<style type="text/css">
.popup{padding:10px;display:block;position:absolute;top:0;left:0;height:30px;width:200px;background:#efefef;}
</style>
<div class="content" ng-app="myApp" ng-controller="myCtrl">
    <div class="field">
        <button ng-click="inputdata=inputdata?false:true" style="margin-top:100px">Show Popup</button>
        <div ng-show="!inputdata" class="popup">
        pop successful.
        </div>
    </div>
</div>
<script>
var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', function($scope) {
  $scope.inputdata = true;
});
</script>
</body>
</html>

Friday, 9 March 2018

salesforce - Clone a record to create another record of same type

Run the below code in Excecute anonymous window of developer console.



QuoteLineItem qli=[SELECT Id,QuoteId, PricebookEntryId, Quantity, UnitPrice, Product2Id, Number_Eligible_Employees__c, Number_Expected_Enrolled__c, Single_Employer_Contribution__c FROM QuoteLineItem WHERE Id='0QL290000001ZN4'];
QuoteLineItem qli2=qli.clone(false,true,false,false);
insert qli2;





Note:
===

         List all the Required fields of the record in SELECT query.