• pranavshah
  • NEWBIE
  • 150 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 49
    Questions
  • 22
    Replies
Hi All,

I have one requirement where once the screen flow is finished, then its should redirect to list view from where it was originated rather than setting the default value in the return URL.

Can anyone let me know how it can achieved.

Thanks,
Pranav Shah
Dear All, 

I have an requirement where i have to send an mail dynamically to user once review record  get created.
I have created custom HTML Email Template  but in blank body is going...
i am not getting html template which i have created

Below is the code which have written

 EmailTemplate template = [SELECT Id,Name,Description,HtmlValue,Body,Subject,DeveloperName 
                                  FROM EmailTemplate WHERE DeveloperName='Review_Email_Notifications'];
        
        System.debug('templates@@@'+template);
        
        String emailSubject = template.Subject;
         String emailTextBody = template.Body;
        if(!usersObjList.isEmpty()) {     
            for(user emails : usersObjList){
            //String emailSubject = template.getSubject();
                //String emailTextBody = template.getPlainTextBody();
             Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
              //  String[] toAddresses = new String[] {emails.email};  
                    //mail.setSenderDisplayName('Administrator');
                // mail.setToAddresses(toAddresses);
                mail.setSubject(emailSubject);
                mail.setPlainTextBody(emailTextBody);
                //mail.setTreatBodiesAsTemplate(true);
                                
                //mail.setplainTextbody(emailTextBody);  
                mail.setWhatId(varReview.id);    
                mail.setTemplateId(template.Id);
                mail.setSaveAsActivity(false); 
                mail.setTargetObjectId(emails.id); //0030m00000aeYpdAAE
                
               //mail.setTargetObjectId(ReviewId); //0030m00000aeYpdAAE
                Messaging.SendEmailResult[] results=Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
                
            }
        }

please help
Dear All,

I have an requirement for my custom lightning community page , where i am showing a bell icon through lightning icon, now when someone posts on chatter for particular Campaign then that should be notify to user on bell icon.
How it can be achieved thorugh apex or something else??


Regards
Pranav Shah
Dear All,

I have requirement in my community page that the feed and feed  publisher which we drag and drop on community page ,needs to have show/hide functionality for those section 
how we can implement it using aura component??
Dear Team,  Could anyone please help with pagination, i am just getting 1st 10 records in pagination when i debug it. but i am able to move 70 records by moving to next page...till every page... For ex: i have 76 records , so it moves 7 page with 70 records but when i click to  next button to move to last 6 records ir displays previous 10 records on page...


Below is my code
Component Class
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordID,lightning:isUrlAddressable" 
                controller="LTI_CodeCoverageHelper">
    <ltng:require styles="{!$Resource.CMTStylesheet + '/stylesheet.css'}" />


    <aura:attribute name="data" type="List"/>
    <aura:attribute name="originaldata" type="List"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="searchText" type="String" description="use for store user search input"/> 
    <aura:attribute name="TotalClasses" type="Integer" description="use for displaying the class count"/>
    <!--aura:attribute name="dataList" type="List"/-->
    
    
    <!-- Start of Pagination attributes-->
    <aura:attribute name="conStart" type="Integer" />    
    <aura:attribute name="conEnd" type="Integer"/>    
    <aura:attribute name="conPageNumber" type="Integer"/>
    <aura:attribute name="pageSize" type="Integer" default="10"/>    
    <aura:attribute name="totalSize" type="Integer"/>
    <aura:attribute name="paginationList" type="List"/>
    <!-- End of Pagination attributes -->

    
    
    <!-- handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit }"/>
    <!--aura:handler event='force:refreshView' action='{!c.doInit}' /-->
        <aura:attribute name="showSpinner" type="Boolean" default="false" />
      
  

    
  

    
   <div class="CMTslds-grid CMTslds-wrap CMT_Gridlayout" style="    margin: 15px;  border-radius: 5px;
    background: white;
   ">
         <div class="CMTslds-grid CMTTitle" style="width:100%;">
            <div class="CMTslds-col CMT_TabHeading CMTTitle">
       <span>Code Coverage Check</span> 
        </div>
           <div class="CMTslds-col" >
      <lightning:button variant="brand" label="Back to Home" title="Back to Home" onclick="{! c.Backtohome }" class="BTOHbutton" />
      <lightning:button name="downloadCsv" label="Download CSV" onclick="{!c.downloadCSV}"  title="Download CSV" variant="brand" class="BTOHbutton"/>
         </div>
         </div>
       
         

   

<div class="slds-col slds-size_3-of-12 CMT_Innersec">
<span>
   <aura:if isTrue="{!v.showSpinner}"> 
    <lightning:input value="{!v.searchText}"
                             required="false"
                             placeholder="Enter the Class Name"
                             aura:id="searchText"
                             label="Looking for a Specific Class? "
                             onchange="{!c.keyCheck}"
                             class="CMT_Inputlab"/>
          <aura:set attribute="else">
                <lightning:spinner alternativeText="Loading" />
            </aura:set>
    </aura:if>
      
    </span>
</div>
<div class="slds-col slds-size_5-of-12 CMT_Innersec">
<span><div class="LegendSec">
            <div >⛔ No Coverage</div>
            <div>⚠️ Need Coverage Analysis</div>
            <div>✅ Good Coverage</div>
            </div></span>
</div>
<div class="slds-col slds-size_12-of-12 CMT_Innertable">
<span><lightning:datatable
                             keyField="id"
                             columns="{!v.columns}"
                             data="{!v.paginationList}"
                             hideCheckboxColumn="true"      
                                 class="CMTTable_style"
                             /></span>
</div>
      
</div>
    
    
  <!--Start of Pagination Buttons>-->
        <div class="slds-clearfix">
            <div class="slds-page-header custom-page-header" role="banner">
                <div class="slds-float_right">            
                    <lightning:button label="First" disabled="{!v.conStart == 0}"  onclick="{!c.first}" class="firstButton"/>            
                    <lightning:button label="Previous" disabled="{!v.conStart == 0}"  onclick="{!c.previous}" class="previousButton"/>      
                    <lightning:button label="Next" disabled="{!v.conEnd >= v.totalSize}" onclick="{!c.next}" class="nextButton"/>            
                    <lightning:button label="Last" disabled="{!v.conEnd >= v.totalSize}" onclick="{!c.last}" class="lastButton"/>
                    <p class="slds-page-header__title">{!v.conStart+1}-{!v.conEnd+1} of {!v.totalSize} | Page {!v.conPageNumber}</p>
                </div>
            </div>
</div>
<aura:component>

