• SK SGS
  • NEWBIE
  • 10 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 4
    Replies
Hi Folks,

I have scenario like Account object has few opportunites on it's related list. When selecting the account in newly created opportunity record or existing opportunity records, need to display all the account related opportunities as a picklist values in one of the custom picklist field(say parent opportunity) of opportunity object. When selecting one of the picklist value(opportunity) as a parent opportunity based on the parent opportunity field values, opportunity field values should be auto populated.
I tried this scenario with automation tools but it won't work. i am new to development. Anyone can suggest or provide code samples how to achieve this scenario. i know it's a complex scenario need to complete this asap as per deadline

Thanks in Advance..
  • September 03, 2020
  • Like
  • 0
Hi All,
i am writing the test class for getting code coverage and deploy it to sandbox for that unable to get the 75%.if any one can suggest to cover the code coverage.my apex class is

public without sharing class PC_OpportunitySearchCmpCntrl {
    
    public class OpptywrapperClass{
        
        @AuraEnabled public boolean selectOppty {get;set;}
        @AuraEnabled public Opportunity Oppty   {get;set;}
        
        public OpptywrapperClass(Opportunity Opp){
            this.Oppty=Opp;
        }
    }
    
    @AuraEnabled
    public static string PerformIntialLoad(){
        
        string jsonString;
        list<String> StageValueList=new list<String>();
        StageValueList.add('All');
        
        Schema.DescribeFieldResult StagefieldResult = Opportunity.StageName.getDescribe();
        list<Schema.PicklistEntry> StagenameValues = StagefieldResult.getPicklistValues();

        for(Schema.picklistEntry objPicklistEntry : StagenameValues) {
            
            StageValueList.add(objPicklistEntry.getLabel());
            
        }
        jsonString = JSON.serialize(StageValueList);
        return jsonString;
        
    }
    
    @AuraEnabled 
    public static list<OpptywrapperClass> PopulateAllOppty(string RecordType){
        //and recordtypeid=:SalesTypeId
        string accId;
        string accType;
        String userids=UserInfo.getUserId();
        list<Opportunity> oppList;
        accId = [select Contact.accountId from User where id = :UserInfo.getUserId()].Contact.AccountId;
        accType = [select account.type from Account where id = :accId].type;
        Id OpptyRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(RecordType).getRecordTypeId();
        system.debug('##### accId accType SalesTypeId '+accId+' '+accType+' '+OpptyRecTypeId+' '+userids);
        oppList = [select Id, Name, stagename,CloseDate,ownerid, Account.name ,Account.BillingCountry, Sold_to_Partner__c, Tier2__c
                   from Opportunity 
                   where (sold_to_Partner__c = :accId or Tier2__c = :accId)
                   and Isclosed=false 
                   and Id not in (select OpportunityId from OpportunityTeamMember where userid=:userids )
                   and recordtypeid=:OpptyRecTypeId
                   order by Name limit 1000];
        system.debug('###### oppList '+oppList);
        list<OpptywrapperClass> OpptyWrpList=new list<OpptywrapperClass>();
        for(Opportunity opp:oppList){
            OpptyWrpList.add(new OpptywrapperClass(opp));
        }
        system.debug('##### OpptyWrpList '+OpptyWrpList);
        return OpptyWrpList;
    }
    
    @AuraEnabled
    public static list<OpptywrapperClass> SearchOpportunityWithfiler(string SoqlFilter, String RecordType){
        list<OpptywrapperClass> OpptyWrpList=new list<OpptywrapperClass>();
        string accId=[select Contact.accountId from User where id = :UserInfo.getUserId()].Contact.AccountId;
        Id SalesTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(RecordType).getRecordTypeId();
        String userids=UserInfo.getUserId();
        string query='select Id, Name, stagename,CloseDate,ownerid, Account.name ,Account.BillingCountry, Sold_to_Partner__c, Tier2__c from Opportunity where (sold_to_Partner__c = '+'\''+accId +'\'' + ' or Tier2__c ='+'\''+accId +'\''+') and Isclosed=false and Id not in (select OpportunityId from OpportunityTeamMember where userid='+'\''+userids+'\''+') and recordtypeid='+'\''+SalesTypeId+'\'';
        system.debug('#### query '+query);
        if(SoqlFilter!=null){
            query+=SoqlFilter+' order by Name limit 1000';
        }else{
            query+=' order by Name limit 1000';
        }
        list<Opportunity> Opplist=Database.query(query);
        if(!Opplist.isempty()){
            for(Opportunity Opp:Opplist){
                OpptyWrpList.add(new OpptywrapperClass(opp));
            }
        }
        return OpptyWrpList;
    }
    
    @AuraEnabled
    public static boolean CheckProfileAccessForSixRec(){
        boolean  isAllowedToAddMoreThanSixOpp=false;
        system.debug('The Profile Id is '+userinfo.getProfileId());
        Profile p = [Select Name from Profile where Id =: userinfo.getProfileid()]; 
        String pname = p.name;
        system.debug('profile name is '+pname);
        isAllowedToAddMoreThanSixOpp = false; 
        system.debug('the is allowed variable is '+isAllowedToAddMoreThanSixOpp);
        List<string> allowedProfiles = new List<String>(); 
        PartnerProfileIAllowedAddAllOpp__mdt[] allowedProfileNames = [SELECT ProfileName__c FROM PartnerProfileIAllowedAddAllOpp__mdt];
        for(PartnerProfileIAllowedAddAllOpp__mdt ap :allowedProfileNames ){
            allowedProfiles.add(ap.ProfileName__c);
        }
        system.debug('the is allowed profiles are '+allowedProfiles);
        
        // loop to check if the user belongs to one of the allowed profiles. 
        for(String pn : allowedProfiles){
            if (pname == pn ){
                isAllowedToAddMoreThanSixOpp = true;
                system.debug('User belongs to the allowed profile '+pn);        
            }
        }
        
        return isAllowedToAddMoreThanSixOpp;      
     }
    
   //public List<Opportunity> oppList;
    @AuraEnabled
    public static boolean updateSelectedRecords(string selectedOpptyList){

        boolean result=false;
        system.debug('#### selectedOpptyList '+selectedOpptyList);
        String userids=UserInfo.getUserId();
        String role ='Partner';  
        String accessLevel ='Edit';
        set<Id> OpptyIdSet=new set<Id>();
        List<Visible_to_Partners__c> vpc = new  List<Visible_to_Partners__c>();
        Visible_to_Partners__c[] m_oppMembers = new List<Visible_to_Partners__c> ();
        List<OpptywrapperClass> selectedOpptyWrpList = (List<OpptywrapperClass>)JSON.deserialize(selectedOpptyList, List<OpptywrapperClass>.class);
        system.debug('### for loop starting '+selectedOpptyWrpList.isempty()+' '+selectedOpptyWrpList.size());
        
        for(OpptywrapperClass cw: selectedOpptyWrpList){
            
            OpptyIdSet.add(cw.Oppty.id);
            Visible_to_Partners__c tmSTP = new Visible_to_Partners__c(PartnerName__c=userids,Opportunity_Name__c=cw.Oppty.id,role__c=role,Opportunity_Access__c=accessLevel,ownerid=cw.Oppty.ownerid);   
            m_oppMembers.add(tmSTP);
            
        }
        
        try{
            vpc = [select id from Visible_to_Partners__c where PartnerName__c=:userids and Opportunity_Name__c in:OpptyIdSet];
            //system.debug('##### vpc '+vpc);
        }catch(Exception e){
            System.debug('***********'+e);
        }
        
        system.debug('##### vpc '+vpc);
        system.debug('###### m_oppMembers '+m_oppMembers);
        try{
            if(vpc.size()>0){
                delete vpc;
            }
            if(!m_oppMembers.isempty()){
                insert m_oppMembers;
                result=true;
            }
        }catch(DMLException e){
            System.debug('Exception in adding user to sales team: ' + e.getMessage());
        }
        system.debug('#### method end '+result);
        return result;    
        
    }
}

