Thursday, 28 September 2017

Salesforce - Get All Field API names of a sObject



public String showFields(String sobjectname) {
        //fields.clear();
        String fields='';
        system.debug('name' + sobjectname);
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map <String, Schema.SObjectField> fieldMap =  schemaMap.get(sobjectname).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            schema.describefieldresult dfield = sfield.getDescribe();
           // system.debug(dfield.getname()+'=>'+dfield.getLabel());
           fields+=dfield.getName()+',';
        }
        fields=fields.removeEnd(',');
        System.debug('fields: '+fields);
        return fields;
    }

Thursday, 21 September 2017

SLDS - ui:inputselect example to display values from salesforce

define  component like this,

<aura:component controller="NewCampaignController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >

 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="CampSearchDataListWrp" type="NewCampaignController.CampSearchDataListWrapper" />


<ui:inputSelect class="multiple uiInputSelect"  multiple="true" aura:id="ContactType" value="{!v.CampSearchDataListWrp.ContactType}" required="true"/>


<ui:inputSelect aura:id="sic" label="SIC" change="{!c.onSicChange}">
                        <aura:iteration items="{!v.groupAccount.sicCodes}" var="level">
                            <ui:inputSelectOption text="{!level}" label="{!level}"/>
                        </aura:iteration>
                    </ui:inputSelect>


</aura:component>


controller class will be like,

 //get data from apex
          var inputsel = component.find("ContactType");
      var opts=[];
         var action2 = component.get("c.getContactType");
       /* action2.setCallback(this, function(a) {         
        for(var i=0;i< a.getReturnValue().length;i++){
            console.log('value: '+a.getReturnValue()[i]);
            opts.push({"class": "optionClass", label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
        }
        inputsel.set("v.options", opts);
console.log('response data: '+JSON.stringify(response.getReturnValue()));
    });*/
        action2.setCallback(this, function(response) {
            if(component.isValid() && response.getState() === "SUCCESS" ) {
                try{
                console.log('response data: '+JSON.stringify(response.getReturnValue()));
                component.set("v.CampSearchDataListWrp",response.getReturnValue());
                var data=component.get("v.CampSearchDataListWrp");
                    var dt=data.ContactType;
                    for(var x in dt){
                console.log('data: '+dt[x]);
                        opts.push({"class": "optionClass", label: dt[x], value: dt[x]});
                    }
                     inputsel.set("v.options", opts);   
                }catch(err){
                    console.log('Exception:'+err.stack);
                }
            }
        });
        $A.enqueueAction(action2);       



apex controller is like,

global with sharing class NewCampaignController {

  global class CampSearchDataListWrapper{
                                                                     @AuraEnabled
                                                                     public String EmailType{get;set;}
                                                                     @AuraEnabled
                                                                     public String CustomerClass{get;set;}
                                                                     @AuraEnabled
                                                                     public String MemberStatus{get;set;}
                                                                     @AuraEnabled
                                                                     public List<String> ContactType{get;set;}
                                                                   
                                                                 }
                                                               
                                                                 @AuraEnabled
                                                                 public static CampSearchDataListWrapper getContactType(){
                                                                     Map<String,String> dupmap=new Map<String,String>();
                                                                   
                                                                     //get all contact types
                                                                     String contacttypes='';
                                                                     for(Contact c:[SELECT Contact_Types__c FROM Contact where Contact_Types__c!=null]){
                                                                       
                                                                          contacttypes+=c.Contact_Types__c+';';
                                                                           
                                                                          }
                                                                 
                                                                     List<String> ctlist=new List<String>();
                                                                 if(contacttypes.contains(';')){
                                                                         for(String s:contacttypes.split(';')){
                                                                             if(s!='' && s!=null){
                                                                                  if(!dupmap.containsKey(s)){
                                                                                  ctlist.add(s);
                                                                                       dupmap.put(s,s);
                                                                                  }
                                                                             }
                                                                         }
                                                                 }
                                                                 System.debug('ctlist :'+ctlist);
                                                                    CampSearchDataListWrapper csw=new CampSearchDataListWrapper();
                                                                     csw.ContactType=ctlist;
                                                                     return csw;
                                                                 }
}




Thursday, 14 September 2017

