Sunday, 6 January 2019

Wrapper class in Apex


A Wrapper is simply an instance of a class that exposes some or all of the properties of a contained object,an object-oriented nomenclature.

ex :

public class MyWrapper
{

public Contact con {get;private set;}
public Opportunity opp {get;private set;}
public MyWrapper(Contact c,Opportunity o)
  {
     this.con=c;
     this.opp=o;
  }
}

ex 2 :


public class SObjectWrapper
{
  public SObject sObj {get;private set;}
  public Object name {get;private set;}
  Public Boolean deleteThis {get;private set;}
 //constructor
  Public SObjectWrapper(SObject so)
   {
     this.sObj=so;
     try{
          this.name=this.sObj.get('Name');
        }
        catch(Exception e){}
  }
}

public string selectString {get;set;}
public List<SObjectWrapper> sObjectWrpper {get;private set;}

public PageReference executeSelect()
{
   try{
      loadData(Database.query(this.selectString));
    }
   catch(Exception e)
   {
     logError(e.getMessage());
   }

}

private void loadData(List<SObject> sObjs)
{
  this.sObjectWrapperList = new List<SObjectWrapper>();
   for(SObject s : sObjs)
    {
    this.sObjectWrapperList.add(new SObjectWrapper(s));
   
   }
}

public PageReference deleteSelected()
{
  try
  {
    List<SObject> sObjs=new List<SObject>();
     for (SObjectWrapper so : this.sObjectWrapperList)
       {
         if(so.deleteThis==true)
            sObjs.add(so.sObj);
       }
     delete sObjs;
     executeSelect();
  }
  catch(Exception e)
   {
   logError(e.getMessage());
   }
  return null;
}

private void logError(String errorString)
{

 ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,errorString);
}

No comments:

Post a Comment