Controller:
({
    doInit : function(component,event) {
        component.set("v.showSpinner", false);
        debugger;
        component.set('v.columns', [
            {label: 'Class Name', fieldName: 'classOrTriggerName', type: 'text'},
            {label: 'Coverage', fieldName: 'coveragePercentage', type: 'text'},
            {label: 'Status', fieldName: 'Status', type: 'text'},
        ]);
            
            var action = component.get("c.getCodeCoverage"); 
            action.setCallback(this, function(response) {
            
            debugger;
            
            var state = response.getState();
            // alert(state);
            console.log(response.getReturnValue());
            var storeresponse = JSON.parse(response.getReturnValue());            

            if(state==="SUCCESS"){
            var pageSize = component.get("v.pageSize");
            component.set("v.data",storeresponse.CoverageList);
            component.set("v.originaldata",storeresponse.CoverageList);
                        component.set("v.showSpinner", true);

            
            //Code for intializing pagination list
            
            //var pageSize = component.get("v.pageSize");
            component.set("v.totalSize", component.get("v.data").length);                                       
            component.set("v.conStart",0);                                 
            component.set("v.conEnd",pageSize-1);
            component.set("v.conPageNumber",1);
            var paginationList = [];     
                      
            for(var i=0; i< pageSize; i++)                                           
            {                        
            if (component.get("v.data").length>i )    
            paginationList.push(storeresponse.CoverageList[i]);                                           
            }                                       
            component.set("v.paginationList", paginationList);                                       
            console.log('@@Pagination list'+JSON.stringify(paginationList));
            component.set("v.showSpinner", true);

           
                        
            }
            else
            {
            var errors = response.getError();
            }
            
            });
            
            $A.enqueueAction(action);
            },
 
    keyCheck : function(component,event,helper){
           
            debugger;
            var searchText =component.get("v.searchText").toLowerCase();           
            var orgdata = component.get('v.originaldata'); 
            var dataOnly = orgdata.filter(function (entry) {
            return entry.classOrTriggerName.toLowerCase().startsWith(searchText);
            });
            component.set("v.data",dataOnly);
          
                        
    },
            
            
//Start of Pagination methods
    first : function(component, event, helper)    
    {    
        var consumptionDetails = component.get("v.data");
        var pageSize = component.get("v.pageSize");
        var paginationList = [];
        var dataList;
        var start;
        var end;
        

        dataList = component.get("v.data"); 

        for(var i=0; i< pageSize; i++)
        {   
            paginationList.push(dataList[i]);            
        } 

        component.set("v.conStart",0);
        component.set("v.conEnd",pageSize-1);
        component.set("v.conPageNumber",1);            
    
        component.set("v.paginationList", paginationList);         
        console.log('@ First Button list'+component.get("v.paginationList"));        
    },
    
    next : function(component, event, helper)    
    {    

        var dataList;
        var start;
        var end;
        
        dataList = component.get("v.data");
        start = component.get("v.conStart");
        end = component.get("v.conEnd"); 
        
        component.set("v.totalSize", dataList.length);
        
        var pageSize = component.get("v.pageSize");
        var totalRecords = component.get("v.totalSize");
        
        var paginationList = [];        
        var counter = 0;
        
        for(var i=end+1; i<end+pageSize+1; i++)            
        {            
            if(dataList.length > end)                
            {                
                paginationList.push(dataList[i]);                
                counter ++ ;                
            }
            
        }
        
        start = start + counter;
           end = end + counter;
        
        component.set("v.conStart",start);
        component.set("v.conEnd",end);
        component.set("v.conPageNumber",component.get("v.conPageNumber")+1);              
        
        component.set("v.paginationList", paginationList);        
          
    },
    
    previous : function(component, event, helper)    
    {   
              
        var dataList;
        var start;
        var end;

        dataList = component.get("v.data");
        start = component.get("v.conStart");
        end = component.get("v.conEnd"); 
                    
        var pageSize = component.get("v.pageSize");        
        var paginationList = [];
        
        var counter = 0;
        
        for(var i= start-pageSize; i < start ; i++)            
        {            
            if(i > -1)                
            {                
                paginationList.push(dataList[i]);               
                counter ++;                
            }            
            else {                
                start++;                
            }            
        }        
        start = start - counter;       
        end = end - counter;
        
        component.set("v.conStart",start);
        component.set("v.conEnd",end);
        component.set("v.conPageNumber",component.get("v.conPageNumber")-1);            
 
        component.set("v.paginationList", paginationList);        
    },
    
    last : function(component, event, helper)
    {
        var conList = component.get("v.data");
        var pageSize = component.get("v.pageSize");
        var totalSize = component.get("v.totalSize");
        
        var totalpages = parseInt(totalSize/pageSize);
        var lastpagecounter = (totalpages*pageSize);
        console.log('@@ Total Pages-->'+totalpages);
        console.log('@@ Total Size-->'+totalSize);       
        console.log('@@ Last Page Starts from-->'+lastpagecounter);

        var paginationList = [];
        for(var i=lastpagecounter; i< totalSize; i++)
        {
            paginationList.push(conList[i]);
        }
        component.set("v.conStart",lastpagecounter);
        component.set("v.conEnd",totalSize-1);
        component.set("v.conPageNumber",totalpages+1);
        component.set('v.paginationList', paginationList);
    },
    //End of Pagination methods
            
            
            
            
            
   Backtohome : function(component, event, helper) {
        var evt = $A.get("e.force:navigateToComponent");
        evt.setParams({
            componentDef : "LTI:LTI_Metadatahomepage",        
        });
     evt.fire();
    },
      downloadCSV : function(component, event, helper){
       // var tableData = component.get("v.originaldata");
      // var tableData = component.get("v.ApexCodeCoverage");
          var tableData = component.get("v.data");
            console.log("tableData>"+JSON.stringify(tableData));
          var csv = helper.convertArrayOfObjectsToCSV(component,tableData); 
               console.log("csv>"+JSON.stringify(csv));
        
        if (csv == null){return;}
            // ####--code for create a temp. <a> html tag [link tag] for download the CSV file--####    
         var hiddenElement = document.createElement('a');
          hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
          hiddenElement.target = '_self'; //
          hiddenElement.download = 'ExportData.csv';  // CSV file Name* you can change it.[only name not .csv]
          document.body.appendChild(hiddenElement); // Required for FireFox browser
          hiddenElement.click(); // using click() js function to download csv file
        }         
   
       
        })
 
Dear All, 

i am trying to implement pagination in one FlowDefinition,i am getting below error in controller class
Invalid type: Schema.FlowDefinition
in below line
 obj.total = [SELECT Count() FROM FlowDefinition];




public class LTI_displayProcessBuilders {
    
   /* @AuraEnabled
    public static String getPBData(){
        String pbData;
        pbData = toolingAPISOQL('Select Id,DeveloperName,LatestVersion.Description,ActiveVersion.VersionNumber,ActiveVersion.Status,LatestVersion.VersionNumber From FlowDefinition');
        system.debug(pbData);
        return pbData;
       
    }*/
    