SLDS - Tooltip Example

 <div class="slds-grid slds-wrap slds-grid--pull-padded" >
                            <div class="slds-col--padded slds-size--1-of-3 slds-medium-size--1-of-3 slds-large-size--1-of-3">
                                <div class="slds-form-element" onmouseover="{!c.showempinfo}" onmouseout="{!c.hideempinfo}">
                                    <div class="slds-form-element__control slds-input-has-icon slds-input-has-icon_right">                                  
                                        <lightning:icon class="icn slds-icon slds-input__icon slds-input__icon_right slds-icon-text-default" iconName="utility:info" size="small"  />
                                        <ui:inputNumber aura:id="contribution" class="slds-input" value="{!v.groupAccount.employeeContribution}" placeholder="Employee Contribution" />
                                    </div>
                                </div>
                                <div class="slds-popover slds-popover_tooltip slds-nubbin_bottom-left slds-fall-into-ground" role="tooltip" aura:id="empinfo" style="position: absolute; top: -32px; left: 275px;">
                                    <div class="slds-popover__body">
                                       This text will show as a tooltip on placing the mouse over the component. on removing the mouse the tooltip hides itseflf.
                                    </div>
                                </div>
                            </div>
</div>




controller.js

    showempinfo : function(component, event, helper){
        console.log('showempinfo success');
        var cmpTarget=component.find('empinfo');
         $A.util.removeClass(cmpTarget, 'slds-fall-into-ground');
        $A.util.addClass(cmpTarget, 'slds-rise-from-ground');
    },
    hideempinfo : function(component, event, helper){
        console.log('hideempinfo success');
        var cmpTarget=component.find('empinfo');
         $A.util.removeClass(cmpTarget, 'slds-rise-from-ground');
        $A.util.addClass(cmpTarget, 'slds-fall-into-ground');
    }

Tuesday, 12 September 2017

Salesforce - User Trigger

trigger UserTrigger on User (after insert) {  
    Map<Id,Id> userAccMap=new Map<Id,Id>();
    Id novatechprofileId;
    if(trigger.isInsert && trigger.isafter){
        try{
            novatechprofileId=[SELECT Id FROM Profile WHERE NAME='Novatech Customer Community Plus Login User' limit 1].Id;
        }catch(QueryException qe){
            system.debug('unable to get profile for novatech due to '+qe);
        }
        //query new user details
        for(User u:[SELECT Id, ProfileId, IsActive,ContactId,AccountId FROM User WHERE Id IN:Trigger.newMap.keyset()]){              
            //get user profile
            if(novatechprofileId!=null && novatechprofileId==u.ProfileId){
                if(u.AccountId!=null)
                    userAccMap.put(u.Id,u.AccountId);
            }
        }
    }
   //change the user
   UserTriggerHelper.shareRecords(userAccMap);
}



here is the helper class



public class UserTriggerHelper {
    @future
    public static void shareRecords(Map<Id,Id> userAccMap){
        System.debug('userAccMap:'+userAccMap);
        //get accounts from contacts  
        List<Account> parentaccs=[SELECT Id,parentId from Account WHERE Id IN:userAccMap.values()];
        List<Account> childaccs=[SELECT Id,parentId FROM Account WHERE ParentId IN:userAccMap.values()];
        childaccs.addAll(parentaccs);
        System.debug('child acclist: '+childaccs);
        List<AccountShare> outacclist=new List<AccountShare>();
        //Share Account access to it's children
        for(Id userId:userAccMap.keySet()){
            //get all children
            for(Account child:childaccs){
                //check if accid is belongs to useraccmap
                if(child.parentid!=null && (userAccMap.get(userId)==child.parentid)
                   || (userAccMap.get(userId)==child.Id)) {
                       outacclist.add(new AccountShare(AccountId=child.Id,
                                                       UserOrGroupId=userId,
                                                       AccountAccessLevel='Edit',
                                                      OpportunityAccessLevel='None',
                                                      CaseAccessLevel='Edit',
                                                      ContactAccessLevel='Read'));
                   }
            }
        }
        System.debug('sharedlist: '+outacclist);
        try{
            insert outacclist;
        }catch(Exception e){
            System.debug('Unable to share records due to '+e+'\n'+e.getStackTraceString());
        }
    }
}

Saturday, 9 September 2017

vlocity - embed a vlocity card in a visualforce page

Clone consolecards.vf like this,

<apex:page docType="html-5.0" applyHtmlTag="false" showHeader="false" sidebar="false" standardStylesheets="false" controller="vlocity_ins.CardCanvasController" >
<html xmlns:ng="http://angularjs.org" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ng-app="myApp" class="ng-cloak"  style="height:100%"
dir="{!IF(isLanguageRTL, 'rtl', 'ltr')}">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<style type="text/css">
body {
margin: 0px !important;
padding: 0px !important;
background: #f9f9f9;
}
</style>

