• Manjunath
  • SMARTIE
  • 505 Points
  • Member since 2012

  • Chatter
    Feed
  • 13
    Best Answers
  • 4
    Likes Received
  • 1
    Likes Given
  • 18
    Questions
  • 163
    Replies

Hi,

I want to get the Account.Name from the Account object from the Contact (before insert) Trigger. 

1. I fill Contact details
2. I select the Account

Then I fire my trigger. My trigger is for Contact object. 

I have the Contact object details

Contact[] cont = Trigger.new;

 

I tired to access the Account.Name related to this Contact by

cont.Account.Name
But it returns NULL.

Please Help me.

Thanks in advance
Hi, I have the following code and I can get the E-sig to work in preview.  My issues is adjusting this code to work so I can add VF page via page layout on a Case record.  It current is not showing on my available VF pages to add via page layout editor.
It's a controller issue, need to make this custom controller work with the Standard Case controller, so I can see and add (I think).

Thanks,  Paul

Visualforce Page

<apex:page docType="html-5.0" controller="CapturePSignatureController" showheader="false" sidebar="false" standardStylesheets="false" id="pg">
 <apex:includeScript value="/soap/ajax/28.0/connection.js"/>
 
 <style>
  .container {
   text-align: center;
   font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
   color: cadetblue;
   font-weight: 500;
   font-size: 14px;
  }
  
  .button {
   font-family: calibri;
   border-radius: 8px;
   background-color: rgb(51, 116, 116);
   height: 36px;
   color: azure;
   font-size: 17px;
   border-width: 0px;
   width: 116px;
  }
 </style>
 <apex:form id="pbform">
  <apex:pageMessages />
  <div class="container">
   <h1 class="labelCol vfLabelColTextWrap ">Record Patient Signature:</h1>
   <canvas id="PsignatureCanvas" height="100px" width="350px" style="border: 3px solid antiquewhite; border-radius: 8px;" ></canvas>
  </div><br/>
  
  <div style="margin-left: 41%;">
   <apex:commandButton value="Save Patient Signature" onclick="savePSignature();return false;" styleClass="button"/>&nbsp;&nbsp;&nbsp;
   <apex:commandButton value="Clear" onclick="clearSign();return false;" styleClass="button"/>
  </div>
 </apex:form>

  <script>
  var canvas;
  var context;
  var drawingUtil;
  var isDrawing = false;
  var accountId = '';
  var prevX, prevY, currX, currY = 0;
  var accountId;

   function DrawingUtil() {
   isDrawing = false;
   canvas.addEventListener("mousedown", start, false);
   canvas.addEventListener("mousemove", draw, false);
   canvas.addEventListener("mouseup", stop, false);
   canvas.addEventListener("mouseout", stop, false);
   canvas.addEventListener("touchstart", start, false);
   canvas.addEventListener("touchmove", draw, false);
   canvas.addEventListener("touchend", stop, false);
   w = canvas.width;
      h = canvas.height;
  }

   function start(event) {
   event.preventDefault();
   
   isDrawing = true;
   prevX = currX;
   prevX = currY;
   currX = event.clientX - canvas.offsetLeft;
   currY = event.clientY - canvas.offsetTop;
   
   context.beginPath();
   context.fillStyle = "cadetblue";
   context.fillRect(currX, currY, 2, 2);
            context.closePath();
   
  }

   function draw(event) {
   event.preventDefault();
   if (isDrawing) {
    prevX = currX;
             prevY = currY;
             currX = event.clientX - canvas.offsetLeft;
             currY = event.clientY - canvas.offsetTop;
    context.beginPath();
    context.moveTo(prevX, prevY);
    context.lineTo(currX, currY);
    context.strokeStyle = "cadetblue";
    context.lineWidth = "2";
    context.stroke();
    context.closePath();
   }
  }

   function stop(event) {
   if (isDrawing) {
    context.stroke();
    context.closePath();
    isDrawing = false;
   }
  }
  
  function clearSign() {
   context.clearRect(0,0,w,h);
  }

   canvas = document.getElementById("PsignatureCanvas");
  context = canvas.getContext("2d");
  context.strokeStyle = "black";
  context.lineWidth = "2";
  drawingUtil = new DrawingUtil(canvas);
  

   function savePSignature() {
   var strDataURI = canvas.toDataURL();
   strDataURI = strDataURI.replace(/^data:image\/(png|jpg);base64,/, "");
   var accId = location.href.split('=')[1];
   accountId = accId;
   var result = CapturePSignatureController.savePSignature(strDataURI, accId, processResult);
  }

   function processResult(result) {
   alert(JSON.stringify(result));
   window.location.href = '/'+accountId;
  }

  </script>


</apex:page> 

Controller

global with sharing class CapturePSignatureController {
 
 @RemoteAction
 global static String savePSignature(String imageUrl, String accountId) {
  
  try {
   Attachment accSign = new Attachment();
   accSign.ParentID = accountId;
   accSign.Body = EncodingUtil.base64Decode(imageUrl);
   accSign.contentType = 'image/png';
   accSign.Name = 'Patient Signature Image';
   accSign.OwnerId = UserInfo.getUserId();
   insert accSign;
   
   return 'success';
   
  }catch(Exception e){
   system.debug('---------- ' + e.getMessage());
   return JSON.serialize(e.getMessage());
  }
  return null; 
 }

}
 
This is the snap shot for below issue
----------------This is the Controller Class Where i am facing Problem.---------------------
public class RerenderEx {

    public contact con{set;get;}
    public boolean Abool{set;get;}
    public boolean Bbool{set;get;}    

    public RerenderEx()
    {
        con=new contact();
        Abool=false;
        Bbool=false;
    }
    public void saveNew() {
        insert con;
        con.clear();//con=new contact();
    }

    public void saveSec() {
        insert con;
        Abool=true;
    }
    
    public void EditSec() {
        Abool=false;
        Bbool=true;
    }
    
     public void updateSec() {
        update con;
    }

}
------------------------------This is the Test Class which is unable to Cover above Class .Its covering only 50%----------
@isTest
public class RerenderEx_TC
{
    static testMethod void testMthd()
    {
     boolean Abool=false;
     boolean Bbool=false;    
    RerenderEx r=new RerenderEx();
     contact con=new contact(lastname='xxx');
    r.saveNew();
     insert con;
     con.lastname='xyy';
     update con;
      r.saveSec();
     r.EditSec();
     r.updateSec();
     }
}
 
here I have to get the month, in the picklist value which is having format like YYYY/MM/DD. 

trigger Totalbilledhrs on Billing_MVA__c (after insert, after update)
{
    string sdate;
    string edate;
    string startdate;
    string enddate;
    list<string> testlist = new list<string>();
    list<string> testlist1 = new list<string>();
    public map<string,string> fieldmap = new map<string,string>();
    fieldmap.put('01','Jan');
    fieldmap.put('02','Feb');
    fieldmap.put('03','Mar');
    fieldmap.put('04','Apr');
    fieldmap.put('05','May');
    fieldmap.put('06','Jun');
    fieldmap.put('07','jul');
    fieldmap.put('08','Aug');
    fieldmap.put('09','Sep');
    fieldmap.put('10','Oct');
    fieldmap.put('11','Nov');
    fieldmap.put('12','Dec');
    
   
    List<Opportunity> opplist = new List<Opportunity>();
    integer counter = [select count() from Opportunity where BCRNo__c != null];
    if(counter>0)
    {
        for(Billing_MVA__c Bill : Trigger.new)
        {
            sdate = Bill.startdate__c;
            edate = Bill.end_date__C;
            List<String> stdate = sdate.split('/');
            List<String> endate = edate.split('/');
                 
            if(stdate != null & endate !=null)
            {
                for(string ss : stdate)
                {
                    string ss1 = ss.get(1);         /****************ERROR IN THIS LINE******************/
                    if(fieldmap.containskey(ss1) == true)
                    {
                        startdate = fieldmap.get(ss1);
                    }
                }

                for(string ss2 : endate)
                {
                    string ss3 = ss2.get(1);
                    if(fieldmap.containskey(ss3)== true)
                    {
                        enddate = fieldmap.get(ss3);
                    }
                }
                system.debug('***********'+enddate);
                
            }
        }
    }
    
}
Hi,