      @AuraEnabled
     public static DisplayProcessBuildersWrapper getPBData(Decimal pageNumber ,Integer recordToDisply) {
      Integer pageSize = recordToDisply;
      Integer offset = ((Integer)pageNumber - 1) * pageSize;
    
    // create a instance of wrapper class.
    DisplayProcessBuildersWrapper obj =  new DisplayProcessBuildersWrapper();
    // set the pageSize,Page(Number), total records and PB List(using OFFSET)   
        obj.pageSize = pageSize;
        obj.page = (Integer) pageNumber;
        obj.total = [SELECT Count() FROM FlowDefinition];
        obj.pbData= toolingAPISOQL('Select Id,DeveloperName,LatestVersion.Description,ActiveVersion.VersionNumber,ActiveVersion.Status,LatestVersion.VersionNumber From FlowDefinition LIMIT :recordToDisply OFFSET :offset');
        system.debug(obj.pbData);
    // return the wrapper class instance .
        return obj;
     }
    
 // create a wrapper class with @AuraEnabled Properties    
 public class DisplayProcessBuildersWrapper {
    @AuraEnabled public Integer pageSize {get;set;}
    @AuraEnabled public Integer page {get;set;}
    @AuraEnabled public Integer total {get;set;}
    //@AuraEnabled public List<FlowDefinition> FData{get;set;}
     @AuraEnabled public string pbData{get;set;}
    
 }
    
    
    
    
    @AuraEnabled
    public static String toolingAPISOQL( String query) {
        return restGet( 
            'callout:tooltipaccess_callback/services/data/v44.0/tooling/query?q='+ (query.replace(' ', '+'))
            ,
            'GET', UserInfo.getSessionId() );
    } 
    @AuraEnabled
    public static String restGet(String endPoint, String method, String sid) {
        Http h = new Http();
        HttpRequest hr = new HttpRequest();
        hr.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        hr.setHeader('Content-Type', 'application/json');
        hr.setTimeout(60000);
        hr.setEndpoint(endPoint);
        hr.setMethod(method);
        HttpResponse r = h.send(hr);
        return r.getBody();
    }

}

please help....


Regards
Pranav Shah


 
Dear All,

I am trying to write a workflow for sending an mail on Birthday, so when i am trying to evalute "Formula Evalutes to true" and then writing DATE(YEAR(TODAY()),month(DOB__c),day(DOB__c))<= TODAY(), i want mail to be trigger on date of birth with not with the curent year , but i am not able to get the desired result.
please help

Regards
Pranav
Hi All,

I have a one requirement , i have status__c f field in task   obj, once the status status  is changed to closed, i need to update two fields closedby & closedon , which i am not showing on UI .. how can i have achieve this using lightning component,

Regards
Pranav
Hi all,

I need to send mail to multiple email id ..different person whose email id will be external// ie not present in salesforce org...
I dont want to hardcord the id//.. just wanto fetch it thorugh custom metadata

How it will be done


List<CEMReportConfig__mdt> cemReportConfigLst = [SELECT Id,MasterLabel,ToEmailAddresses__c,CcEmailAddresses__c,EmailUniqueTemplateName__c FROM CEMReportConfig__mdt];
                                                                 
    
    //Messaging.MassEmailMessage email = new Messaging.MassEmailMessage();
    
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        
    efa.setFileName('Order.xml');
    efa.setBody(csvBlob);
    String[] toAddresses = new String[] {'pranav17shah@gmail.com'};
        
    email.setSubject('Order Data');
    email.setToAddresses(toAddresses);
    email.setPlainTextBody('Batch Processed');
    
    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
    
    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});  


Regards
Pranav Shah
Hi All,

Have any worked on creation of XML file through apex class using blob function & sending the file through batch class.


1.I have written a class which gives me O/P in XML format.
2.Now i want to create and generate an file with .XML file format.
3.Sending the file through batch class to an Email Address.


I have wriiten class
global class cls_OppFilessent
    {

     public string xmlstring { get; set;}
     public static string OppFilesend()
     {
       //Opportunity rew=new Opportunity();
        List<opportunity> lstopt =[SELECT id,Name,Booking_Date__c,Type,Trade_In__c,VW_Delivery_Date__c FROM Opportunity Limit 2];

    if (lstopt != null)
    {
    system.debug('Hariom Ganesha : listOpty='+lstopt.size());
    }
        
      Dom.Document doc = new Dom.Document();
      XmlStreamWriter w = new XmlStreamWriter();
      w.writeStartDocument(null, '1.0');
      w.writeStartElement(null, 'Opportunities', null); //this will be ROOT of <Opportunities> in XML


              for(Opportunity rew:lstopt)
              {
              w.writeStartElement(null, 'Opportunity', null);//Element <Opportunity>
          
              w.writeStartElement(null, 'Id', null);//Element </Id>
              w.writeCharacters(rew.Id);
              w.writeEndElement();//Element </Id>
      
              //Element <BookingDate>
              w.writeStartElement(null, 'BookingDate', null);
              //w.writeEndElement();
              if(rew.Booking_Date__c!=null)
              {
                  //w.writeStartElement(null, 'BookingDate', null);
                  w.writeCharacters(String.valueOf(rew.Booking_Date__c)); 
                     
              }
              w.writeEndElement();
              
              
              w.writeStartElement(null, 'Name', null);
              if(rew.Name!=null)
              {
                  w.writeCharacters(rew.Name);
                  
              }
                  w.writeEndElement();
                  
              
              
              //Element <TradeIN>
              w.writeStartElement(null, 'TradeIN', null);
              if(rew.Trade_In__c!=null)
              {
                  w.writeCharacters(String.valueOf(rew.Trade_In__c));
                  
              }
                  w.writeEndElement();
                  
                  
             w.writeStartElement(null, 'Type', null);
              if(rew.Type!=null)
              {
                  w.writeCharacters(rew.Type);
              }
                  w.writeEndElement();
              
              //Element <DeliveryDate>
              w.writeStartElement(null, 'DeliveryDate', null);
              if(rew.VW_Delivery_Date__c!=null)
              {
                  w.writeCharacters(String.valueOf(rew.VW_Delivery_Date__c)); 
              }
                  w.writeEndElement();
              }
               w.writeEndElement();
              w.writeEndDocument();//this will be ROOT CLOSE of </Opportunities> in XML
         string xmlOutput = w.getXmlString();
         system.debug('XML is xmlOutput  '+xmlOutput );
         w.close();
         doc.Load(xmlOutput);
         string xmldata = doc.toXmlString();
         system.debug('XML is '+xmldata);
   
   
    /*
     Blob  csvBlob;
     try{
                csvBlob  = Blob.valueOf(xmldata);  
            }catch(exception e){

                csvBlob  = Blob.valueOf('Some Text');
           }
     
        if(rew.Active__c==true){
            return 'Reward feed already sent';
        }else{
             Attachment attachment = new Attachment();
                attachment.Body = csvBlob ;
                attachment.Name = 'Rewardfile.xml';
                attachment.ParentId = rew.id;
             insert attachment;
          
           rew.Active__c=true;
           Update rew; 
          return 'XML: '+xmldata;
         }*/
         
         
         //String myString = 'StringToBlob';
         //Blob myBlob = Blob.valueof(myString);
         
         return 'XML: '+xmldata; // Pranav - temporary return - remove this once BLOB code is tested
    
   }
}