thanks in advance..
  • December 27, 2018
  • Like
  • 0
Hi All,
i created the one lighnting component to display the opportunity records in search componet.but it not working properly.unable to arrange the fileds in component using slds. i am new to LEX. Can any one help to todo this.the alignments of fields are Account Name    Opportunity Name     Stage in the same horizantal line with text boxes also display the search results/records in another drop down  section in table format like
 Select   OppName   AccName   BilligngCountry  CloseDate   Stage   like this way.i will add my code for your reference

Apex Controller
public with sharing class searchAccountController {
 
 @AuraEnabled
 public static List <Opportunity> fetchOpportunities(String searchKeyWord) {
  String searchKey = searchKeyWord + '%';
  List < Opportunity > returnList = new List < Opportunity > ();
  List < Opportunity > lstOfOpp = [select id, Name, Account.Name,Account.BillingCountry, CloseDate,StageName from Opportunity
                                   where Name LIKE: searchKey LIMIT 1000];
 
  for (Opportunity opp: lstOfOpp) {
   returnList.add(opp);
  }
  return returnList;
 }
}
component .cmp
<!--<aura:component implements="force:hasRecordId,force:appHostable,flexipage:availableForRecordHome,forceCommunity:availableForAllPageTypes,forceCommunity:searchInterface" access="global"> 
    <aura:attribute name="objOpp" type="Opportunity" />
    <aura:attribute name="objAcc" type="Account" />
    
    <div class="slds-form slds-form_horizontal">
    <div class="slds-brand-band slds-brand-band_medium">
        <div class="slds-align_absolute-center slds-m-top_medium">
               
                   <div class="slds-form-element">
                    <label class="slds-form-element__label" for="input-id-01">Text Input</label>
                <div class="slds-form-element__control">
                      <input type="text" id="input-id-01" class="slds-input" />
                   </div>
                  </div>
            </div>
                                 
                
        
        </div>
    </div>
    
    