I am running in to an issue that I have not been able to solve and I was hoping that someone might have an idea of how to fix it. I have a visualforce page that allows me to add and remove child junction objects called Opportunity Competotors to the parent Opportunity object. the Opportunity Competitor object joins the Opportunity and Account objects with Account being in a master-detail relationship and Opportunity is a parent object in a lookup relationship. So because of this the Account field is required.

I am able to add new Opportunity Competitor junction objects to the page by adding a new wrapper object, however, it will not let me delete the unsaved junction object without first entering in an Account that meets the filter criteria. This is annoying from an end user perspective because there is no reason that they should need to enter information for something that they are just trying to delete.

My issue seems to be that I cannot even get to the delete method (delWrapper) before the error is thrown. It appears to be entering the getter method for the wrapper class at the very top of the controller and then entering the getter method for the Opportunity Competitor in the Wrapper class. at this point, I have not been able to pass which action is being taken as the param in the delete command button gets passed after the rerender I believe and I am not even able to reach the delete or save methods before this validation that there is an Account is performed.

Any ideas about how to get around this would be greatly appreciated.

this code was based on an idea in Bob Buzzard's blog located here:
http://bobbuzzard.blogspot.co.uk/2011/07/managing-list-of-new-records-in.html

controller:
public with sharing class OppCompetitorInsertController {
	 
	 public List<OppCompetitorWrapper> wrappers {get; set;}/* {if((!OppCompetitorWrapper.isSaved) && (OppCompetitorWrapper.oppComp.Competitor__c != null))
	 												{
	 													
	 												}
	 												} set;}*/
	 public Integer testId {get; set;}
	 public static Integer toDelIdent {get; set;}
	 public static Integer addCount {get; set;}
	 private Integer nextIdent=0;
	 private ApexPages.StandardController controller;
	 public Opportunity oppRecord {get; set;}
	  
	 public OppCompetitorInsertController(ApexPages.StandardController controller)
	 {
	 	  system.debug('test1');
	 	  this.controller = controller;
	 	  if (!Test.isRunningTest())
	 	  {
				controller.addFields(new List<String>{'Id', 'Name'});
	 	  }
	 	  oppRecord = (Opportunity)controller.getRecord();
	 	  system.debug(oppRecord);
	 	  
	 	  
	 	  List<Opportunity_Competitor__c> currentCompetitorList = new List<Opportunity_Competitor__c>{};
	 	  currentCompetitorList = [select Name, Id, Competitor__c, Competitor_Details__c, Lost_To__c, Opportunity__c, Primary__c, Replaced__c, Relationship__c, Opportunity__r.Id,
	 	  								  Opportunity__r.Competitor_Replaced__c, Opportunity__r.Competitor_Lost_To__c, Opportunity__r.Competitor_Complemented__c, Opportunity__r.Primary_Competitor__c
	 	  						  from Opportunity_Competitor__c
	 	  						  where Opportunity_Competitor__c.Opportunity__c =: oppRecord.Id];
		  wrappers = new List<OppCompetitorWrapper>();
		  
		  for(Opportunity_Competitor__c oppcomp : currentCompetitorList)
		  {
		  	system.debug(oppcomp.Id);
		  	wrappers.add(new OppCompetitorWrapper(nextIdent++, oppcomp, true, false));
		  }
	 }
	 
	 
	  
	 public void delWrapper()
	 {
	 	system.debug('checkpoint1');
		  Integer toDelPos=-1;
		  for (Integer idx=0; idx<wrappers.size(); idx++)
		  {
			   if (wrappers[idx].ident==toDelIdent)
			   {
			    	toDelPos=idx;
			   }
		  }
		  system.debug('checkpoint2');
		  system.debug(toDelPos);
		  if (-1!=toDelPos)
		  {
		  		if((wrappers.get(toDelPos).oppComp.Relationship__c == 'Replaced') && (wrappers.get(toDelPos).oppComp.Primary__c))
		  		{
		  			oppRecord.Competitor_Replaced__c = null;
		  		}
		  		if((wrappers.get(toDelPos).oppComp.Relationship__c == 'Lost To') && (wrappers.get(toDelPos).oppComp.Primary__c))
		  		{
		  			oppRecord.Competitor_Lost_To__c = null;
		  		}
		  		if((wrappers.get(toDelPos).oppComp.Relationship__c == 'Complemented') && (wrappers.get(toDelPos).oppComp.Primary__c))
		  		{
		  			oppRecord.Competitor_Complemented__c = null;
		  		}
		  		if((wrappers.get(toDelPos).oppComp.Relationship__c == null) && (wrappers.get(toDelPos).oppComp.Primary__c))
		  		{
		  			oppRecord.Primary_Competitor__c = null;
		  		}
		  		
		  		if(wrappers.get(toDelPos).isSaved)
		  		{
		  			try
		  			{
		  				delete wrappers.get(toDelPos).oppComp;
		  				update oppRecord;
		  			}
				  	catch (DmlException e)
				  	{
				  		system.debug(LoggingLevel.ERROR, 'There was an error: ' + e.getMessage());
				  	}
		  			
		  			
		  		}
		  		system.debug('checkpoint3');
		   		wrappers.remove(toDelPos);
		  }
	 }
	  
	 public void addRows()
		 {
		  for (Integer idx=0; idx<addCount; idx++)
		  {
		   	wrappers.add(new OppCompetitorWrapper(nextIdent++, oppRecord, false, true));
		  }
	 }
	  
	 public void /*PageReference*/  save()
	 {
	 	
	 	
		List<Opportunity_Competitor__c> oppCompsToUpsert = new List<Opportunity_Competitor__c>();
		List<Opportunity_Competitor__c> oppCompsReplaced = new List<Opportunity_Competitor__c>();
		List<Opportunity_Competitor__c> oppCompsLostTo = new List<Opportunity_Competitor__c>();
		List<Opportunity_Competitor__c> oppCompsComplemented = new List<Opportunity_Competitor__c>();
		List<Opportunity_Competitor__c> oppCompsPrimary = new List<Opportunity_Competitor__c>();
		list<OppCompetitorWrapper> ocwsChangedIsSaved = new list<OppCompetitorWrapper>{};
		Integer errorCount = 0;
		
		for (OppCompetitorWrapper wrap : wrappers)
		{
			
			Integer ocCount = 0;
			oppCompsToUpsert.add(wrap.oppComp);
			if(!wrap.isSaved)
			{
				wrap.isNew = false;
				wrap.isSaved = true;
				ocwsChangedIsSaved.add(wrap);
			}
			
			if((wrap.oppComp.Relationship__c == 'Replaced') && (wrap.oppComp.Primary__c))
			{
				oppCompsReplaced.add(wrap.oppComp);
		  		
			}
			for(Opportunity_Competitor__c ocr : oppCompsReplaced)
			{
				if(ocCount > 0)
				{
					ocr.Relationship__c.addError('You can only have one primary competitor that is replaced.');
					errorCount++;
				}
				ocCount++;
			}
			ocCount = 0;
			
			if((wrap.oppComp.Relationship__c == 'Lost To') && (wrap.oppComp.Primary__c))
			{
				oppCompsLostTo.add(wrap.oppComp);
			}
			for(Opportunity_Competitor__c oclt : oppCompsLostTo)
			{
				if(ocCount > 0)
				{
					oclt.Relationship__c.addError('You can only have one primary competitor that is lost to.');
					errorCount++;
				}
				ocCount++;
			}
			ocCount = 0;
			
			if((wrap.oppComp.Relationship__c == 'Complemented') && (wrap.oppComp.Primary__c))
			{
				oppCompsComplemented.add(wrap.oppComp);
			}
			for(Opportunity_Competitor__c occ : oppCompsComplemented)
			{
				if(ocCount > 0)
				{
					occ.Relationship__c.addError('You can only have one primary competitor that is complemented.');
					errorCount++;
				}
				ocCount++;
			}
			ocCount = 0;
			
			if((wrap.oppComp.Primary__c) && (wrap.oppComp.Relationship__c == null))
			{
				oppCompsPrimary.add(wrap.oppComp);
			}
			for(Opportunity_Competitor__c ocp : oppCompsPrimary)
			{
				if(ocCount > 0)
				{
					ocp.Primary__c.addError('You can only have one competitor that is primary when a Relationship value has not been selected.');
					errorCount++;
				}
				ocCount++;
			}
			ocCount = 0;
	  	}
		   
		if(errorCount < 1)
		{
			if(!oppCompsReplaced.IsEmpty())
			{
				oppRecord.Competitor_Replaced__c = oppCompsReplaced.get(0).Competitor__c;
			}
			else
			{
				oppRecord.Competitor_Replaced__c = null;
			}
			
			if(!oppCompsLostTo.IsEmpty())
			{
				oppRecord.Competitor_Lost_To__c = oppCompsLostTo.get(0).Competitor__c;
			}
			else
			{
				oppRecord.Competitor_Lost_To__c = null;
			}
			
			if(!oppCompsComplemented.IsEmpty())
			{
				oppRecord.Competitor_Complemented__c = oppCompsLostTo.get(0).Competitor__c;
			}
			else
			{
				oppRecord.Competitor_Complemented__c = null;
			}
			
			if(!oppCompsPrimary.IsEmpty())
			{
				oppRecord.Primary_Competitor__c = oppCompsPrimary.get(0).Competitor__c;
			}
			else
			{
				oppRecord.Primary_Competitor__c = null;
			}
			
			try
		    {
		    	update oppRecord;
				upsert oppCompsToUpsert;
		    }
		  	catch (DmlException e)
		  	{
		  		system.debug(LoggingLevel.ERROR, 'There was an error: ' + e.getMessage());
		  	}
		}
		else
		{
			for(OppCompetitorWrapper ocw : ocwsChangedIsSaved)
			{
				ocw.isSaved = false;
			}
			ocwsChangedIsSaved.clear();
		}
		  
		  
		   
		  //return new PageReference('/' + Schema.getGlobalDescribe().get('Opportunity').getDescribe().getKeyPrefix() + '/o');
		//return new PageReference('/' + oppRecord.Id);
	 }
	 
	 public void methodOne() 
     {
      	  system.debug('entering method 1');
	      OppCompetitorWrapper selectedLine;
	
	      for(integer i = 0; i < wrappers.size(); i++)
	      {
	        if(wrappers[i].ident == testId)
	        {
	          wrappers[i].beingDeleted = true; 
	        }
	        system.debug(wrappers[i]);
	      	system.debug(wrappers[i].beingDeleted);
	      }
	      
	      
	      
	      
     }
	  
	 public class OppCompetitorWrapper
	 {
		 
		  public Integer ident {get; private set;}
		  public boolean isSaved {get; private set;}
		  public boolean isNew {get; private set;}
		  public boolean beingDeleted {get; set;}
		  public String tooManyReplacedError {get; set;}
		  
		  public Opportunity_Competitor__c oppComp {
		  	get{
		      	system.debug('oppComp.Id = ' + oppComp.Id);
		      	system.debug('isNew = ' + isNew);
		      	system.debug('isSaved = ' + isSaved);
		      	if((oppComp.Id == null) && (isSaved == false) && (isNew == false))
		      	{
		      		oppComp.Competitor__c = '0018000000t9eJq';
		      		return oppComp;
		      	}
		      	else if((oppComp.Id == null) && (isSaved == false) && (isNew == true))
		      	{
		      		system.debug('oppComp = ' + oppComp);
		      		
		      		Opportunity_Competitor__c oppComp2 = new Opportunity_Competitor__c(Opportunity__c = oppComp.Opportunity__c);
		      		system.debug('oppComp2 = ' + oppComp2);
		      		return oppComp2;
		      	}
		      	else
		      	{
		      		return oppComp;
		      	}
		          
		      } 
		      set;
		  }
		  public String backgroundColor {
		      get{
		      	system.debug('oppComp.Id = ' + oppComp.Id);
		      	system.debug('isSaved = ' + isSaved);
		        if(isSaved == true)
		          return '#eeeeef';
		        else 
		          return '#FFF';
		      } 
		      set;
		  }
		  
		  set<Id> idsToCheck = new set<Id>{};
		  public OppCompetitorWrapper(Integer inIdent, Opportunity opp, boolean isRecordSaved, boolean isRecordNew)
		  {
		  	   isNew = isRecordNew;
		  	   isSaved = isRecordSaved;
			   ident=inIdent;
			   oppComp = new Opportunity_Competitor__c(Opportunity__c = opp.Id);
			   tooManyReplacedError ='';
	  	  }
	  	  
	  	  public OppCompetitorWrapper(Integer inIdent, Opportunity_Competitor__c currentoppcomp, boolean isRecordSaved, boolean isRecordNew)
		  {
		  	   isNew = isRecordNew;
			   ident=inIdent;
			   isSaved = isRecordSaved;
			   oppComp = currentoppcomp;
			   tooManyReplacedError ='';
	  	  }
	  	  
	 }
}
page:
<apex:page standardController="Opportunity" extensions="OppCompetitorInsertController">
 <apex:form >
 
 
  
   <apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" >
		<apex:param name="firstParam" assignTo="{!testId}" value="" />
   </apex:actionFunction>
	
 
 
   <apex:pageBlock title="Add Competitors">
   <apex:pageMessages />
   
					
      <apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable" width="95%">
         
         
         <apex:column width="23px" style="background-color: {!wrapper.backgroundColor};">
         	<apex:outputLabel value="Primary: " for="primaryFieldId" style="font-weight: bold; padding-right:7px"/><br />
         	<apex:inputField value="{!wrapper.oppComp.Primary__c}" id="primaryFieldId"/>
         </apex:column>
         
         
         <apex:column width="440px" style="background-color: {!wrapper.backgroundColor};">
         	<apex:outputLabel value="Competitor: " for="competitorFieldId" style="font-weight: bold"/><br />
         	<apex:inputField value="{!wrapper.oppComp.Competitor__c}" style="height:20px; width:400px" id="competitorFieldId"/>
         </apex:column>
         
        
         
         <apex:column width="43px" style="background-color: {!wrapper.backgroundColor};">
         	<apex:outputLabel value="Relationship: " for="relationshipFieldId" style="font-weight: bold; padding-right:7px"/><br />
         	<apex:inputField value="{!wrapper.oppComp.Relationship__c}" id="relationshipFieldId"/>
         </apex:column>
         
         
         
         <apex:column width="105px" style="background-color: {!wrapper.backgroundColor};">
         	<apex:outputLabel value="Competitor Details: " for="compDetailsFieldId" style="font-weight: bold"/><br />
         	<apex:inputField value="{!wrapper.oppComp.Competitor_Details__c}" style="height:20px; width:300px" id="compDetailsFieldId"/>
         </apex:column>
         
         <apex:column width="14px" style="background-color: {!wrapper.backgroundColor};">
         	<apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable" style="width:40px">
            	<apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/>
            	<apex:param name="beingDelTrue" value="true" assignTo="{!wrapper.beingDeleted}"/>
            </apex:commandButton>
         </apex:column>
         
         
          <!--
         <apex:column width="23px" style="background-color: {!wrapper.backgroundColor};">
		      			<div>
		      			
					    <apex:outputPanel onclick="methodOneInJavascript('{!wrapper.ident}')"  > 
					        test
					    </apex:outputPanel>
					    
       					</div>
       					 
		</apex:column>
        -->
         
      </apex:pageBlockTable>
      <apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable">
         <apex:param name="addCount" value="1" assignTo="{!addCount}"/>
      </apex:commandButton>
      <apex:commandButton value="Save All" action="{!save}" rerender="wtable">
      </apex:commandButton>
   </apex:pageBlock>
 </apex:form>