Now i want to create and generate an .XMLfile  so that it can be send through email

please suggest


Regards
Pranav Shah


 
Hi Team,

I want to create a simple XMl file with few fields...
Below is my code for the same

global class cls_OppFilessent{
     public static string OppFilesend(ID Optid)
     {
       Opportunity rew=new Opportunity();
        rew =[SELECT id,Name,Booking_Date__c,Type,Trade_In__c,VW_Delivery_Date__c FROM Opportunity where id='0067F00000E9VxaQAF'];
      Dom.Document doc = new Dom.Document();
      XmlStreamWriter w = new XmlStreamWriter();
      w.writeStartDocument(null, '1.0');
      w.writeStartElement(null, 'Opportunities', null); //this will be ROOT of <Opportunities> in XML

              
              w.writeStartElement(null, 'Opportunity', null);//Element <Opportunity>
          
              w.writeStartElement(null, 'Id', null);//Element </Id>
              w.writeCharacters(rew.Id);
              w.writeEndElement();//Element </Id>
      
              //Element <BookingDate>
              w.writeStartElement(null, 'BookingDate', null);
              //w.writeEndElement();
              if(rew.Booking_Date__c!=null)
              {
                  //w.writeStartElement(null, 'BookingDate', null);
                  w.writeCharacters(String.valueOf(rew.Booking_Date__c)); 
                     
              }
              w.writeEndElement();
              
              
              w.writeStartElement(null, 'Name', null);
              if(rew.Name!=null)
              {
                  w.writeCharacters(rew.Name);
                  
              }
                  w.writeEndElement();
                  
              
              
              //Element <TradeIN>
              w.writeStartElement(null, 'TradeIN', null);
              if(rew.Trade_In__c!=null)
              {
                  w.writeCharacters(String.valueOf(rew.Trade_In__c));
                  
              }
                  w.writeEndElement();
                  
                  
             w.writeStartElement(null, 'Type', null);
              if(rew.Type!=null)
              {
                  w.writeCharacters(rew.Type);
              }
                  w.writeEndElement();
              
              //Element <DeliveryDate>
              w.writeStartElement(null, 'DeliveryDate', null);
              if(rew.VW_Delivery_Date__c!=null)
              {
                  w.writeCharacters(String.valueOf(rew.VW_Delivery_Date__c)); 
              }
                  w.writeEndElement();
      
      
                w.writeEndDocument();//this will be ROOT CLOSE of </Opportunities> in XML
         string xmlOutput = w.getXmlString();
         system.debug('XML is xmlOutput  '+xmlOutput );
         w.close();
         doc.Load(xmlOutput);
         string xmldata = doc.toXmlString();
         system.debug('XML is '+xmldata);
   
   
    /*
     Blob  csvBlob;
     try{
                csvBlob  = Blob.valueOf(xmldata);  
            }catch(exception e){

                csvBlob  = Blob.valueOf('Some Text');
           }
     
        if(rew.Active__c==true){
            return 'Reward feed already sent';
        }else{
             Attachment attachment = new Attachment();
                attachment.Body = csvBlob ;
                attachment.Name = 'Rewardfile.xml';
                attachment.ParentId = rew.id;
             insert attachment;
          
           rew.Active__c=true;
           Update rew; 
          return 'XML: '+xmldata;
         }*/
         
         return 'XML: '+xmldata; // Pranav - temporary return - remove this once BLOB code is tested
    
   }
}


Test Class:

@isTest
public class test_OppFilessent{
    public static testMethod void m1(){
      
         /*Time_Based_Mgmnt__c t = new Time_Based_Mgmnt__c ();
         t.Name='Q1';
            t.Start_Date__c=Date.Valueof('2014-01-01');
            t.End_Date__c=Date.Valueof('2014-03-01');
        insert t;
      
      
        Reward__c rwrd= new Reward__c();
         //   rwrd.Name='test';
            rwrd.Rward_Amount__c=5000;
            rwrd.Active__c =true;
            rwrd.User__c = userinfo.getUserId();
            rwrd.Time_Based_Mgmnt__c = t.id;
          insert rwrd; 
       */
        //cls_RewardFeedSent.rewardfeedsend('0067F00000E9VxaQAF');
       
       
        //rwrd.Active__c =false;
        //update rwrd;
        ID sfdcOptyID = '0067F00000E9VxaQAF';
        cls_OppFilessent.OppFilesend(sfdcOptyID);
       
    }
}

But i am getting error as

System.QueryException: List has no rows for assignment to SObject


Class.cls_OppFilessent.OppFilesend: line 5, column 1
Class.test_OppFilessent.m1: line 26, column 1


please help
How we can write test class for folowing lines


f(ISstarrating != '' && ISstarrating == 'StarOptions')
                    {
                        component.Apex.selectRadio theselectlist = new Component.Apex.selectradio();
                        //component.Apex.selectlist theselectlist = new Component.Apex.selectlist();
                        theselectlist.expressions.value = '{!lstLeadGenFollowup['+counter+'].VW_Answer1__c}';
                        theselectlist.id = 'Answer_'+counter;
                        theselectlist.styleClass = 'Answer_'+counter;
                        //theselectlist.size = 1;
                        
                       // AddSelectOption(theselectlist, '', '--None--');
                        for(string s : lstStrSelectOpps)
                        {
                            AddSelectRadioOption(theselectlist, s, s);
                        }
                        fieldDiv.styleClass = 'fieldSubDiv star-rating';
                        fieldDiv.childComponents.add(theselectlist);
                    }


Regards
Pranav Shah
Hi All,

I hav 2 Objects... Object A & Object B... their is lookup relationship between 2 objects... suppose their are 10 records on object B..now i want to fetch records from Object B  on Object A by querying the fields...so thier will be list of records insertion everytime from external system.if the  record exist then insertion will happen successful otherwise it will get failed.... so how it will be done .. please suggest

Regards
Pranav Shah
Hi All,

Below is my code to insert opportunty on basis of custom object(Cable unit) in salesforce. record is getting inserted.. but in response i am getting some issue... response is added at the end... i am fetching response throgh workbench

Also i dont want opportunity to be created,if their is no cable unit created