</aura:component>-->

<aura:component implements="force:hasRecordId,force:appHostable,flexipage:availableForRecordHome,forceCommunity:availableForAllPageTypes,forceCommunity:searchInterface" access="global" controller="searchAccountController">    
    <aura:attribute name="objOpp" type="Opportunity" />
    <aura:attribute name="objAcc" type="Account" />
    <aura:attribute name="searchResult" type="List" />
    <aura:attribute name="searchKeyword" type="String"/> 
    <aura:attribute name="Message" type="boolean" default="false"/>
    
    <div class="slds-m-around_medium">
       <!-- SEARCH INPUT AND SEARCH BUTTON--> 
        <lightning:layout>
            <div class="slds-align_absolute-center slds-m-top_medium">
             <lightning:button variant="neutral" label="Search" onclick="{!c.Search}" />
        
           </div>
            <div class="slds-grid slds-wrap slds-grid_pull-padded slds-m-top_large">
              <lightning:layoutItem size="3">
                <lightning:input value="{!v.searchKeyword}" label="Account Name" padding="around-medium"/>
                <lightning:input value="{!v.searchKeyword}" label="Opportunity Name" padding="around-medium"/>
                <lightning:input value="{!v.searchKeyword}" label="Stage" padding="around-medium"/>
                               
             </lightning:layoutItem>
            <!--<lightning:layoutItem size="2" padding="around-small">
                <lightning:button onclick="{!c.Search}" variant="brand" label="Search" iconName="utility:search"/>             
            </lightning:layoutItem>-->
            </div>
        </lightning:layout>
       
        
        <!-- ERROR MESSAGE IF NOT RECORDS FOUND--> 
        <aura:if isTrue="{!v.Message}">
            <div class="slds-notify_container slds-is-relative">
                <div class="slds-notify slds-notify_toast slds-theme_error" role="alert">
                    <div class="slds-notify__content">
                        <h2 class="slds-text-heading_small">No Records Found...</h2>
                    </div>
                </div>
            </div>
        </aura:if>
       
       <table class="slds-table slds-table_cell-buffer slds-table_bordered">
            <thead>
            <tr class="slds-line-height_reset">
              <!--<div class="slds-checkbox"> -->
            <th class="slds-checkbox" scope="col">
            <div class="slds-truncate" title="Select">Select</div>
             </th>
            <th class="slds-text-title_caps" scope="col">
            <div class="slds-truncate" title="Opportunity Name">Opportunity Name</div>
            </th>
            <th class="slds-text-title_caps" scope="col">
            <div class="slds-truncate" title="Account Name">Account Name</div>
            </th>
            <th class="slds-text-title_caps" scope="col">
            <div class="slds-truncate" title="Billing Country">Billing Country</div>
            </th>
            <th class="slds-text-title_caps" scope="col">
            <div class="slds-truncate" title="Close Date">Close Date</div>
            </th>
            <th class="slds-text-title_caps" scope="col">
            <div class="slds-truncate" title="Stage">Stage</div>
            </th>
            </tr>
            </thead>
            <tbody>
                
           </tbody>

            
        </table>
    </div>
</aura:component>
controller.js
 
({
    Search: function(component, event, helper) {
        var searchField = component.find('searchField');
        var isValueMissing = searchField.get('v.validity').valueMissing;
        // if value is missing show error message and focus on field
        if(isValueMissing) {
            searchField.showHelpMessageIfInvalid();
            searchField.focus();
        }else{
          // else call helper function 
            helper.SearchHelper(component, event);
        }
    },
})
helper.js