</apex:page>

User-added image


 

This is a simplified version of my issue, if it doesnt make sense I may have to explain complete scenario. But basically I am having problems  where the value I have is a field of type email, and there is a map whose key's are of type string. The map's value are of type string because the map was build from parsing a JSON response to a webservice call. And the JSON parser only has a getText() value, there is nothing specific to pull out an email value. The map returns false if i perform a containsKey on it, even though if I print the keySet out I see it in there.

 

But I am able to query for records like Leads by looking for those where the email field is contained in a set of strings.

 

I wrote a test and it seems to prove my issue:

Lead l = new Lead(lastName = 'last', Company = 'company', email = 'email@emailTest.com', Country = 'US');
insert l;

Map<String, String> emailsAsStringsMap = new Map<String, String>();
emailsAsStringsMap.put('email@emailTest.com', 'test');

system.debug('THIS IS emailsAsStringsMap.keySet(): ' + emailsAsStringsMap.keySet());


for(Lead insertedLead : [SELECT Id, Email FROM Lead WHERE Email IN : emailsAsStringsMap.keySet()]){
	system.debug('THIS IS insertedLead.Email: ' + insertedLead.Email);
	system.debug('THIS IS emailsAsStringsMap.containsKey(insertedLead.Email): ' + emailsAsStringsMap.containsKey(insertedLead.Email));   
}

 

 

