• pranav shah 40
  • NEWBIE
  • 140 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 43
    Questions
  • 19
    Replies
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



 
Hi All,
Below is my apex class and Vf page, to display list of all Sobjects in My org.. Now Suppose, If i select Account from Dropdown, i need to display all the list of all the account name in my org... how it will be done

public class ObjectList
{
public String Value{get;set;}
public List<SelectOption> getName()
{
List<Schema.SObjectType> gd= Schema.getGlobalDescribe().values();
List<SelectOption> options = new List<SelectOption>();
for (Schema.sobjecttype b: gd)
{
options.add(new SelectOption(b.getdescribe().getlabel(),b.getdescribe().getlabel()));
options.sort();

}
return options;
}
}


VF page:

<apex:page controller="ObjectList"> <apex:pageBlock title="ObjectList"> <apex:form id="pageload"> <apex:pageBlockSection > <apex:selectList value="{!Value}" size="1"> <apex:selectOptions value="{!Name}"> </apex:selectOptions> </apex:selectlist> </apex:pageblocksection> </apex:form> </apex:pageBlock> </apex:page>





\



System.SearchException: search term must be longer than one character:
Error is in expression '{!search_now}' in component <apex:commandButton> in page testvf4: Class.TestVF4.search_now: line 27, column 1
Class.TestVF4.search_now: line 27, column

I am getting above error in Vf page..
when i am trying to click on search button without entering any text


public class TestVF4 
{
    public List<Account> lstAccount {get;set;}
    private ApexPages.StandardSetController stndSetCtrl;
    public Integer pageNumber {get;set;}
    public Boolean isHasPrev {get;set;}
    public Boolean isHasNext {get;set;}
    public string  keyword {get; set;}

    public TestVF4()
    {
        lstAccount = new List<Account>();
        stndSetCtrl = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Id, Name, Rating, Type, Industry from Account ORDER BY CreatedDate DESC]));//100
        stndSetCtrl.setPageSize(10);
        fetchRecords();
    }
    public string getkeyword()
    {
     return keyword;
    }    
    public void setkeyword(String input)
    {
     keyword=input;
    }
    public pageReference search_now()
    {
     lstAccount=(List<Account>)[FIND :keyword in all Fields Returning Account(Name, Rating, Type, Industry)][0];
     return null;
    }
    
    public void fetchRecords()
    {
        lstAccount = stndSetCtrl.getRecords();// 1-10
        pageNumber = stndSetCtrl.getPageNumber();
        isHasPrev = stndSetCtrl.getHasPrevious();
        isHasNext = stndSetCtrl.getHasNext();
    }
    public void next()
    {
        stndSetCtrl.next();
        fetchRecords();
    }
    public void prev()
    {
        stndSetCtrl.previous();
        fetchRecords();
    }
    public void first()
    {
        stndSetCtrl.first();
        fetchRecords();
    }
    public void last()
    {
        stndSetCtrl.last();
        fetchRecords();
    }
}




Hi All,,

please find the below code. as i am trying to update a field (Total Opportunity Amount) on Account object whenever opportunity ia
added, if one opportunity is moved from one Account to another account.. other account field is getting updated, but the value is not getting subtracted from previous one

please check my else block and let me know what issue i am facing...please dont  write an code.... just expalin me logic what can i do.. so that i can learn and try myself


public void opportunityownerchange(list<opportunity> opps,map<id,opportunity> mapopportunity)
    {
        set<id> opt=new Set<id>();
        for(opportunity opp:opps)
        {
         opt.add(opp.Accountid);
        }
        List<Account> lstAcct =[select id,Name,Total_Opportunity_Amount__c,(select id, Amount from opportunities) from account where Id IN:opt];
        for(Account acc:lstAcct)
        {
        for(Opportunity opp:opps)
        {
            double TotalAmount=0;
            Opportunity oldopp = mapopportunity.get(opp.Id);
            if(oldopp.AccountID!=opp.AccountID && opp.AccountID!= null )
            {
            if(opp.Amount!=null)
            {  
              totalAmount=TotalAmount+opp.Amount;
            }
            else
            {
             totalAmount= totalAmount-opp.Amount;
            }
            }  
            acc.Total_Opportunity_Amount__c=totalAmount;
            lstacct.add(acc);
        }
        }
        update lstacct;
    }
}
Hi,

can someone explain me the below code. i am facing some difficulty in learning... the trigger is for geeting opportunity amount updated into Account

public class opportunityhandler
{
    public void opportunityamount(list<opportunity> newopportunity)
    {
        set<Id> setOppName=new set<Id>();
        List<Account> lstActs =new list<Account>();
        List<Opportunity> opps=new list<Opportunity>();
        for(opportunity opp:newopportunity)
        {
            setOppname.add(opp.Accountid);
        }
        
        list<Account> LstAccs= [select id,Name,Total_Opportunity_Amount__c,(select id, Amount from opportunities) from account where Id IN:setOppname];
        for(Account acc: lstAccs)
        { 
            double TotalAmount=0;
            for(Opportunity opp:acc.opportunities)
            {
                if(opp.Amount!=null)
                {  
                    totalAmount=TotalAmount+opp.Amount;
                }
            }  
            acc.Total_Opportunity_Amount__c=totalAmount;
            lstacts.add(acc);
        }
        update lstacts;
    }
}
Suppose i am writing a a trigger handler class on opportunity..
if for one opportunity i need to change the account owner,, how it will be done using trigger..
how can i compare old and new value.

i am trying to write in the following way..
please suggest

public void updateAccountowner(list<opportunity> opportunities, map<id, opportunity> mapoldopportunity)
   {
    for(Opportunity opp:opportunities)
   {
      if(mapoldopportunity.get(opp.id).Amount!=='' && opp.amount!=='')
     {
     
     }
   }
   }

 
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];
    {
    
    }
  }
 }
 
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???
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?
 
these is What i have Written,,

trigger UpdateAccount on Account (after insert,after update, after delete, after undelete) 
{
set<ID> setAccountIDs=new Set<ID>();
for (Account a:Trigger.new)
{
setAccountIDs.add(a.AccountID);
List <Account> accounts=[select ID,Name from Account Where ID IN: setAccountIDs];
String accName = '';
a.name=accName;
}
update account;
}
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.