({
    SearchHelper: function(component, event) {
        // show spinner message
         component.find("Id_spinner").set("v.class" , 'slds-show');
        var action = component.get("c.fetchOpportunities");
        action.setParams({
            'searchKeyWord': component.get("v.searchKeyword")
        });
        action.setCallback(this, function(response) {
           // hide spinner when response coming from server 
            component.find("Id_spinner").set("v.class" , 'slds-hide');
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
                
                // if storeResponse size is 0 ,display no record found message on screen.
                if (storeResponse.length == 0) {
                    component.set("v.Message", true);
                } else {
                    component.set("v.Message", false);
                }
                
                // set numberOfRecord attribute value with length of return value from server
                //component.set("v.TotalNumberOfRecord", storeResponse.length);
                
                // set searchResult list with return value from server.
                component.set("v.searchResult", storeResponse); 
                
            }else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
            }else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + 
                                    errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
})
 
thanks in advance
 




 
  • December 20, 2018
  • Like
  • 0

Dear Community,

I want to certify as the Community Cloud Consultant/Sales Cloud Consultant/Service Cloud Consultant.Where Can i get the practice material for this certifications. Can any one suggest where  i can get the docs.

thanks in advance,
sg
 

  • December 20, 2018
  • Like
  • 0
Hi Community,
i am new to the community cloud and also i need to learn about community cloud.can any one suggest urls,pdf and also any kind of materials,links where i can get detailed information of community cloud.How to we work with community cloud and how to assign users to this cloud.
regards,
GS
  • November 13, 2018
  • Like
  • 0
Dear Community,
what is the order of the objects in Sales cloud and Service Cloud in Salesforce.as of now i know the which objects support sales and service cloud.
in sales cloud it supports accounts,contacts,Opportunities,Products,Campaign,...........etc.then what is the order from these objects.From which object we start working on sales cloud.
In service cloud it supports Accounts,contacts,cases,solutions etc.then what is the order in those sales and service clouds.can any one explain me with order.
like campaign-->account --> contact--> Lead-->Opportunity-->,......etc

regards
sgs
  • October 23, 2018
  • Like
  • 0
Hi All,
I am generating the pdf for Account object using lightning components .In that i want to use some styles and markups with all the fields of selected  record in detailed page.As of now i am unable to get the all the fields and styles.components code is  working fine and generate the pdf.
But unable to get all the fields in pdf form.how to get the all the fields with styles,markups like visualforce pages in LEX..how to use the standard/custom styles in LEX.any one can please provide the solution for this,i am new to the LEX.

my components are

Apex class
public class TextVFPDFController {
    public Account acc{get;set;}
    public TextVFPDFController(){
        Id accId = apexpages.currentpage().getparameters().get('id');
        acc = [select Id,Name,Type,Rating,Phone from Account where id=: accId];
    }
}
VF Page
<apex:page controller="TextVFPDFController" renderAs="PDF">
    <apex:includeLightning rendered="true" /> 
    </apex:page>

Component.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="TestAppController">
    
    <lightning:button variant = "brand" label = "Generate Pdf" onclick = "{!c.savePDF}" />
</aura:component>

Client-side controller.js
({
    savePDF : function(component, event, helper) {
       
        var action = component.get("c.savePDFAccount");
        action.setParams({recordId : component.get("v.recordId")});
               
        action.setCallback(this, function(response) {
           
            var state = response.getState();
            if (state === "SUCCESS") {
                
                alert('Attachment saved successfully');
                
                console.log('pdf created successfully');
                
                $A.get('e.force:refreshView').fire();
                window.location.reload();
            }
            else if (state === "ERROR") {
                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);
    }
})

Server-side controller.cls

public class TestAppController {
    @auraEnabled
    public static void  savePDFAccount(Id recordId){
        PageReference pdfPage = new PageReference('/apex/TextVFPDF');
        pdfPage.getParameters().put('Id',recordId);
        Blob pdfContent = pdfPage.getContent();
                
        Attachment attach1= new Attachment();
        attach1.ParentId = recordId;
        //attach1.ParentId = parentId;
        attach1.Name ='Test Attachment for PDF';
        attach1.Body = pdfContent;
        attach1.contentType = 'application/pdf';
        insert attach1;
            }
}

Thanks in advance
sgs
 
  • October 11, 2018
  • Like
  • 0
Hi All,
I am generating  Pdf for Account object using lightning components.in that client side controller file it will through 
component.setParams() callback failed..i passed the accountId also but getting same error.can any one help me on this issue becuase i am new to lightning exp.
my code is
apex cls
public class TextVFPDFController {
    public Account acc{get;set;}
    public TextVFPDFController(){
        Id accId = apexpages.currentpage().getparameters().get('id');
        acc = [select id,Name from Account where id=: accId];
    }
}

vf page
<apex:page controller="TextVFPDFController" renderAs="PDF">
    {!acc.Name}
</apex:page>

component

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="TestAppController" >
    <aura:attribute name = "accountId" type = "Account" />
    <lightning:button variant = "brand" label = "Generate Pdf" onclick = "{!c.savePDF}" />
</aura:component>

client-side controller.js

({
    savePDF : function(component, event, helper) {
        var action = component.get("c.savePDFAccount");
        action.setCallback(this, function(response) {
            component.setParams({"recordId" : component.get("v.accountId")});
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.recordId",response.getReturnValue());
                alert('Attachment saved successfully');
                              
            }        
               else {
                        console.log("Unknown error");
                    }
                
        });
        $A.enqueueAction(action);
    }
})

server-side controller.cls

public class TestAppController {
    @auraEnabled
    public static void savePDFAccount(String recordId){
        PageReference pdfPage = new PageReference('/apex/TextVFPDF');
        pdfPage.getParameters().put('Id',recordId);
        Blob pdfContent = pdfPage.getContent();
        Attachment attach1= new Attachment();
        //attach1.ParentId = parentId;
        attach1.Name = 'Test Attachment for PDF';
        attach1.Body = pdfContent;
        attach1.contentType = 'application/pdf';
        insert attach1;
        
    }
}

and the error is

Uncaught Error in $A.getCallback() [component.setParams is not a function]
Callback failed: apex://TestAppController/ACTION$savePDFAccount

can any one help this issue
thanks in advance
 
  • October 10, 2018
  • Like
  • 1
Dear Community,
I am new to Lightning experience,i have some knowledge about lightning.i tried to generate the pdf for Account or any standard or custom object.i wrote the some logic the pfd is generated with empty sheet,i want all the fields of the perticular object which is i mentioned.i think i missed some logic in my components/controllers.
can any one suggest where i did mistake and also can tell me how to generate the pdf for perticular object either custom or standard
my code is 
Apex class:
public class DataDisplayController {
    public String PDFData{get;set;}
    
    public DataDisplayController(){
        
        PDFData = '';
    }
    public PageReference downloadPDF(){
        System.PageReference pageRef = new System.PageReference('/apex/PDFGenerator');
        //ensure pdf downloads and is assigned with defined name
        pageRef.getHeaders().put('content-disposition', 'attachment; filename=TestPDF.pdf');
        
        return pageRef;
    }
    }
Component:
<aura:component >
    <aura:attribute name = "sendData" type = "Account"/>
    <lightning:button label = "Download Document" onclick = "{!c.downloadDocument}" />
    
</aura:component>

client-side controller.js
({
 downloadDocument : function(component, event, helper){

  var sendDataProc = component.get("v.sendData");
  var dataToSend = {
     "label" : "This is test"
  }; //this is data you want to send for PDF generation

  //invoke vf page js method
  sendDataProc(dataToSend, function(){
              
  });
 }
})
Helper.js
({
    helperMethod : function(component,callbackMethod) {
        var action = component.get("c.download");
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var generatePdf = reponse.getReturnValue();
                component.set("v.sendData",generatePdf);
                console.log('pdf generated successfully');
                
            }
            else{
                console.log('unable to generate the pdf');
            }
        });
        $A.enqueueAction(action);
        
    }
})
VF Page:
<apex:page controller="DataDisplayController" showHeader="false">
    <apex:includeLightning />
    
    <apex:form>
        <apex:inputHidden id="hidData" value="{!PDFData}"/>
        <apex:actionFunction name="jsGeneratePDF" action="{!downloadPDF}"/>
        <div id = "lightning" />
        
        <script>
            function saveData(data, callback){
            var hidData = document.getElementById('{!$Component.hidData}');
            hidData.value = JSON.stringify(data);
            
            //invoke PDF Generation
            jsGeneratePDF();
         
            //invoke callback;
            if(typeof callback == 'function') callback();
        }
        
        
        function loadComponents(){
            console.log("Loading lightning component: DataProcessor");
            
            $Lightning.use("c:LightningPDFGeneratorDemoApp", function() {
                $Lightning.createComponent("c:DataProcessor",
                { 
                    sendData : saveData
                },
                "lightning",
                function(cmp) {
                    // do some stuff
                });
            });
        }
        
        loadComponents();
        </script>            
           </apex:form>