This is the output:

19:02:51.329 (329237000)|USER_DEBUG|[7]|DEBUG|THIS IS emailsAsStringsMap.keySet(): {email@emailTest.com}
19:02:51.329 (329848000)|SOQL_EXECUTE_BEGIN|[10]|Aggregations:0|select Id, Email from Lead 
19:02:51.352 (352823000)|SOQL_EXECUTE_END|[10]|Rows:1
19:02:51.353 (353150000)|SYSTEM_METHOD_ENTRY|[7]|QueryLocatorIterator.QueryLocatorIterator()
19:02:51.353 (353170000)|SYSTEM_METHOD_EXIT|[7]|QueryLocatorIterator
19:02:51.353 (353561000)|USER_DEBUG|[11]|DEBUG|THIS IS insertedLead.Email: email@emailtest.com
19:02:51.353 (353694000)|USER_DEBUG|[12]|DEBUG|THIS IS emailsAsStringsMap.containsKey(insertedLead.Email): false

 

See how the email is in the keySet as a String, but the map containsKey value doesn't seem to be able to equate the email field to the string value.

 

 

  • April 23, 2013
  • Like
  • 0

I am creating a VF page rendered as a PDF and would like to display Account information and active programs from the Program_c object (Program_c has master detail relationship with Account)

 

I am getting this error:

 

SObject row was retrieved via SOQL without querying the requested field: Program__c.Active__c

 


Below is the code for my Class:

 

public class ActiveProgramsExtension {
    
    Account CurrentAccount = null;
    List<Program__c> ActivePrograms = null;
    
    public ActiveProgramsExtension(ApexPages.StandardController controller) {
        CurrentAccount = (Account)controller.getRecord();
        ActivePrograms = [SELECT Id, Name FROM Program__c WHERE Account__c= :CurrentAccount.Id and Active__c=TRUE];
    }
    
    public List<Program__c> getActivePrograms() { return ActivePrograms; }
    
     public static testMethod void testContactsExtension()
    {
        Account testAccount = new Account(Name='Dev Church of the Sandbox',ISO_Code__c='US');
        
        ApexPages.StandardController controller  = new ApexPages.StandardController(testAccount);
      ActiveProgramsExtension BEC = new ActiveProgramsExtension(controller);
      List<Program__c> ActivePrograms = BEC.getActivePrograms();
    }
}

 

And here is the code for my page:

 

<apex:page standardController="Account" extensions="ActiveProgramsExtension" showHeader="false" renderAs="pdf">
    <apex:pageBlock title="Account Profile">

          <apex:pageBlockTable value="{!ActivePrograms}" var="ActiveProg">
             <apex:column >
                <apex:outputLink value="/{!ActiveProg.Id}" target="_parent">{!ActiveProg.Name}</apex:outputLink>
            </apex:column>
            <apex:column value="{!ActiveProg.Active__c}" />
            
            </apex:pageBlockTable>
    </apex:pageBlock>
     
</apex:page>

 

 

HELP!!!!

 

  • April 09, 2013
  • Like
  • 0

I finally got my code to work and now I need help with my Test Class.  My Test Class is only giving me 24% code coverage.  I am not sure how to test the bottom portion of my trigger.  Please advice.  

 

 

Here is my trigger:

 

trigger TaskSendEmail on Task (before update) {
// Don't forget this- all triggers in SF are bulk triggers and so
// they can fire on multiple objects. So you need to process objects
// in a FOR loop.
Set<Id> CBIds = new Set<Id>();

for(Task tsk: Trigger.New)

if(tsk.RecordTypeId == '012Z00000004WFV' && tsk.Status == 'Completed')

CBIds.add(tsk.CreatedById);

// Build a map of all users who created the tasks.
Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :CBIds]);

for(Task tsk : Trigger.New){
if(!TriggerHelperClass.HasAlreadyFired()){

if(tsk.RecordTypeId == '012Z00000004WFV' && tsk.Status == 'Completed')
{


User theUser = userMap.get(tsk.CreatedById);

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {theUser.Email};
mail.setToAddresses(toAddresses); // Set the TO addresses
mail.setSubject('The following Task has been Completed'); // Set the subject
// Next, create a string template. Specify {0}, {1} etc. in place of actual values.
// You can replace these values with a call to String.Format.
String template = 'The following Task has been Completed: \n\n';
template+= 'Subject: {0}\n';
template+= 'Comments: {1}\n\n';
template+= 'Click the link to access the record: https://cs11.salesforce.com/{2}\n';
String duedate = '';

if (tsk.ActivityDate==null)
duedate = '';
else
duedate = tsk.ActivityDate.format();

List<String> args = new List<String>();
args.add(tsk.Subject);
args.add(tsk.Description);
args.add(tsk.Id);


// Here's the String.format() call.
String formattedHtml = String.format(template, args);

mail.setPlainTextBody(formattedHtml);

TriggerHelperClass.setAlreadyFired();
Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});

}
}
}
}

 

 

 

Here is my Test Class:

 

@isTest (seeAllData=true)
public class TestTaskSendEmail {

static testMethod void myUnitTest(){


Test.startTest();

Task testTask = new Task ();
testTask.OwnerId='005G0000001jWxo';
testTask.Type='Email';
testTask.Subject='Test';
testTask.ActivityDate=system.Today();
testTask.Priority='Normal';
testTask.Status='Not Started';
insert testTask;

testTask.Status ='Completed';
update testTask;

System.assertEquals (testTask.Status,'Completed');
Test.stopTest();

}
}

  • April 04, 2013
  • Like
  • 0

Hi All,

 

I am stuck at a requirement which I am desperate to get out from. Here is what I need:

 

There is a custom object Note__c that has a look up relation with Account. A VF Page is having lookup field on it that will let the user select the Account. Now whichever Account is selected, the relatedlist NOTES should be displayed on the same VF Page. I have used a button as of now that would be required to display the notes.

 

The code is : 

<apex:page standardController="Account" extensions="AccNoteExtension">

    <apex:form >
       Please Select an Account: <apex:inputField value="{!No.Account__c}"/>
       <br/>
       <apex:commandButton action="{!DisplayNotes}" value="Display Notes" reRender="myPanel"/>
    </apex:form>
    <apex:outputPanel id="myPanel">
    <apex:relatedList subject="{!ac}" list="Notes__r" rendered="{!$ObjectType.Note__c.accessible"/>
    </apex:outputPanel>
 
 
</apex:page>
            

 

public class AccNoteExtension{ 

     public AccNoteExtension(ApexPages.StandardController controller) 
     {
       
         
     }
     public Note__c No{get;set;}
        
    
     String s,str;
     Id myId;
     List <Account> ac;
      
     public List<Account> getAC()
     {
       
     return ac;
     }
    public PageReference DisplayNotes()
     {
       ac = [select id from Account where Name = 'Kevin Test Account'];
       system.debug('AC==========='+ac);
       return null;
     }
}

 

hey,

 

    I am trying to delete contacts (Child records) of an Account, but only when i remove the LastName(Mandatory field) of a contact record.

Actually  i have visualforce page where LastName field of Contact is an input field, if user wants to update he can change the LastName and the record will be Updated...this thing is happening in my code

     BUT trying to delete the records by removing the LastName and leaving it BLANK...Thats not happening.

 

Regards 

Abhi Tripathi

I am Getting the Following Error when Invoking a External Service .

 

How do i check if the External System Is being called atleast .

 

 

This is being Invoked from My Developer Console.

 

 

string ResponseString;
string EmailId= 'adb@xyz.com';
integer lnno= 201345680;
try{
tempuriOrg13.WSHttpBinding_IProdWcfService loan= new tempuriOrg13.WSHttpBinding_IProdWcfService();
System.debug('Inputs to Function'+ln +'siteUrl'+siteUrl);
ResponseString=loan.CallWcfService(lnno,EmailId);
system.debug('Output from outside system '+ResponseString);
}catch(Exception E)
{
    system.debug(E);
}

 