@RestResource(urlMapping='/OpportunityCreation/*')
global class OpportunityCreate
{
@HttpPost   
    global static  List<responseWrapper> createNewOpportunity(list<OpportunityWrapper> oppwrapList) 
    {
        //RestRequest req = RestContext.request;
        //RestResponse res = RestContext.response;
        string returnString='';
        string cuNo;
        List<responseWrapper> response = new List<responseWrapper>();


        //set<Id> setNewOpp=new set<Id>();
        try
        {
            list<Opportunity> opplist = new list<Opportunity>();
            Map<String,Id> cableUnitNoToIdMap=new Map<String,Id>();
            Map<String,id> cableUnitNoToAccountIdMap=new Map<String,id>();
            Set<String> cableUnitSet=new Set<String>();
            list<Database.SaveResult> srList;
            list<String> kissCUNos = new list<String>();
            list<String> successkissCUNos = new list<String>();


              for(OpportunityWrapper wrapObj:oppWrapList)
              {
                  cableUnitSet.add(wrapObj.cableUnitNo); // heck variable name in wrapper class 
              }
              system.debug('--------------------cableUnitSet-----------------'+cableUnitSet);
              list<Cable_Unit__c> cableUnitRecords = [select Id,Customer__r.Id,Customer__c,Cable_Unit_No__c from Cable_Unit__c where Cable_Unit_No__c IN :cableUnitSet];
              system.debug('-----------cableUnitRecords Size-------------'+cableUnitRecords.size());
             for(Cable_Unit__c c:cableUnitRecords)
              {
                  system.debug('------------CU record-----------------'+c);
                  cableUnitNoToIdMap.put(c.Cable_Unit_No__c,c.Id);
                  //cableUnitNoToAccountIdMap.put(c.Cable_Unit_No__c, c.Customer__c);
              }
              List<Account> AccountRecords=[select Id,Name,Cable_Unit_No__c from Account where Cable_Unit_No__c IN:cableUnitSet];
              for(Account acct:AccountRecords)
              {
                   system.debug('------------Customer record-----------------'+acct);
                   //cableUnitNoToIdMap.put(acct.Cable_Unit_No__c,acct.Id);
                   cableUnitNoToAccountIdMap.put(acct.Cable_Unit_No__c, acct.id);
              }
              system.debug('--------------------cableUnitNoToIdMap size-----------------------------'+cableUnitNoToIdMap.size());
              system.debug('--------------------cableUnitNoToIdMap-----------------------------'+cableUnitNoToIdMap);
              system.debug('--------------------cableUnitNoToAccountIdMap size-----------------------------'+cableUnitNoToAccountIdMap.size());
              system.debug('--------------------cableUnitNoToAccountIdMap -----------------------------'+cableUnitNoToAccountIdMap);
                for(OpportunityWrapper wrap : oppwrapList) 
                {           
                    
                    Opportunity opp = new Opportunity();
                    opp.Name= wrap.Name;
                    opp.StageName =wrap.StageName;
                    opp.CloseDate = date.valueof(Label.CloseDate);
                    //customLabelValue = System.Label.CloseDate;
                    //opp.CloseDate =date.valueof(wrap.closedate);
                  
                    if(cableUnitNoToIdMap.containskey(wrap.cableUnitNo))
                    { 
                        opp.cable_unit__c=cableUnitNoToIdMap.get(wrap.cableUnitNo);
                    }
                    if(cableUnitNoToAccountIdMap.containskey(wrap.cableUnitNo)) 
                    {
                        opp.AccountId =cableUnitNoToAccountIdMap.get(wrap.cableUnitNo);
                        system.debug('---------------cableUnitNoToAccountIdMap.get(wrap.cableUnitNo);--------------------'+cableUnitNoToAccountIdMap.get(wrap.cableUnitNo));
                        system.debug('---------------opp.AccountId--------------------'+opp.AccountId);
                    }
                    opplist.add(opp);
                    system.debug('*****' +  oppwrapList);
                }
                 {
                   srList = Database.insert(opplist,false);
                 }
               //create response for all the CUs'for which Opportunity and CU record has been successfully inserted in SF Database.

               for(Opportunity insertedopportunity : opplist)
               {
               
                successkissCUNos.add(cableUnitNoToIdMap.get(insertedopportunity.cable_unit__c));
                responseWrapper responseRec = new responseWrapper();
                responseRec.cableUnitNo = cableUnitNoToIdMap.get(insertedopportunity.cable_unit__c);
                responseRec.cableUnitSFID =insertedopportunity.cable_unit__c;
                responseRec.OpportunitySFID = insertedOpportunity.id;
                responseRec.IsSuccess = 'true';
                response.add(responseRec);
               }
           
            //these condition checks the Opp records for which opp and CU records are not created in SF.
            
                if(!successkissCUNos.contains(CuNo))
                {
                    responseWrapper responseError = new responseWrapper();
                    responseError.IsError = 'true'; 
                    responseError.CableUnitNo = CuNo;
                    responseError.ErrorMessage = 'Cable Unit and Opportunity Record Record Creation failed In Salesforce';
                    response.add(responseError);
                }
            
            system.debug('------response---------'+response);                
        }
        catch(exception ex)
        {
            returnString = 'Request got failed: Error details-'+ex.getmessage();
        }
         return response;
    }
    
    
   global class OpportunityWrapper
       {
        global string StageName;
        global string CloseDate;
        global string CableUnitNo;
        global string name;
       }
   global class responseWrapper
       {
        global String cableUnitNo;
        global String OpportunitySFID;
        global String cableUnitSFID;
        //global String AccountSFID;
        global String IsSuccess;
        global String IsError;
        global String ErrorMessage;
       }    
}

But while inserting through workbench i am not getting cable number in response...


[
{
"OpportunitySFID" : "006M000000FaLTQIA3",
"IsSuccess" : "true", "IsError" : null,
"ErrorMessage" : null,
"cableUnitSFID" : "a1TM0000001yrZwMAI",
"cableUnitNo" : null
},
 {
"OpportunitySFID" : "006M000000FaLTRIA3",
"IsSuccess" : "true",
"IsError" : null,
"ErrorMessage" : null,
"cableUnitSFID" : "a1TM0000001yrZxMAI",
"cableUnitNo" : null
} ]


please suggest....
Hi All,

I need to pass a record id, when  a record gets inserted ...For EG if i have  a contact object, and their is  status field on contact object... so when a contact gets inserted via apex class. instead of passing string as succesful or failure.. i want to display salesforce id of record which gets created and also the value of status field...when i am doing testing through work bench,,,,
below is the sample code for the same

 if (accList <> null && acclist.size() > 0)
            {
             returnString='Successful';
            }
             else
            {
            returnString='Failed';
            }        
            }
        catch(exception ex)
        {
            returnString = 'Request got failed: Error details-'+ex.getmessage();
        }
         return returnString;
    }

please help..
Regards
Pranav
Hi All,

Can someone tell me is dis ryt way to create instance for child object an to insert the list of records of child object(Cable unit) on Account object...
if not can some one correct it