</apex:page>

<apex:page controller="DataDisplayController"  renderAs="pdf">
    {!PDFData}
</apex:page>

App:
<aura:application extends = "ltng:outApp" >
    <c:DataProcessor />
    
</aura:application>

thanks in advance
  • October 10, 2018
  • Like
  • 0
Hi All,
How to create the Test class for triggers?can you any one explain?and below is the sample trigger,then how to create the test class for this.
  trigger CheckForDefaultCustAddress on CustomerAddress__c (before insert,before update) 
{
    Set<String> shipAddress = new Set<String>();
    Set<Id> accountId = new Set<Id>();
    Map<String, CustomerAddress__c> customerAddressMap = new Map<String, CustomerAddress__c>();
    Map<String, CustomerAddress__c> accountCustomerAddress = new Map<String, CustomerAddress__c>();
    Map<String, CustomerAddress__c> accountDefaultCustomerAddress = new Map<String, CustomerAddress__c>();
    
    For(CustomerAddress__c p : Trigger.New)
    {
        
        If(p.BillingAddress__c != null)
        {
            shipAddress.add(p.BillingAddress__c);
        }
        If(p.CustomerName__c!= null)
        {
            accountId.add(p.CustomerName__c);
        }
    }
    //to check Same address is present in customer 
    For(CustomerAddress__c p :[SELECT Id,BillingAddress__c,CustomerName__c FROM CustomerAddress__c WHERE BillingAddress__c =:shipAddress AND CustomerName__c =: accountId])
    {
        customerAddressMap.put(p.BillingAddress__c+'-'+p.CustomerName__c, p);
    }
    
    // Check for Address is there for Account OR not
    For(CustomerAddress__c p :[SELECT Id,CustomerName__c FROM CustomerAddress__c WHERE CustomerName__c =: accountId])
    {
        accountCustomerAddress.put(p.Id+'-'+p.CustomerName__c, p);
    }
    
    For(CustomerAddress__c p :[SELECT Id,CustomerName__c FROM CustomerAddress__c WHERE CustomerName__c =: accountId AND PrimaryDefaultAddress__c = TRUE])
    {
        accountDefaultCustomerAddress.put(p.Id+'-'+p.CustomerName__c, p);
    }
    
    
    For(CustomerAddress__c p : Trigger.New)
    {
        String keyChek = p.BillingAddress__c+'-'+p.CustomerName__c;
        
        if(accountCustomerAddress.size()<1)
        {
            System.debug('no address first one so make it default');
            p.PrimaryDefaultAddress__c=true;
        }   
        else if(Trigger.isInsert && p.PrimaryDefaultAddress__c)
        {
            if(accountDefaultCustomerAddress.size()>=1)
            {
                System.debug('already Default Address is there');
                p.name.addError('One Account have only one Default Address');
            }    
            
        }        
        else if(Trigger.isInsert && customerAddressMap.containsKey(keyChek))
        {
                 System.debug('already same address is there');  
                 p.name.addError('already same address is there');
        }
        
       
    }     
}
thanks
  • October 04, 2018
  • Like
  • 0