External service class file generated from WSDL

 

//Generated by wsdl2apex

public class tempuriOrg13 {
    public class CallWcfServiceResponse_element {
        public String CallWcfServiceResult;
        private String[] CallWcfServiceResult_type_info = new String[]{'CallWcfServiceResult','http://www.w3.org/2001/XMLSchema','string','0','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://tempuri.org/','true','false'};
        private String[] field_order_type_info = new String[]{'CallWcfServiceResult'};
    }
    public class CallWcfService_element {
        public Integer transactionNo;
        public String email;
        private String[] transactionNo_type_info = new String[]{'transactionNo','http://www.w3.org/2001/XMLSchema','int','0','1','false'};
        private String[] email_type_info = new String[]{'email','http://www.w3.org/2001/XMLSchema','string','0','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://tempuri.org/','true','false'};
        private String[] field_order_type_info = new String[]{'transactionNo','email'};
    }
    public class WSHttpBinding_IProdWcfService {
        public String endpoint_x = 'http://api.*****.com:8081/ProdWcfService.svc';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'http://schemas.microsoft.com/2003/10/Serialization/', 'temporgMicro', 'http://tempuri.org/', 'tempuriOrg13'};
        public String CallWcfService(Integer transactionNo,String email) {
            tempuriOrg13.CallWcfService_element request_x = new tempuriOrg13.CallWcfService_element();
            tempuriOrg13.CallWcfServiceResponse_element response_x;
            request_x.transactionNo = transactionNo;
            request_x.email = email;
            Map<String, tempuriOrg13.CallWcfServiceResponse_element> response_map_x = new Map<String, tempuriOrg13.CallWcfServiceResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'http://tempuri.org/IProdWcfService/CallWcfService',
              'http://tempuri.org/',
              'CallWcfService',
              'http://tempuri.org/',
              'CallWcfServiceResponse',
              'tempuriOrg13.CallWcfServiceResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.CallWcfServiceResult;
        }
    }
}





Error received :

 

21:41:15.278 (278886000)|VARIABLE_SCOPE_BEGIN|[16]|E|Exception|true|false
21:41:15.279 (279018000)|VARIABLE_ASSIGNMENT|[16]|E|"common.apex.runtime.impl.ExecutionException: IO Exception: External server did not return any content"|0x25f92037
21:41:15.279 (279035000)|STATEMENT_EXECUTE|[16]
21:41:15.279 (279040000)|STATEMENT_EXECUTE|[17] 21:41:15.279 (279068000)|SYSTEM_METHOD_ENTRY|[17]|System.debug(ANY) 21:41:15.279 (279102000)|USER_DEBUG|[17]|DEBUG|System.CalloutException: IO Exception: External server did not return any content 21:41:15.279 (279113000)|SYSTEM_METHOD_EXIT|[17]|System.debug(ANY)