global class CustomerCunit
{
    global static String createNewAccount(list<accountWrapper> accwrapList) 
    {
        //RestRequest req = RestContext.request;
        //RestResponse res = RestContext.response;
        string returnString='';
        try
        {
        list<account> acclist = new list<account>();
        list<Cable_unit__c> Cunitlist= new list<Cable_unit__c>();
            system.debug('*****' + accwrapList);
            for(accountWrapper wrap : accwrapList) 
            {
            Account acc = new Account();
            Cable_Unit__c Cunit= new  Cable_Unit__c();
            acc.Name= wrap.AccName;
            acc.Potential_Installations__c =wrap.PotentialInstallations;
            acclist.add(acc);
            acc.Customer_Segment_Lookup__c=wrap.CustomerSegmentLookup;
            Cunit.Municipaly__c =wrap.Municipaly;
            Cunit.Housing_Type__c=wrap.HousingTypeLookup;
            Cunit.Housing_Ownership__c=wrap.HousingOwnershipLookup;
            Cunit.Cable_Unit_post_Code__c= wrap.CableUnitPostCode;
            Cunit.Building_Type__c=wrap.BuildingType;
            Cunit.Cable_Unit_No__c=wrap.CableUnitNo;
            CunitList.add(Cunit);
            }
            insert Cunitlist;
            insert acclist;
            if (accList <> null && acclist.size() > 0)
            {
             returnString='Successful';
            }
             else
            {
            returnString='Failed';
            }        
            }
        catch(exception ex)
        {
            returnString = 'Request got failed: Error details-'+ex.getmessage();
        }
         return returnString;
    }
    
    
   global class accountWrapper
       {
        global string AccName;
        global Integer PotentialInstallations;
        global string Municipaly;
        global string CustomerSegmentLookup;
        global string HousingTypeLookup;
        global string HousingOwnershipLookup;
        global string CableUnitPostCode;
        global string CableUnitNo;
        global string BuildingType;
       }
}


Thanks & Regards
Pranav Shah

Hi All,

I need to parse below code in JSON format to insert multiple records at a time... i have done for single record to be inserted...For inserting multiple records through web service , how it will be done



@RestResource(urlMapping='/showAccountDetails/*')
global with sharing class NewCustomerCreation
{
 @HttpPost

 global static string doPost(String name)
 {
  RestRequest req = RestContext.request;
  RestResponse res = RestContext.response;
  res.addHeader('Content-Type', 'application/json');
  String jsonResponse = '';
  String accountName = req.params.get('account_name');
  Integer PInstallations = Integer.ValueOf(req.params.get('Potential_Installations__c')); 
  String Muncipaly = req.params.get('Municipaly__c');
  String CustSegment = req.params.get('Customer_Segment_Lookup__c'); 
  String CustHousingType = req.params.get('Housing_Type_Lookup__c'); 
  String CustHousingOwnership = req.params.get('Housing_Ownership_Lookup__c');  

  //Inserting records into Account
  
  Account acc= new Account();
  acc.name=accountName;
  acc.Potential_Installations__c= PInstallations;
  acc.Municipaly__c='Muncipaly';
  acc.Customer_Segment_Lookup__c ='CustSegment';
  acc.Housing_Type_Lookup__c ='CustHousingType';
  acc.Housing_Ownership_Lookup__c = 'CustHousingOwnership';
  insert acc;
  return acc.id;
      
}


below is the required format


{
"Account" :[{
 "cableunit_name":"",
              "cableunit_number":"",
              "potential_installation":"",
              "municipality":"",
              "postcode":"",
              "customer_segment":"",
              "Housing_type":"",
              "building_type":"",
              "housing_ownership":""
}
      
    },{
     "cableunit_name":"",
              "cableunit_number":"",
              "potential_installation":"",
              "municipality":"",
              "postcode":"",
              "customer_segment":"",
              "Housing_type":"",
              "building_type":"",
              "housing_ownership":""
}
    },{
    "attributes" :  "cableunit_name":"",
              "cableunit_number":"",
              "potential_installation":"",
              "municipality":"",
              "postcode":"",
              "customer_segment":"",
              "Housing_type":"",
              "building_type":"",
              "housing_ownership":""
}
    },{
    "cableunit_name":"",
              "cableunit_number":"",
              "potential_installation":"",
              "municipality":"",
              "postcode":"",
              "customer_segment":"",
              "Housing_type":"",
              "building_type":"",
              "housing_ownership":""
}
    }]
}


please help

Thanks & Regards
Pranav Shah
How can i convert the below string in the  web service class in JSON..

please help..

@RestResource(urlMapping='/Account/*')
 global with sharing class NewCustCreation
 {
    //public String Status {get;set;}
    //public List<Account> Data {get;set;}
    //public String Message {get;set;}
    //public String ErrorCode {get; set;}
    
     public class Account
     {

        public String Name;
     }

    @HttpPost
    global static String dopost(String Name)
    {
        system.debug('-----------Name----------------------'+Name);
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response; 
         Account account =  new Account();
         account.name=name;
         String success = 'Welcome to Salesforce';
         String error = 'Error';
         if(Name!= '')
         {
              return Name;
         }
         else
         {
              return error;   
         }
         

    }
Hi All,

I am getting following error for my class:
Unexpected parameter encountered during deserialization: name at [line:2, column:9]
errorCode: JSON_PARSER_ERROR

below is my code for same.
i am trying to insert account name thrugh workbench
@RestResource(urlMapping='/Account/*')
 global with sharing class NewCustCreation
 {
    //public String Status {get;set;}
    //public List<Account> Data {get;set;}
    //public String Message {get;set;}
    //public String ErrorCode {get; set;}
    
     public class Account
     {

        public String Name;
     }

    @HttpPost
    global static String dopost(String Name)
    {
        system.debug('-----------Name----------------------'+Name);
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response; 
         Account account =  new Account();
         account.name=name;
         String success = 'Welcome to Salesforce';
         String error = 'Error';
         if(Name!= '')
         {
              return Name;
         }
         else
         {
              return error;   
         }
         

    }
    public static NewCustCreation parse(String json)
        {
        return (NewCustCreation) System.JSON.deserialize(json, NewCustCreation.class);
        }
    }



Request Body:
{
"name":"Eniig Customer"
}
Hi All,


i am getting following error while running the code on trailhead for Apex Rest Callouts
Line No 12  Variable does not exist: AnimalsCallouts

@isTest
private class AnimalsCalloutsTest {
    @isTest static void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result,
            'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(),
          'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(),
          'The array should only contain 3 items.');          
    }   
}

please help

Thanks
Pranav



 
Dear All,

I have requirement in my community page that the feed and feed  publisher which we drag and drop on community page ,needs to have show/hide functionality for those section 
how we can implement it using aura component??
Dear All, 

i am trying to implement pagination in one FlowDefinition,i am getting below error in controller class
Invalid type: Schema.FlowDefinition
in below line
 obj.total = [SELECT Count() FROM FlowDefinition];




public class LTI_displayProcessBuilders {
    
   /* @AuraEnabled
    public static String getPBData(){
        String pbData;
        pbData = toolingAPISOQL('Select Id,DeveloperName,LatestVersion.Description,ActiveVersion.VersionNumber,ActiveVersion.Status,LatestVersion.VersionNumber From FlowDefinition');
        system.debug(pbData);
        return pbData;
       
    }*/
    