Hi All,
i am new to the Apex Testing,can any tell me how to write the Test Class for the Existing  Apex Class.
Apex class:
public class NewProductNoteComponentController 
{
    public class My1Exception extends Exception {}
    @AuraEnabled
    public static Event getMeetingRec(Id meetingId) 
    {
        // Perform isAccessible() checks here
        return [SELECT id, subject FROM Event WHERE Id = :meetingId];
    }
    
    @AuraEnabled
    public static String saveProductNote(CustomerProduct__c productNote, Id meetingId) 
    {
        
        //Query for the CustomerProduct__c record types
        List<RecordType> rtypes = [Select Id From RecordType where Name='MoM Product' AND SobjectType = 'CustomerProduct__c'];
        Event acId=[SELECT WhatId,MeetingName__c FROM Event WHERE Id = :meetingId];
        CustomerProduct__c newRecord = new CustomerProduct__c();
        
        system.debug('Product name in CP '+productNote.Product__c);
        system.debug('meeting Id in CP '+meetingId);
        
        List<CustomerProduct__c> checkCPRecord=[SELECT Id FROM CustomerProduct__c WHERE Product__c =:productNote.Product__c AND MeetingId__c =:meetingId];    
        
        if(checkCPRecord.size()>0)
        {
            System.debug('check condition');
            return ''; 
           
        }
        else
        {
            // Perform isAccessible() and isUpdateable() checks here
            newRecord.Product__r = productNote.Product__r;
            newRecord.Account__c=acId.WhatId;
            newRecord.MeetingName__c=acId.MeetingName__c;
            newRecord.MeetingNotes__c = productNote.MeetingNotes__c;
            newRecord.MeetingId__c = meetingId;
            newRecord.recordtypeid = rtypes.get(0).Id;
            try
            {
                
                insert newRecord;
                
             }
            catch(DmlException ex)
            {
                throw new AuraHandledException(ex.getMessage());
            }    
           return 'Record Added Successfully';  
        }
           
    }           

}
i am tried with another test class for sample apex class but it will through the error for method does not exist.can any one give any idea for this
apex class
public class Clone_Quote 
{
    