I tried the following way but only one contact is getting updated.....

 
   if(trigger.isUpdate)
   {
      list<id> ids=new list<id>();
      for(account ac:trigger.new)
      {
        ids.add(ac.id);
      }
      list<contact> con=new list<contact>();
      list<contact> updtcont=new list<contact>();
      map<id,contact> map1=new map<id,contact>();
      con=[select accountid,MailingStreet,MailingCity,MailingState,MailingCountry from contact where accountid in:ids ];
      
      for(contact cont:con)
      {
         map1.put(cont.accountid,cont);
      }
     for(account ac:trigger.new)
      {
             if(map1.containsKey(ac.id))
       {
                 map1.get(ac.id). MailingStreet=ac.BillingStreet;
                 updtcont.add(map1.get(ac.id));
       }
      }
      try
      {
        if(!updtcont.isEmpty())
       {
       
        update updtcont;
       
        }
      }
     
      catch(Exception e)
   {
      Error_Reporting__c err= new Error_Reporting__c();
      err.Reason__c=e.getMessage();
      err.Record_Id__c=updtcont.get(0).id;
       insert(err);
   
   }

Hi,

 

 I want to represent the time in hh:mm format , i am using the following code below,

 

 if(callReppaMap.get(ac.personContactId)!=null){
                    DateTime dt=System.now();
                    String dtStr=dt.format('HH:mm');
                    paDet.crdate=String.valueof(callReppaMap.get(ac.pe

rsonContactId).Date__c);
                    }else{
                        paDet.crdate='';

                    }

 

but i am getting the date as well as time, please help me with my issue.

 

 

Thanks in Advance

Hi ,
I was trying to solve the trailhead challenge under "Using Static Resources".

Am getting following message:
Challenge not yet complete... here's what's wrong: 
The page does not include a reference to the specified image

Following code am using.
<apex:page >
            <apex:pageBlock title="Pic" >
                    <apex:pageBlockSection >
                         <apex:image value="{!URLfor($Resource.vfimagetest, '/cats/kitten1.jpg')}"/>
                    </apex:pageBlockSection>
             </apex:pageBlock>
</apex:page>
Am I missing something here?

Regards,
Manjunath C Sarashetti
Hi,

I am having a problem to render the apex:EnhancedList .
I have a action function which calls a controller method to set the boolean value to true and rerender that EnhancedList.
It keeps displaying Loading but does not load.

Below is the code.

       <apex:outputPanel id="enhancedActivityList"    >
                <apex:outputPanel >
                    <apex:enhancedList type="Activity" height="600" rendered="{!isEnahanceListEnabled }"  />
                </apex:outputPanel>
           </apex:outputPanel>

I have initalized a varaible in the controller i set it to true when an icon is clicked using the actionfunction and rerender the output panel.

Has anybody faced this issue, any work around to do this.
Thanks in advance.

Regards
Manjunath

Hi,

 

I have a picklist  with values A,B,C and 3 fields F1,F2and F3. If I select A as option then F1 should be required and if B is selected F2 in Visualforce page.

 

Can any help me on this.Thanks in advance.

 

Regards,

 

Hi,

 

Can anyone give information on how many records are returned by single SOQL query in trigger.

 

Regards,

Hi,

 

Is it possible to update a Staticresource record using the apex controller ?

 

Regards,

Hi,

 

As per salesforce's best practice for writing trigger. It suggests to avoid SOQL inside the for loop, but there might be some scenarios where in we need to use SOQL inside. How to Avoid this?

 

Regards,

Hi,

 

How can we implement OAuth for multiple client org and how to add remote access into a package?

 

Regards,

 

Hi,

 

Can we add connected app inside a managed package? Or it is to be treated as separate entities.

 

Regards,

Hi,

 

Does any one know how to add remote access to manage package.

 

Regards,

Hi,

 

In my developer instance, Connected app section is missing. How do I enable it?

 

Regards,

Hi,

 

Does any one know how to add remote access to manage package.

 

Regards,

 

Hi,

 

Anyone knows how to get child elements with namespace.

 

Example :

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <InvokeResponse xmlns="http://tempuri.org/">
      <InvokeResult>Hello world</InvokeResult>
    </InvokeResponse>
  </soap:Body>
</soap:Envelope>

 

I want to get the value of  InvokeResult node.

 

Regards,

 

Hi,

 

Any one has any idea on how to handle http errors in saleforce when using proxy class.

It would be really helpful if any one can give an example.

 

Regards,

 

Hi,

 

I have a string which I am decoding using base64Decode method, then am encoding it back using base64Encode. Then ultimately I should have the initial string, but in certain case its been truncated.

 

Any idea, why is this happening or am I missing here something?

 

Thanks.

Hi,

 

I have a string which I am decoding using base64Decode method, then am encoding it back using base64Encode. Then ultimately I should have the initial string, but in certain case its been truncated.

 

Any idea, why is this happening or am I missing here something?

 

Thanks.

Hi,

 

Is there a possibility where in we can overlap text on image.

 

Regards,

Manjunath

Hi,

 

Can i modify the object permissions of a profile in test class?

 

Regards,

Manjunath

Hi,

 

1.Can I create a virtual user recod and profile in my test class.

 

Regards,

Manjunath

Hi ,
I was trying to solve the trailhead challenge under "Using Static Resources".

Am getting following message:
Challenge not yet complete... here's what's wrong: 
The page does not include a reference to the specified image

Following code am using.
<apex:page >
            <apex:pageBlock title="Pic" >
                    <apex:pageBlockSection >
                         <apex:image value="{!URLfor($Resource.vfimagetest, '/cats/kitten1.jpg')}"/>
                    </apex:pageBlockSection>
             </apex:pageBlock>
</apex:page>
Am I missing something here?

Regards,
Manjunath C Sarashetti
Hi all,

I have been working on this for quite some time and I think that I may have to take a different approach. I am trying to convert a "guest user" (Contact) into a Registered (Customer Community) User based on the current Application that is pulled up in a community for company admins. I am doing this by building an extension on the existing controller for the page where agents can pull the application up.

I added a inputText and button to the page where the agent can enter in an email. This code updates the Contact record fine, as well as creates the associated Account. I want the code to update the Account, not create an entirely different one. This is supposed to be handled by passing methods from the original controller, but I'm running into snags here and there where the User is not being created at all and the Account that is created/updated is not being reflected in the Application record. For instance, where a guest user has filled an application they are assigned to "Guest Account" which is a placeholder of sorts for that person's application. This is also visible on the Application record in the Related_object__c field. When I enter an email in the field on my page, it updates the contact information and adds the Contact to "Firstname Middlename Last Name Account" but doesn't not update the Application's Related_Account__c field. 

I'm also unfamiliar with Page References so I may be going about using them incorrectly. 

I currently get an error "Variable does not exist: updatedCon" when I attempt to pass an SObject variable as parameter (declared and returned from changeGuestUser) method. I think I just need another pair of eyes to get this working as I have it thusfar. 

Thanks! 
 
public Contact changeGuestContact(String searchEmail){
        
       // LoginServices.generateAccountName(fname, mname, lname); *Might Still Use This*
        
       //Query for Head_of_Household information on current app
       //Can not move this out of list. 
       //Error! - SObject constructor must use name=value pairs
       List<FC_Member__c> hohContact = new List<FC_Member__c>([Select Contact__r.ID, Contact__r.FirstName, 
                        Contact__r.MiddleName, 
                        Contact__r.LastName, 
                        Contact__r.Email, 
                        ID, 
                        FC_Application__r.Related_Account__c,                                       
                        FC_Application__r.Confirmation_Number__c, 
                        FC_Application__r.Head_of_Household_Name__c
                                                              
                        
                        FROM FC_Member__C 
                        WHERE FC_Application__r.Confirmation_Number__c = :fcord.confnum LIMIT 1]);

        //Create Contact 
        Contact updatedCon = New Contact();
        updatedCon.ID = hohContact[0].Contact__r.ID;
        updatedCon.FirstName = hohContact[0].Contact__r.FirstName;
        updatedCon.MiddleName = hohContact[0].Contact__r.MiddleName;
        updatedCon.LastName = hohContact[0].Contact__r.LastName;
        updatedCon.email = searchEmail;
        
        //
        String newAcctName = LoginServices.generateAccountName(updatedCon.FirstName, updatedCon.MiddleName, updatedCon.LastName);
         Account updatedAccount = new Account(Name=newAcctName);
        
        update updatedAccount;
        
        updatedCon.AccountId = updatedAccount.ID;
        
        
        system.debug('Contact updated: ' +updatedCon);
        update updatedCon;    
        return updatedCon;

        
    }
    
    public FC_Application__c changeApp(Contact updatedCon) { //Line 171 Variable does not exist: updatedCon --> changeApp(updatedCon); 
        
        //query for the current application by confirmation number *The app that is pulled up in AdminTool*
        List <FC_Application__c>  currentApp = new List<FC_Application__c>([SELECT ID,
                                                                    Related_Account__c,
                                                                    Confirmation_Number__c
                                                                    
                                                                    FROM FC_Application__c
                                                                    WHERE Confirmation_Number__c =:fcord.confnum LIMIT 1]); 
     
        FC_Application__c updateApp = new FC_Application__c();
        updateApp.ID = currentApp[0].ID;
        updateApp.Related_Account__c = updatedCon.AccountId;

        
        update updateApp;
        system.debug('Account: ' +updateApp.Related_Account__c);
        
        //Need to set the AccountID/Name from the updatedCon variable to the Related_Account__c variable on the current
        //Application.
         //updatedAccount.Application__c = currentApp[0].ID;
         
         
        
        return updateApp;
    }   
    
    
        public Account changeGuestAccount(Contact updatedCon){
        
        //String newAcctName = LoginServices.generateAccountName(updatedCon.FirstName, updatedCon.MiddleName, updatedCon.LastName);
         //Account updatedAccount = new Account(Name=newAcctName);
        
        //upsert updatedAccount;    
        return null;
        
    }
    
    //Calls LoginServices.createNewApplicant to 'self-register' the Guest into a Customer User
    public Boolean createSuccessful(Contact updatedCon){
        try{
        changeGuestContact(searchEmail);
        LoginServices.createNewApplicant(updatedCon.email, updatedCon.firstname, updatedCon.middlename, updatedCon.lastname);
        system.debug('User created?: ');
        }
        catch (exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Contact not updated'));
            return false;
        }
        return true;
    }
    
    
    
    
    

    
    public PageReference checkEmail(){
        try{
            //setSearchEmail('jdough@test.com');
            //changeGuestContact(searchEmail);
            //changeGuestAccount();
            createSuccessful(updatedCon); //Variable does not exist: updatedCon
            //changeApp(updatedCon); //variable does not exist: updatedCon
            return null;
        } 
        catch (exception e){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Contact not updated'));
         
        }
        return null;
    }





 
Hi,

I am pretty new to SalesForce coding and hoping you can help.

I am getting the following error: Error:Apex trigger CreateCompetitor caused an unexpected exception, contact your administrator: CreateCompetitor: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.CreateCompetitor: line 5, column 1. 

My research seems to be telling me that it is throwing an error when the field I am referencing is blank. Sometimes this field will need to be blank and I don't want to run the trigger in that case, can someone please help?

Below is my code (which will eventually need to be built out some more to include more competitors)

trigger CreateCompetitor on Opportunity (after insert, after update) {
 for(Opportunity o: trigger.new){ 
    String opptyId = o.Id;
    Opportunity oldOpp = Trigger.oldMap.get(o.Id);
    if(o.Competitors__c.contains('Competitor 1') && !oldOpp.Competitors__c.contains('Competitor 1')){
    Competitor__c[] OLI = [Select Id, Name  
                           From Competitor__c
                           where Name = 'Competitor 1'];
      Link_Competitor_with_an_Opportunity__c[] ast = new Link_Competitor_with_an_Opportunity__c[]{};
         Link_Competitor_with_an_Opportunity__c m = new Link_Competitor_with_an_Opportunity__c();
                  for(Competitor__c ol: OLI){
            m = new Link_Competitor_with_an_Opportunity__c();    
            m.Opportunity__c = o.Id;
            m.Competitor__c = ol.Id;
            ast.add(m);
            update OLI;
            insert ast;
    if(o.Competitors__c.contains('Competitor 2') && !oldOpp.Competitors__c.contains('Competitor 2')){
    Competitor__c[] OLI2 = [Select Id, Name  
                           From Competitor__c
                           where Name = 'Competitor 2'];
      Link_Competitor_with_an_Opportunity__c[] ast2 = new Link_Competitor_with_an_Opportunity__c[]{};
         Link_Competitor_with_an_Opportunity__c m2 = new Link_Competitor_with_an_Opportunity__c();
                  for(Competitor__c ol2: OLI2){
            m2 = new Link_Competitor_with_an_Opportunity__c();    
            m2.Opportunity__c = o.Id;
            m2.Competitor__c = ol2.Id;
            ast2.add(m2);
            update OLI;
            insert ast2;
            }}}}}}

Thanks in advance!
Hi ,
I was trying to solve the trailhead challenge under "Using Static Resources".

Am getting following message:
Challenge not yet complete... here's what's wrong: 
The page does not include a reference to the specified image

Following code am using.
<apex:page >
            <apex:pageBlock title="Pic" >
                    <apex:pageBlockSection >
                         <apex:image value="{!URLfor($Resource.vfimagetest, '/cats/kitten1.jpg')}"/>
                    </apex:pageBlockSection>
             </apex:pageBlock>
</apex:page>
Am I missing something here?

Regards,
Manjunath C Sarashetti
This is the scenario , filter records based on a picklist or a lookup field in visual force page where I am looking for solution.

There is an object objA, it has 4 lookup fields.
Lookup Field1 (LF1) - This field is lookup to ObjB
Lookup Field2 (LF2) - This field is lookup to ObjC
Lookup Field3 (LF3) - This field is lookup to ObjD
Lookup Field4 (LF4) - This field is lookup to ObjE

in the visual force page, all the above lookup fields are dependent on one another. Once LF1 is entered, then LF2 is dependent on LF1 value, LF3 is dependent on LF2 value and LF4 value is dependent on LF3 value

Can someone help me in writing visual force page and apex controller for this scenario
  • March 05, 2015
  • Like
  • 0

Hi,

I want to get the Account.Name from the Account object from the Contact (before insert) Trigger. 

1. I fill Contact details
2. I select the Account

Then I fire my trigger. My trigger is for Contact object. 

I have the Contact object details

Contact[] cont = Trigger.new;

 

I tired to access the Account.Name related to this Contact by

cont.Account.Name
But it returns NULL.

Please Help me.

Thanks in advance
Hi, I have the following code and I can get the E-sig to work in preview.  My issues is adjusting this code to work so I can add VF page via page layout on a Case record.  It current is not showing on my available VF pages to add via page layout editor.
It's a controller issue, need to make this custom controller work with the Standard Case controller, so I can see and add (I think).

Thanks,  Paul

Visualforce Page

<apex:page docType="html-5.0" controller="CapturePSignatureController" showheader="false" sidebar="false" standardStylesheets="false" id="pg">
 <apex:includeScript value="/soap/ajax/28.0/connection.js"/>
 
 <style>
  .container {
   text-align: center;
   font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
   color: cadetblue;
   font-weight: 500;
   font-size: 14px;
  }
  
  .button {
   font-family: calibri;
   border-radius: 8px;
   background-color: rgb(51, 116, 116);
   height: 36px;
   color: azure;
   font-size: 17px;
   border-width: 0px;
   width: 116px;
  }
 </style>
 <apex:form id="pbform">
  <apex:pageMessages />
  <div class="container">
   <h1 class="labelCol vfLabelColTextWrap ">Record Patient Signature:</h1>
   <canvas id="PsignatureCanvas" height="100px" width="350px" style="border: 3px solid antiquewhite; border-radius: 8px;" ></canvas>
  </div><br/>
  
  <div style="margin-left: 41%;">
   <apex:commandButton value="Save Patient Signature" onclick="savePSignature();return false;" styleClass="button"/>&nbsp;&nbsp;&nbsp;
   <apex:commandButton value="Clear" onclick="clearSign();return false;" styleClass="button"/>
  </div>
 </apex:form>

  <script>
  var canvas;
  var context;
  var drawingUtil;
  var isDrawing = false;
  var accountId = '';
  var prevX, prevY, currX, currY = 0;
  var accountId;

   function DrawingUtil() {
   isDrawing = false;
   canvas.addEventListener("mousedown", start, false);
   canvas.addEventListener("mousemove", draw, false);
   canvas.addEventListener("mouseup", stop, false);
   canvas.addEventListener("mouseout", stop, false);
   canvas.addEventListener("touchstart", start, false);
   canvas.addEventListener("touchmove", draw, false);
   canvas.addEventListener("touchend", stop, false);
   w = canvas.width;
      h = canvas.height;
  }

   function start(event) {
   event.preventDefault();
   
   isDrawing = true;
   prevX = currX;
   prevX = currY;
   currX = event.clientX - canvas.offsetLeft;
   currY = event.clientY - canvas.offsetTop;
   
   context.beginPath();
   context.fillStyle = "cadetblue";
   context.fillRect(currX, currY, 2, 2);
            context.closePath();
   
  }

   function draw(event) {
   event.preventDefault();
   if (isDrawing) {
    prevX = currX;
             prevY = currY;
             currX = event.clientX - canvas.offsetLeft;
             currY = event.clientY - canvas.offsetTop;
    context.beginPath();
    context.moveTo(prevX, prevY);
    context.lineTo(currX, currY);
    context.strokeStyle = "cadetblue";
    context.lineWidth = "2";
    context.stroke();
    context.closePath();
   }
  }

   function stop(event) {
   if (isDrawing) {
    context.stroke();
    context.closePath();
    isDrawing = false;
   }
  }
  
  function clearSign() {
   context.clearRect(0,0,w,h);
  }

   canvas = document.getElementById("PsignatureCanvas");
  context = canvas.getContext("2d");
  context.strokeStyle = "black";
  context.lineWidth = "2";
  drawingUtil = new DrawingUtil(canvas);
  

   function savePSignature() {
   var strDataURI = canvas.toDataURL();
   strDataURI = strDataURI.replace(/^data:image\/(png|jpg);base64,/, "");
   var accId = location.href.split('=')[1];
   accountId = accId;
   var result = CapturePSignatureController.savePSignature(strDataURI, accId, processResult);
  }

   function processResult(result) {
   alert(JSON.stringify(result));
   window.location.href = '/'+accountId;
  }

  </script>


</apex:page> 

Controller

global with sharing class CapturePSignatureController {
 
 @RemoteAction
 global static String savePSignature(String imageUrl, String accountId) {
  
  try {
   Attachment accSign = new Attachment();
   accSign.ParentID = accountId;
   accSign.Body = EncodingUtil.base64Decode(imageUrl);
   accSign.contentType = 'image/png';
   accSign.Name = 'Patient Signature Image';
   accSign.OwnerId = UserInfo.getUserId();
   insert accSign;
   
   return 'success';
   
  }catch(Exception e){
   system.debug('---------- ' + e.getMessage());
   return JSON.serialize(e.getMessage());
  }
  return null; 
 }

}
 
here is my code (i just dont want to give hard code id ) . plz guide me
----------------------------------------
<apex:page standardController="contact" extensions="pg">
 <apex:form >
<apex:inputField value="{!contact.accountid}"/>

 </apex:form>
 <apex:form >
 <apex:pageBlock title="contact details">
  <apex:pageBlockSection columns="2">
  <apex:pageBlockTable value="{!cont}" var="co">
  <apex:column value="{!co.lastname}"/>
    <apex:column value="{!co.phone}"/>
      <apex:column value="{!co.email}"/>
  </apex:pageBlockTable>
  </apex:pageBlockSection>
  </apex:pageBlock>
  <apex:pageBlock title="oppty details">
  <apex:pageBlockSection >
  <apex:pageBlockTable value="{!oppty}" var="op">
  <apex:column value="{!op.name}"/>
    <apex:column value="{!op.Amount}"/>
  </apex:pageBlockTable>
  </apex:pageBlockSection>
  </apex:pageBlock>
 </apex:form>
</apex:page>
--------------------
public class pg {

    public pg(ApexPages.StandardController controller) {
     cont=[select id, firstname, lastname , email,phone from contact where accountid =:'cont.accountid']; 
      oppty=[select name, amount from opportunity where accountid='0019000001CuKu3'];
    

    }


    

    public list<contact> cont { get; set; }
        public list<opportunity> oppty{ get; set; }
    
   public pg()
    {
     
    
    }
}
  • January 22, 2015
  • Like
  • 0
Hi all,

In our customer portal we have users created through "Enable Customer Users" option in contact. While saving user unfortunately I am getting an exception from our trigger that contact Id is null. I am facing this issue while creating user through contact. I guess something went wrong in latest release?

Any suggestions please?
  • January 14, 2015
  • Like
  • 0
hi all,

i have a controller where in am getting this error displayed on my VF page.
Below is my code
public String distributionIds;
    
  public List<Distribution_List_Item__c> distItemLst{get;set;}
    
    //CONSTRUCTOR
    public VistAudit_VFC()
    {
        visitId=ApexPages.currentPage().getParameters().get('id');
        relatedAccountId=ApexPages.currentPage().getParameters().get('accid');
        distItemLst=new List<Distribution_List_Item__c>();
        distributionIds='';
    }
    
    //Constructs the data displayed on the page for all sections
    public void createData()
    {
     distributionIds=[select Id from Distribution_List__c where Business_Partner__c=:relatedAccountId 
                      AND Start_Date__c < today AND End_Date__c > today AND Status__c='Active'].Id;

     distItemLst=[select id from Distribution_List_Item__c where Distribution_List__c =:distributionIds];
}

in the above code,actually no record exisits in database to return the rows.But because of this error it discards the further execution of the code.
So can anyone please suggest how do i get rid of this error when there are no records present in database?

Thanks
Hi ,
I am running a batch to update a field - Below is the code 


global class MassDeleteRecords implements  Database.Batchable<sObject> {
global final string query;
public String query1;

global MassDeleteRecords (String q)
{
   query1 = q;
   system.debug(query1);
   query  = 'Select Id,Description__c from Account where Round_Robin_ID__c =:query1';
   system.debug(query);
}

global Database.QueryLocator start(Database.BatchableContext BC){

   return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Account> scope){
  List<Account> lsttoupdate = new List<Account>();
  for(Account s : scope){
     s.Description__c = 'Updated in Batch Apex';
     lsttoupdate.add(s);
     }
     update lsttoupdate;
    }
global void finish(Database.BatchableContext BC){
 
}
}

From Developer console I am running the below code - 

String q = '1';
MassDeleteRecords b = new MassDeleteRecords(q);
Database.executeBatch(b);

But i see no records has been updated. Can anybody help..
Hi I am getting Constructor not defined: [MassDeleteRecords].<Constructor>(Integer) error while running the apex class from developer console. Please help . 

Below is my code - 


global class MassDeleteRecords implements  Database.Batchable<sObject> {
global final string query;

global MassDeleteRecords (String q)
{
   String query1 = q;
   query  = 'Select Id from Account where Round_Robin_ID__c =\'' + query1 + '\'';
}

global Database.QueryLocator start(Database.BatchableContext BC){

   return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Account> scope){
  List<Account> lsttoupdate = new List<Account>();
  for(Account s : scope){
     s.Description__c = 'Updated in Batch Apex';
     lsttoupdate.add(s);
     }
     update lsttoupdate;
    }
global void finish(Database.BatchableContext BC){
 
}
}

Developer console - I am running = 
MassDeleteRecords b = new MassDeleteRecords(1);
Database.executeBatch(b); 

Regards
Hi,

I am get error like: 
System.NullPointerException: Attempt to de-reference a null object
Class.SearchListController.getSObjectList: line 19, column 1     

public class SearchListController{
 
    public String objectName {get;set;}
    public List<String> objectFields {get;set;}
    public List<SObject> SObjectListToShow {get;set;}
    public SearchListController(){
        //objectName= 'MyObject__c';
        objectName= '';
        SObjectListToShow =new List<SObject>();
       // SObjectListToShow = getSObjectList();
    }
    
    public List<SObject> getSObjectList(){
    
    //Getting field list for the sObject 
        objectFields =  new List<String>();
        Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
        Schema.sObjectType sObjType = globalDescription.get(objectName);
        Schema.DescribeSObjectResult res = sObjType.getDescribe();  // In this line, iam getting error
 
         Map<String , Schema.SObjectField> mapFieldList = res.fields.getMap();
        for(Schema.SObjectField field : mapFieldList.values())
        {
            Schema.DescribeFieldResult fieldResult = field.getDescribe();
            if(fieldResult.isAccessible())
            {
                objectFields.add(fieldResult.getName());
            }
        }
 
        //Building Query with the fields
        Integer i = 0;
        String fieldsToFetch = '';
        Integer len = objectFields.size();
        for(String temp:objectFields)
        {
 
            if(i==len-1)
            {
                  fieldsToFetch = fieldsToFetch + temp;
            }
            else
            {
                  fieldsToFetch = fieldsToFetch + temp + ',';
            }
            i++;
        }
            String qryStr = 'Select ' + fieldsToFetch + ' From ' + objectName  ;
            return  Database.Query(qryStr);
    }
}

Please help sove this problem.

Regards,
Shaik
  • December 11, 2014
  • Like
  • 0
Snap shot for code Coverage
_____________This is the Class where i am facing problem------------------------------
public class SaveMultiObj {


    public humanresource__c hr{get;set;}
      public CandidateHr__c cand{get;set;}
      public AdminService__c admin{get;set;}
        
        public SaveMultiObj(){
        hr=new humanresource__c();
        cand=new CandidateHr__c();
        admin=new AdminService__c ();
        }
    public void custsave(){
     
      insert hr;
     cand.HumanResource__c=hr.id;
     cand.rank__c=hr.rank__c;
     cand.last_name__c=hr.last_name__c;
      insert cand;   
     }
    public void custUpdate() {
      CandidateHr__c cand1 =[select id,last_name__c,rank__c,name from candidatehr__c where name=:cand.name];
       cand1.last_name__c=hr.last_name__c;
       cand1.rank__c=hr.rank__c;
       update cand1;
      
     admin.CandidateHr__c=cand1.id;
     admin.rank__c=cand1.rank__c;
     admin.last_name__c=cand1.last_name__c;
      insert admin;         
    }   
   }
-------------------------This is Test Class which is related to above Class ---which able to cover only 68%--------
@isTest
public class SaveMultiObj_TC
{
    static testMethod void testMthd()
    {
        SaveMultiObj s=new SaveMultiObj ();
        s.custsave();
        s.custUpdate();
        s.hr=new humanresource__c (name='xxx');
        s.cand=new CandidateHr__c (name='yyy');  
        insert s.cand;
        s.cand.name='yyo';   
        update s.cand;
        s.admin=new AdminService__c (name='uuu');
        insert s.admin;
    }
}
This is the snap shot for below issue
----------------This is the Controller Class Where i am facing Problem.---------------------
public class RerenderEx {

    public contact con{set;get;}
    public boolean Abool{set;get;}
    public boolean Bbool{set;get;}    

    public RerenderEx()
    {
        con=new contact();
        Abool=false;
        Bbool=false;
    }
    public void saveNew() {
        insert con;
        con.clear();//con=new contact();
    }

    public void saveSec() {
        insert con;
        Abool=true;
    }
    
    public void EditSec() {
        Abool=false;
        Bbool=true;
    }
    
     public void updateSec() {
        update con;
    }

}
------------------------------This is the Test Class which is unable to Cover above Class .Its covering only 50%----------
@isTest
public class RerenderEx_TC
{
    static testMethod void testMthd()
    {
     boolean Abool=false;
     boolean Bbool=false;    
    RerenderEx r=new RerenderEx();
     contact con=new contact(lastname='xxx');
    r.saveNew();
     insert con;
     con.lastname='xyy';
     update con;
      r.saveSec();
     r.EditSec();
     r.updateSec();
     }
}
 
I've had some trouble with SOSL in escaping wildcard characters (* and ?).  From the SOSL documentation (http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_sosl_find.htm), it seems like * should be escaped with \* or possibly \\* or even \\\\*, but none of those seem to work.

These are the results I saw:
[FIND 'pre*post' IN ALL FIELDS RETURNING Lead(Id, Name)];  // works as a wildcard
[FIND 'pre\*post' IN ALL FIELDS RETURNING Lead(Id, Name)];  // error: Invalid string literal 'pre\*post'. Illegal character sequence '\*' in string literal.
[FIND 'pre\\*post' IN ALL FIELDS RETURNING Lead(Id, Name)];  // error: Invalid string literal 'pre\*post'. Illegal character sequence '\*' in string literal.
[FIND 'pre\\\\*post' IN ALL FIELDS RETURNING Lead(Id, Name)]; // seems to function as wildcard same as no backslash

Similar behavior is observed with ? instead of *.

Any help?  Thanks in advance!
Hi.

In the VF I used the date format as YYYY-MM-dd in the 
<apex:outputText value="{0,date,YYYY/MM/dd}">
Before the last week of the year it was OK. When the new year falls in the  last week of Decemeber comes the issue.
For example
2014:
S   M  T  W Th F Sat
28 29 30 31 1   2 3

In the above calendar 1st Jan of 2015 falls in the Thurusday.So when I viewd the records of 28,29,30 of December 2014 It showed as
2015-12-28
2015-12-29
2015-12-30
2015-12-31

After that I came to know that
@"YYYY" is week-based calendar year.
@"yyyy" is ordinary calendar year.
http://realmacsoftware.com/blog/working-with-date-and-time

cheers
suresh