Friday, 17 January 2014

Insert in custom object using VF page and custom controller and use trigger with class

/*
     Insert values on an Custom Object using VF page and custom controller as well as on basis of this use a trigger to insert value in another Custom object  using a trigger and a class.
*/
/*
Consideration following for below code :-
your object names :- AKG__A__c,  AKG__B__c
VF page name:- t1ONACon , controller name :- t1ONACu
Apex Trigger name :- InsertOnB , Apex Class :- trgInsobjB

*/
VF page name:- t1ONACon
<apex:page controller="t1ONACu" >

<apex:pageMessages />
<apex:form >
        <apex:outputLabel value="Saved Successfully!"  style="font-weight:bold;color:green" rendered="{!errFlag}"/>
 <apex:pageBlock title="Insert object A">

     <apex:pageblockButtons >
         <apex:commandButton value="Save!!" action="{!savemethod}"/>
     </apex:pageblockButtons>
  <apex:pageblocksection title="Basic Information">
      <apex:inputField value="{!Aobjstr.name}"/>
     <apex:inputField value="{!Aobjstr.aaa__c}"/>
  </apex:pageblocksection>
 </apex:pageBlock>
</apex:form> 
</apex:page>
 Controller name :- t1ONACu
public with sharing class t1ONACu {

public AKG__A__c Aobjstr {get;set;}
public boolean errFlag{get;set;}

public t1ONACu(){
 Aobjstr= new  AKG__A__c();
 errFlag = false;
}
public void savemethod(){
 
  try{
   insert Aobjstr;
   errFlag = true;
   
   }
   catch(Exception e){
   errFlag = false;  
   ApexPages.addMessage( new ApexPages.message(ApexPages.Severity.Error,'MY ERRRR'+e)) ;
   
   
   }


}

}

Apex Trigger name :- InsertOnB 

trigger InsertOnB on A__c (After insert) {

set<id> objAId = new set<id>();

if(trigger.isinsert){
    for(A__c a:Trigger.new){
    
        system.debug('~~~~~~a'+a);
        objAId.add(a.id); 
    }
        system.debug('~~~~~~objAId'+objAId);
       
        trgInsobjB clsB = new trgInsobjB();
        clsB.insertObjB(objAId,Trigger.new);
}

}

 Apex Class :- trgInsobjB 

public with sharing class trgInsobjB{

    public void insertObjB(set<id> aid,A__c[] Alist ){

    Id myid= new List<id>(aid)[0];
    System.debug('~~~~~~InSide Class aid '+aid+' ~~~~~ Alist '+Alist+'~~~~myid '+myid);
        
        if(aid != null)
        {
            AKG__B__c B = new AKG__B__c();
            B.name = Alist[0].Name+ 'FRM A';
           B.AKG__B_A__c  = myid;
           B.AKG__OnB__c = myid;
    insert B;            
        }

    }
}