Monday, 25 January 2016

Attempt to de-reference a null object Issue in SOQL Querry

Attempt to de-reference a null object is common issue, this issue occurs when particular value will be null and we are trying get that value.

I am sharing one scenario where i also faced same issue.

 String MSORecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Managed Sales Opportunity').getRecordTypeId();  

map<Id,Opportunity> map_Opportunity = new map<id,Opportunity>([SELECT id,Stagename FROM Opportunity WHERE name = 'test Oppty'  AND recordtypeid = :MSORecordTypeId.substring(0,15)]); 
System.debug('Printing map==='+)map_Opportunity ;
 if(map_Opportunity ! = null){
    Opportunity oppty = map_Opportunity.get('OpportynityId');

I got error on the line (Opportunity oppty = map_Opportunity.get('OpportynityId');) Because map_Opportunity is having empty value when query filter condition got unsatisfied which is not null so obliviously if condition satisfied. 

To avoid such issue we need to add condition below 

 if(map_Opportunity.keyset().size() > 0){

Keep Exploring and sharing more and more .. :)

Monday, 11 January 2016

How to Invoke Opportunity Trigger when Opportunity Contact Role Created ?

As we already know Opportunity and contact are related through the junction object OpportunityContactRole and when OpportunityContRole created there wont be any update event to Opportunity. In that case how will we invoke opportunity trigger ?

How will we perform some action when an opportunity is linked to contact?

Possibly answer would be via workflow or trigger. Unfortunately we wont to able to write trigger on OpportunityContactRole nor workflow.

Below is workaround for that scenario.

  • Create  Visual-force page.
  • Create a temp field on Opportunity.
  • Add that vf page on opportunity layout.
  • Set height and width as zero so that it wont be displayed on opportunity layout. 
After OpportunityConRole created, it returns back to Opportunity layout that means inline vf page will be loaded by which one action method will be invoked to update temp field on opportunity.

Once that field is updated, obliviously Opportunity Trigger will be executed.

<apex:page standardController="Opportunity" extensions="OppTriggerInvoked" action="{!updateoppty}" />

public with sharing class OppTriggerInvoked {
    public Opportunity opp;
    public OppHelper( ApexPages.StandardController stdController ) {
        opp = ( Opportunity )stdController.getRecord();        
    public void updateoppty(){
        OppTriggerInvoked .updateopptyRecord( opp.Id );    
    @future public static void updateopptyRecord( Id oppId ) {
        Opportunity opp = new Opportunity (id = oppId );
        opp.Is_Updated__c =  true;
        update opp;