<apex:stylesheet value="{!URLFOR($Resource.vlocity_ins__vlocity_assets, '/css/vlocity.css')}"/>

<!-- Salesforce Console API -->
<apex:includeScript value="/support/console/34.0/integration.js"/>

</head>
<body>

<!-- Component loads the vloc-layout and cards - defaults to Grid if no layout parameter is present -->
<!-- <c:CardLayoutComponent layout="Grid" controllers="myCtrl" modules="myApp"/> -->


<vlocity_ins:CardLayoutComponent layout="census_card" modules="myApp"/>


<script type="text/javascript">
var myApp = angular.module('myApp',['forceng','consoleCards']);
</script>

</body>
</html>
</apex:page>




pass card name to the layout attribute in

<vlocity_ins:CardLayoutComponent layout="census_card" modules="myApp"/>


name the page as 'CensusCard'

pass the card param value like, suppose it is params.id='0013B00000E01azQAB',

url will be like,

https://c.cs50.visual.force.com/apex/CensusCard?id=0013B00000E01azQAB


Wednesday, 6 September 2017

vlocity - Read parameters from url and pass those values to apex class from a vlocity UI template


Below code works for this scenario,


vlocity.cardframework.registerModule.controller('networkController', function($scope,dataService) {
 
   $scope.list={
        text1:'',
        text2:''
    };
 
    $scope.init=function(){
        //read url parameters
        var searchParams = new URLSearchParams(window.parent.location.search);
        var effective_date=searchParams.get("effective_date");
        var plan_type=searchParams.get("plan_type");
        var quote_Id=searchParams.get("quoteId");
        console.log('effective_date: '+effective_date);
        $scope.effective_date=effective_date;
        $scope.plan_type=plan_type;
        $scope.quote_Id=quote_Id;
        //pass those parameters to apex function
         var className = 'ProductAttributeRemote';
            var classMethod = 'getMedicalProducts';
            console.log('className :'+className);
            console.log('classMethod :'+classMethod);
            console.log('effective_date'+effective_date);
            console.log('plan_type'+plan_type);
            console.log('quote_Id'+quote_Id);
         
            if(className && classMethod) {
                var inputMap = {};
                inputMap.effective_date = effective_date;
                inputMap.plan_type = plan_type;
                inputMap.quote_Id = quote_Id;
               dataService.doGenericInvoke(className, classMethod,angular.toJson(inputMap),null)
               .then((data) => {
                    // Handle callout response
                   console.log('call out data:'+JSON.stringify(data));
                })
                .catch((error)=>{
                    // Handle error
                    console.log('error :',err);
                });
            }
    }
        // Your code goes here
$scope.changeMedicalPlans=function(){
    console.log('hi');
    //get url parameter

    var scp = $scope;
    console.log(scp);
   console.log('text1');
   var loc = window.location.toString();
   console.log(loc);
 
   var param = loc.split('?')[1],
    iframe = document.getElementById('iFrameResizer0');

iframe.src = iframe.src + '?' + params;
console.log('ifrmasrc'+iframe.src );
 
$scope.list.text1 = $scope.MedicalPlan;
$scope.$parent.$parent.updateDatasource($scope.list);
console.log($scope.list.text1);
}
$scope.changeDeductible=function(){
    console.log('text2');

$scope.list.text2 = $scope.Deductible;
$scope.$parent.$parent.updateDatasource($scope.list);
console.log($scope.list.text2);
}
   
//}])


//vlocity.cardframework.registerModule.controller('logoController', ['$scope', //function($scope) {

$scope.goldLogo=false;
$scope.silverLogo=false;
$scope.bronzeLogo=false;
 
   $scope.checkLogo=function(name){
     
      // console.log('Entered into check logo method');
     var logoName = name.split(/\s+/);
        if(logoName[0]==="Gold"){
            $scope.goldLogo=true;
            $scope.silverLogo=false;
            $scope.bronzeLogo=false;
            return true;
        }
        else if(logoName[0]==="Silver"){
            $scope.silverLogo=true;
            $scope.goldLogo=false;
            $scope.bronzeLogo=false;
            return true;
        }
        else if(logoName[0]==="Bronze"){
            $scope.goldLogo=false;
            $scope.silverLogo=false;
            $scope.bronzeLogo=true;
            return true;
        }
     
   };
   
});


place init method as

<div ng-controller="myCtrl" ng-init="init()"></div>