      @AuraEnabled
     public static DisplayProcessBuildersWrapper getPBData(Decimal pageNumber ,Integer recordToDisply) {
      Integer pageSize = recordToDisply;
      Integer offset = ((Integer)pageNumber - 1) * pageSize;
    
    // create a instance of wrapper class.
    DisplayProcessBuildersWrapper obj =  new DisplayProcessBuildersWrapper();
    // set the pageSize,Page(Number), total records and PB List(using OFFSET)   
        obj.pageSize = pageSize;
        obj.page = (Integer) pageNumber;
        obj.total = [SELECT Count() FROM FlowDefinition];
        obj.pbData= toolingAPISOQL('Select Id,DeveloperName,LatestVersion.Description,ActiveVersion.VersionNumber,ActiveVersion.Status,LatestVersion.VersionNumber From FlowDefinition LIMIT :recordToDisply OFFSET :offset');
        system.debug(obj.pbData);
    // return the wrapper class instance .
        return obj;
     }
    
 // create a wrapper class with @AuraEnabled Properties    
 public class DisplayProcessBuildersWrapper {
    @AuraEnabled public Integer pageSize {get;set;}
    @AuraEnabled public Integer page {get;set;}
    @AuraEnabled public Integer total {get;set;}
    //@AuraEnabled public List<FlowDefinition> FData{get;set;}
     @AuraEnabled public string pbData{get;set;}
    
 }
    
    
    
    
    @AuraEnabled
    public static String toolingAPISOQL( String query) {
        return restGet( 
            'callout:tooltipaccess_callback/services/data/v44.0/tooling/query?q='+ (query.replace(' ', '+'))
            ,
            'GET', UserInfo.getSessionId() );
    } 
    @AuraEnabled
    public static String restGet(String endPoint, String method, String sid) {
        Http h = new Http();
        HttpRequest hr = new HttpRequest();
        hr.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
        hr.setHeader('Content-Type', 'application/json');
        hr.setTimeout(60000);
        hr.setEndpoint(endPoint);
        hr.setMethod(method);
        HttpResponse r = h.send(hr);
        return r.getBody();
    }

}

please help....


Regards
Pranav Shah


 
Hi Team,

I want to create a simple XMl file with few fields...
Below is my code for the same

global class cls_OppFilessent{
     public static string OppFilesend(ID Optid)
     {
       Opportunity rew=new Opportunity();
        rew =[SELECT id,Name,Booking_Date__c,Type,Trade_In__c,VW_Delivery_Date__c FROM Opportunity where id='0067F00000E9VxaQAF'];
      Dom.Document doc = new Dom.Document();
      XmlStreamWriter w = new XmlStreamWriter();
      w.writeStartDocument(null, '1.0');
      w.writeStartElement(null, 'Opportunities', null); //this will be ROOT of <Opportunities> in XML

              
              w.writeStartElement(null, 'Opportunity', null);//Element <Opportunity>
          
              w.writeStartElement(null, 'Id', null);//Element </Id>
              w.writeCharacters(rew.Id);
              w.writeEndElement();//Element </Id>
      
              //Element <BookingDate>
              w.writeStartElement(null, 'BookingDate', null);
              //w.writeEndElement();
              if(rew.Booking_Date__c!=null)
              {
                  //w.writeStartElement(null, 'BookingDate', null);
                  w.writeCharacters(String.valueOf(rew.Booking_Date__c)); 
                     
              }
              w.writeEndElement();
              
              
              w.writeStartElement(null, 'Name', null);
              if(rew.Name!=null)
              {
                  w.writeCharacters(rew.Name);
                  
              }
                  w.writeEndElement();
                  
              
              
              //Element <TradeIN>
              w.writeStartElement(null, 'TradeIN', null);
              if(rew.Trade_In__c!=null)
              {
                  w.writeCharacters(String.valueOf(rew.Trade_In__c));
                  
              }
                  w.writeEndElement();
                  
                  
             w.writeStartElement(null, 'Type', null);
              if(rew.Type!=null)
              {
                  w.writeCharacters(rew.Type);
              }
                  w.writeEndElement();
              
              //Element <DeliveryDate>
              w.writeStartElement(null, 'DeliveryDate', null);
              if(rew.VW_Delivery_Date__c!=null)
              {
                  w.writeCharacters(String.valueOf(rew.VW_Delivery_Date__c)); 
              }
                  w.writeEndElement();
      
      
                w.writeEndDocument();//this will be ROOT CLOSE of </Opportunities> in XML
         string xmlOutput = w.getXmlString();
         system.debug('XML is xmlOutput  '+xmlOutput );
         w.close();
         doc.Load(xmlOutput);
         string xmldata = doc.toXmlString();
         system.debug('XML is '+xmldata);
   
   
    /*
     Blob  csvBlob;
     try{
                csvBlob  = Blob.valueOf(xmldata);  
            }catch(exception e){

                csvBlob  = Blob.valueOf('Some Text');
           }
     
        if(rew.Active__c==true){
            return 'Reward feed already sent';
        }else{
             Attachment attachment = new Attachment();
                attachment.Body = csvBlob ;
                attachment.Name = 'Rewardfile.xml';
                attachment.ParentId = rew.id;
             insert attachment;
          
           rew.Active__c=true;
           Update rew; 
          return 'XML: '+xmldata;
         }*/
         
         return 'XML: '+xmldata; // Pranav - temporary return - remove this once BLOB code is tested
    
   }
}


Test Class:

@isTest
public class test_OppFilessent{
    public static testMethod void m1(){
      
         /*Time_Based_Mgmnt__c t = new Time_Based_Mgmnt__c ();
         t.Name='Q1';
            t.Start_Date__c=Date.Valueof('2014-01-01');
            t.End_Date__c=Date.Valueof('2014-03-01');
        insert t;
      
      
        Reward__c rwrd= new Reward__c();
         //   rwrd.Name='test';
            rwrd.Rward_Amount__c=5000;
            rwrd.Active__c =true;
            rwrd.User__c = userinfo.getUserId();
            rwrd.Time_Based_Mgmnt__c = t.id;
          insert rwrd; 
       */
        //cls_RewardFeedSent.rewardfeedsend('0067F00000E9VxaQAF');
       
       
        //rwrd.Active__c =false;
        //update rwrd;
        ID sfdcOptyID = '0067F00000E9VxaQAF';
        cls_OppFilessent.OppFilesend(sfdcOptyID);
       
    }
}

But i am getting error as

System.QueryException: List has no rows for assignment to SObject


Class.cls_OppFilessent.OppFilesend: line 5, column 1
Class.test_OppFilessent.m1: line 26, column 1


please help
Hi All,

Can someone tell me is dis ryt way to create instance for child object an to insert the list of records of child object(Cable unit) on Account object...
if not can some one correct it