     @AuraEnabled 
    public static  Quote getQuoteDetails(string recordId)
    {
        
        return [SELECT AccountId,AgentName__c,BankDetails__c,BankName__c,BillingAddress,BillingCity,
                BillingCountry,BillingGeocodeAccuracy,BillingLatitude,BillingLongitude,BillingName,BillingPostalCode,
                BillingState,BillingStreet,CommissionType__c,ContactId,ContractId,CurrencyIsoCode,
                CustomerAddress__c,CustomerProduct__c,CustomerType__c,
                DateForTheNextCall__c,DeliveryTerms__c,Description,Email,ExpirationDate,Fax,ModeOfTransport__c,
                OpportunityId,PaymentTerms__c,Phone,PlantAddress__c,Pricebook2Id,Product__c,Quantity__c,
                QuoteOrderForm__c,SalesPrice__c,SalesType__c,ShippingAddress,ShippingCity,ShippingCountry,
                ShippingGeocodeAccuracy,ShippingHandling,ShippingLatitude,ShippingLongitude,ShippingName,
                ShippingPostalCode,ShippingState,ShippingStreet,Status,Type__c FROM Quote WHERE Id=:recordId];
       
        
    }    

}
test class
@isTest
private class Clone_Quote_TC {
     @isTest static  void myTest() {
        Clone_Quote q1 = new Clone_Quote();
        q1.getQuoteDetails();
         
         }
    }
thanks in advance.
  • October 03, 2018
  • Like
  • 0
Hi All,
I am generating  Pdf for Account object using lightning components.in that client side controller file it will through 
component.setParams() callback failed..i passed the accountId also but getting same error.can any one help me on this issue becuase i am new to lightning exp.
my code is
apex cls
public class TextVFPDFController {
    public Account acc{get;set;}
    public TextVFPDFController(){
        Id accId = apexpages.currentpage().getparameters().get('id');
        acc = [select id,Name from Account where id=: accId];
    }
}

vf page
<apex:page controller="TextVFPDFController" renderAs="PDF">
    {!acc.Name}
</apex:page>

component

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="TestAppController" >
    <aura:attribute name = "accountId" type = "Account" />
    <lightning:button variant = "brand" label = "Generate Pdf" onclick = "{!c.savePDF}" />
</aura:component>

client-side controller.js

({
    savePDF : function(component, event, helper) {
        var action = component.get("c.savePDFAccount");
        action.setCallback(this, function(response) {
            component.setParams({"recordId" : component.get("v.accountId")});
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.recordId",response.getReturnValue());
                alert('Attachment saved successfully');
                              
            }        
               else {
                        console.log("Unknown error");
                    }
                
        });
        $A.enqueueAction(action);
    }
})

server-side controller.cls

public class TestAppController {
    @auraEnabled
    public static void savePDFAccount(String recordId){
        PageReference pdfPage = new PageReference('/apex/TextVFPDF');
        pdfPage.getParameters().put('Id',recordId);
        Blob pdfContent = pdfPage.getContent();
        Attachment attach1= new Attachment();
        //attach1.ParentId = parentId;
        attach1.Name = 'Test Attachment for PDF';
        attach1.Body = pdfContent;
        attach1.contentType = 'application/pdf';
        insert attach1;
        
    }
}

and the error is

Uncaught Error in $A.getCallback() [component.setParams is not a function]
Callback failed: apex://TestAppController/ACTION$savePDFAccount

can any one help this issue
thanks in advance
 
  • October 10, 2018
  • Like
  • 1
Hi Folks,

I have scenario like Account object has few opportunites on it's related list. When selecting the account in newly created opportunity record or existing opportunity records, need to display all the account related opportunities as a picklist values in one of the custom picklist field(say parent opportunity) of opportunity object. When selecting one of the picklist value(opportunity) as a parent opportunity based on the parent opportunity field values, opportunity field values should be auto populated.
I tried this scenario with automation tools but it won't work. i am new to development. Anyone can suggest or provide code samples how to achieve this scenario. i know it's a complex scenario need to complete this asap as per deadline

Thanks in Advance..
  • September 03, 2020
  • Like
  • 0
Hi All,
I am generating the pdf for Account object using lightning components .In that i want to use some styles and markups with all the fields of selected  record in detailed page.As of now i am unable to get the all the fields and styles.components code is  working fine and generate the pdf.
But unable to get all the fields in pdf form.how to get the all the fields with styles,markups like visualforce pages in LEX..how to use the standard/custom styles in LEX.any one can please provide the solution for this,i am new to the LEX.

my components are

Apex class
public class TextVFPDFController {
    public Account acc{get;set;}
    public TextVFPDFController(){
        Id accId = apexpages.currentpage().getparameters().get('id');
        acc = [select Id,Name,Type,Rating,Phone from Account where id=: accId];
    }
}
VF Page
<apex:page controller="TextVFPDFController" renderAs="PDF">
    <apex:includeLightning rendered="true" /> 
    </apex:page>

Component.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="TestAppController">
    
    <lightning:button variant = "brand" label = "Generate Pdf" onclick = "{!c.savePDF}" />
</aura:component>