global class CustomerCunit
{
    global static String createNewAccount(list<accountWrapper> accwrapList) 
    {
        //RestRequest req = RestContext.request;
        //RestResponse res = RestContext.response;
        string returnString='';
        try
        {
        list<account> acclist = new list<account>();
        list<Cable_unit__c> Cunitlist= new list<Cable_unit__c>();
            system.debug('*****' + accwrapList);
            for(accountWrapper wrap : accwrapList) 
            {
            Account acc = new Account();
            Cable_Unit__c Cunit= new  Cable_Unit__c();
            acc.Name= wrap.AccName;
            acc.Potential_Installations__c =wrap.PotentialInstallations;
            acclist.add(acc);
            acc.Customer_Segment_Lookup__c=wrap.CustomerSegmentLookup;
            Cunit.Municipaly__c =wrap.Municipaly;
            Cunit.Housing_Type__c=wrap.HousingTypeLookup;
            Cunit.Housing_Ownership__c=wrap.HousingOwnershipLookup;
            Cunit.Cable_Unit_post_Code__c= wrap.CableUnitPostCode;
            Cunit.Building_Type__c=wrap.BuildingType;
            Cunit.Cable_Unit_No__c=wrap.CableUnitNo;
            CunitList.add(Cunit);
            }
            insert Cunitlist;
            insert acclist;
            if (accList <> null && acclist.size() > 0)
            {
             returnString='Successful';
            }
             else
            {
            returnString='Failed';
            }        
            }
        catch(exception ex)
        {
            returnString = 'Request got failed: Error details-'+ex.getmessage();
        }
         return returnString;
    }
    
    
   global class accountWrapper
       {
        global string AccName;
        global Integer PotentialInstallations;
        global string Municipaly;
        global string CustomerSegmentLookup;
        global string HousingTypeLookup;
        global string HousingOwnershipLookup;
        global string CableUnitPostCode;
        global string CableUnitNo;
        global string BuildingType;
       }
}


Thanks & Regards
Pranav Shah
Hi All,


i am getting following error while running the code on trailhead for Apex Rest Callouts
Line No 12  Variable does not exist: AnimalsCallouts

@isTest
private class AnimalsCalloutsTest {
    @isTest static void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result,
            'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(),
          'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(),
          'The array should only contain 3 items.');          
    }   
}

please help

Thanks
Pranav



 
Hi All, 
 their is one requirement i have ..
i have 'Amount field' on opportunity needs to be entered whenever a opportunity is created related to a particular account  once a opportunity is created ,then i want 'Total Opportunity Amount' field on Account object needs to be updated.

I want to write trigger for the same

How it will be done

I have written this much amount of code, but i am not able to go ahead..as i am on learning stage ..please help me out.

public class opportunityhandler
{
 public void opportunityamount(list<opportunity> newopportunity)
 {
  set<String> setOppName=new set<String>();
  for(opportunity opp:newopportunity)
  {
    setOppname.add(opp.Amount);
  }
    list<opportunity> opps= [select Name, Amount from opportunity where AccountId =:setOppname];
    {
    
    }
  }
 }
 
In one interview i had a question like How many relationship can be defiend on junction object??
 
My ans was one : i.e Many To Many Relationship

is it correct//
Hi,

can please someone explain me parent child & master detail relationship in salesforce

Regards
Pranav Shah
9029966976
Can anyone explain me below line of codes


public class myWeb2LeadExtension
{
private final Lead weblead;
public myWeb2LeadExtension(ApexPages.StandardController stdController) 
{
weblead = (Lead)stdController.getRecord();

public PageReference saveLead() {
try 
{
insert(weblead);
 }
catch(System.DMLException e) {
 ApexPages.addMessages(e);
return null;
}
PageReference p = Page.ThankYou;
p.setRedirect(true);
       return p;
     }
 
Apex: 
<apex:page controller="allObjectListClass">
    <apex:pageBlock>
        <apex:form id = "myForm">
            
            <apex:pageBlockSection>
                <apex:selectList id="objList" value="{!selectedObj}" size="1">
                    <apex:selectOptions value="{!objName}"/>
                    <apex:actionSupport event="onchange" reRender="myForm"/>
                </apex:selectList>  
            </apex:pageBlockSection>
            
            <apex:pageBlockSection>
                <apex:pageblockTable value="{!fieldName}" var="f">
                    <apex:column value="{!f}"/>
                </apex:pageblockTable>
            </apex:pageBlockSection>
            
        </apex:form>        
    </apex:pageBlock>    
</apex:page>
Controller :
public class allObjectListClass {
    public String selectedObj {get;set;}
    
    public static List<selectOption> getObjName(){
        List<selectOption> options = new List<selectOption>();
        
        for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
        {
            Schema.DescribeSObjectResult objResult = o.getDescribe();           
            system.debug( 'Sobject API Name: ' + objResult.getName() +' Sobject Label Name: ' + objResult.getLabel());           
            options.add(new SelectOption(objResult.getName(),objResult.getLabel()));
        }
        return options;
    }
    
    public static List<String> getFieldName(){
        List<String> reqFields = new List<String>();
        /*
			Required Code 
		*/
        return reqFields;
    }
}
I am getting a hard time dealing with schema methods, i have gone through the Salesforce documentation though.
Thanks in advance...


 
Hi All,

Can anyone, please help on the same..
not a code required, can u please share the logic.. so that i can work on same as i am new and learning triggers.

Thanks & Regards
Pranav Shah
Hi All,
While writing  triggers, i am getting below error

Error: Compile Error: Variable does not exist: First_Name at line 5 column 3    
Code:

trigger HelloWorld on Lead (before Update)
 {
for(lead l: Trigger.New)
{
l.FirstName ='Hello';
l.LastName  ='World';
}
}
one more thing , if i have a stock object in one custom object and if stock is 0 then available checkbox should become false otherwise it should be true... How it can be done , whether by validation rules or workflow rules???
I have added 3 custom fields to the Opportunity Product section, all of which are set to currency and have a 14 character limit with 4 decimal places. I am trying to build a 4th formula with the following to equal "total price" (also a currency with the above):

Dollar_GB_Cost__c  *  Standard_Price__c  =  List_Price__c

What am I doing wrong here? I am new to salesforce and trying to mess around with opportunity pricing based on a cost (usually in the $.50 range) x standard cost = list price/sales price.
 
have just completed the Challenge for the module Converting and Assigning Leads. I am sure I have done it correctly, however I still get an error window stating, Challenge Not yet complete... here's what's wrong: 
'Betty Nguyen' is not a lead or was not created with the correct fields. Is it me or the system?
 
Hello,

This is the trailhead questions which I am trying to solve :

Create an Apex class that returns an array (or list) of formatted strings ('Test 0', 'Test 1', ...). The length of the array is determined by an integer parameter.The Apex class must be called 'StringArrayTest' and be in the public scope.
The Apex class must have a public static method called 'generateStringArray'.
The 'generateStringArray' method must return an array (or list) of strings. Each string must have a value in the format 'Test n' where n is the index of the current string in the array. The number of returned strings is specified by the integer parameter to the 'generateStringArray' method.


Here is my code :

public class StringArrayTest {
    public static List <String> generateStringArray (Integer n) {
       List<String> List1 = new List<String> ();
        for(Integer i=0;i<n;i++) {
          List1.add('\'Test'+ i+'\'' );
  }
        System.debug(List1);
        return List1;
    } 

}


I am getting following error :

Challenge not yet complete... here's what's wrong: 
Executing the 'generateStringArray' method failed. Either the method does not exist, is not static, or does not return the proper number of strings.


I tried it many times but I am not able to solve this problem. Please help.