Client-side controller.js
({
    savePDF : function(component, event, helper) {
       
        var action = component.get("c.savePDFAccount");
        action.setParams({recordId : component.get("v.recordId")});
               
        action.setCallback(this, function(response) {
           
            var state = response.getState();
            if (state === "SUCCESS") {
                
                alert('Attachment saved successfully');
                
                console.log('pdf created successfully');
                
                $A.get('e.force:refreshView').fire();
                window.location.reload();
            }
            else if (state === "ERROR") {
                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);
    }
})

Server-side controller.cls

public class TestAppController {
    @auraEnabled
    public static void  savePDFAccount(Id recordId){
        PageReference pdfPage = new PageReference('/apex/TextVFPDF');
        pdfPage.getParameters().put('Id',recordId);
        Blob pdfContent = pdfPage.getContent();
                
        Attachment attach1= new Attachment();
        attach1.ParentId = recordId;
        //attach1.ParentId = parentId;
        attach1.Name ='Test Attachment for PDF';
        attach1.Body = pdfContent;
        attach1.contentType = 'application/pdf';
        insert attach1;
            }
}

Thanks in advance
sgs
 
  • October 11, 2018
  • Like
  • 0
Hi All,
i am new to the Apex Testing,can any tell me how to write the Test Class for the Existing  Apex Class.
Apex class:
public class NewProductNoteComponentController 
{
    public class My1Exception extends Exception {}
    @AuraEnabled
    public static Event getMeetingRec(Id meetingId) 
    {
        // Perform isAccessible() checks here
        return [SELECT id, subject FROM Event WHERE Id = :meetingId];
    }
    
    @AuraEnabled
    public static String saveProductNote(CustomerProduct__c productNote, Id meetingId) 
    {
        
        //Query for the CustomerProduct__c record types
        List<RecordType> rtypes = [Select Id From RecordType where Name='MoM Product' AND SobjectType = 'CustomerProduct__c'];
        Event acId=[SELECT WhatId,MeetingName__c FROM Event WHERE Id = :meetingId];
        CustomerProduct__c newRecord = new CustomerProduct__c();
        
        system.debug('Product name in CP '+productNote.Product__c);
        system.debug('meeting Id in CP '+meetingId);
        
        List<CustomerProduct__c> checkCPRecord=[SELECT Id FROM CustomerProduct__c WHERE Product__c =:productNote.Product__c AND MeetingId__c =:meetingId];    
        
        if(checkCPRecord.size()>0)
        {
            System.debug('check condition');
            return ''; 
           
        }
        else
        {
            // Perform isAccessible() and isUpdateable() checks here
            newRecord.Product__r = productNote.Product__r;
            newRecord.Account__c=acId.WhatId;
            newRecord.MeetingName__c=acId.MeetingName__c;
            newRecord.MeetingNotes__c = productNote.MeetingNotes__c;
            newRecord.MeetingId__c = meetingId;
            newRecord.recordtypeid = rtypes.get(0).Id;
            try
            {
                
                insert newRecord;
                
             }
            catch(DmlException ex)
            {
                throw new AuraHandledException(ex.getMessage());
            }    
           return 'Record Added Successfully';  
        }
           
    }           

}
i am tried with another test class for sample apex class but it will through the error for method does not exist.can any one give any idea for this
apex class
public class Clone_Quote 
{
    
     @AuraEnabled 
    public static  Quote getQuoteDetails(string recordId)
    {
        
        return [SELECT AccountId,AgentName__c,BankDetails__c,BankName__c,BillingAddress,BillingCity,
                BillingCountry,BillingGeocodeAccuracy,BillingLatitude,BillingLongitude,BillingName,BillingPostalCode,
                BillingState,BillingStreet,CommissionType__c,ContactId,ContractId,CurrencyIsoCode,
                CustomerAddress__c,CustomerProduct__c,CustomerType__c,
                DateForTheNextCall__c,DeliveryTerms__c,Description,Email,ExpirationDate,Fax,ModeOfTransport__c,
                OpportunityId,PaymentTerms__c,Phone,PlantAddress__c,Pricebook2Id,Product__c,Quantity__c,
                QuoteOrderForm__c,SalesPrice__c,SalesType__c,ShippingAddress,ShippingCity,ShippingCountry,
                ShippingGeocodeAccuracy,ShippingHandling,ShippingLatitude,ShippingLongitude,ShippingName,
                ShippingPostalCode,ShippingState,ShippingStreet,Status,Type__c FROM Quote WHERE Id=:recordId];
       
        
    }    

}
test class
@isTest
private class Clone_Quote_TC {
     @isTest static  void myTest() {
        Clone_Quote q1 = new Clone_Quote();
        q1.getQuoteDetails();
         
         }
    }
thanks in advance.
  • October 03, 2018
  • Like
  • 0