Using Wrapper class for displaying records from two objects in a single table

Sometimes we need to display data from different objects (not related to each other) in a table. Best way to do that is using wrapper class. I am showing you an example where i am displaying records from contact and account object ( i am not using their r/ship, so it could be any two object)

Page:
<apex:page controller="Deleteme7_controller" >
<apex:pageBlock >
    <apex:pageblocktable value="{!final}" var="a">
            <apex:column value="{!a.acc.name}" /> 
            <apex:column value="{!a.con.name}"/>
            </apex:pageblockTable>
     </apex:pageBlock>
</apex:page>

Controller:

public with sharing class Deleteme7_controller {
List final3 = new list();
wrapclass wrapobject;
public Deleteme7_controller (){
list a= [select id,name from account];
list c = [select name,id from contact];
add(a,c);
}

public list getFinal(){
return final3;
}

public void add(list a,list b){
integer j=0;

public class wrapclass{
public account acc{get;set;}
public contact con{get;set;}

}
}

Button to activate/deactivate a task on a object

Sometimes we feel like to create a button/checkbox to activate/deactivate a task on that respective object. There are two ways to do that
1) Workflows (Easier, but has limits)
2) Trigger
I am sharing the code with you for creating a checkbox. If set to true, create a task for reminding after 30 days, if deactivated, delete the task.

for (Contact c :trigger.new){

  contact oldc = trigger.oldmap.get(c.id);

  if(c.Activate__c==true && oldc.Activate__c==false){

    task t = new task();

    t.subject = 'Reminder about calling Contact';

    t.whoid = c.id;

    t.isreminderset = true;

    t.reminderdatetime = system.today()+30;

    t.status = 'In Progress';

    t.IsRecurrence = false;

    insert t;}


  else if(c.Activate__c==false && oldc.Activate__c==true){

   List<task> t = [select id from task t where t.whoid=:c.id and t.subject='Reminder about calling Contact'];

   delete t;

  }} }

Date with inputtext

We can now use a standard datepicker with <apex:inputtext> also. you can use the code Make sure you have id attribute given some value in inputtext

Controlling Recursive Triggers

Sometimes we need to update the record of same object, which is intializing the trigger. This will cause recursive trigger and throws an exception. Exception could be "SELF_REFERENCE_FROM_TRIGGER"
For example, suppose you have self look up to contact named spouse. You have two contact, A and B. when you select A as spouse of B, you want to also update A as spouse of B. In trigger for A, when you update B, it will call recursive trigger.
To control/prevent such condition, we need to add a static variable in another class, as this variable will share single instance, as these transaction has occured from a single event. This static variable allows the code to execute in first run. but prevent from any run thereafter.



code for static var:


public class flag {
public static boolean firstrun = true;
}

code for trigger:


trigger MatchSpouse on Contact (after insert, before update) {
List spouses = new List();
Contact spouse;
for (Contact c : Trigger.new){
if (c.Spouse__c != null){
spouse = new contact(id = c.spouse__c);
if(spouse.Spouse__c != c.id)
{
spouse.Spouse__c = c.id;
spouses.add(spouse);
}}}
if(spouses.size()>0 && flag.firstrun ){
flag.firstrun = false;
update spouses;

}}

Creating dependant pickist in visualforce from custom settings

Creating dependant pickist in visualforce from custom settings

Hi,
Today, i got a requirement for creating a dependant picklist which gets its values from custom setting. I thought of sharing it with you all.

In my example, i am selecting name of countries and its associated city from custom settings.

Steps :
1) Create a new list type custom setting, with only one text field named 'City' in my case.
2) Click on manage in the custom setting, and create a new record.
Name of the custom setting record should be name of the country.
City field contains name of the cities for that country, separated by ';'



3) Code for page :



<apex:page controller="CustomSettings_controller" >
<apex:pageBlock >
<apex:form >
<apex:actionFunction name="rerenderStates" rerender="ListState" >
<apex:param name="firstParam" assignTo="{!country}" value="" />
</apex:actionFunction>

<apex:pageblocksection >
Country <apex:selectList id="ListCountry" value="{!country}" size="1" onchange="rerenderStates(this.value)">
<apex:selectOptions value="{!countrylist}"></apex:selectOptions>
</apex:selectList>
</apex:pageblocksection>

<apex:pageblocksection >
State <apex:selectList id="ListState" value="{!states}" size="1">
<apex:selectOptions value="{!statelist}"></apex:selectOptions>
</apex:selectList>
</apex:pageblocksection>

</apex:form>
</apex:pageBlock>
</apex:page>

4) code for controller :




public class CustomSettings_controller {


Map<String, countrystate__c> c = countrystate__c.getall();


public list<selectoption> getStateList() {
list<selectoption> s = new list<selectoption> ();
s.add(new selectoption('','Select one'));
if(country==null){
country='';
}
else
if(c.containskey(country)){
s.clear();
string sm = c.get(country).States__c;
for(string st: sm.split(';'))
s.add(new selectoption(st,st));
}

return s;
}


public List<SelectOption> getCountrylist() {
List<SelectOption> country = new List<SelectOption>();
country.add(new selectoption('India','---SELECT ONE---'));
list<string> countryname= new list<string>();
countryname.addall(c.keyset());

for(string s : countryname){
country.add(new selectoption(s,s));

}

return country;
}


public String states { get; set; }

public String country{ get; set;}

}


Final Outcome :



Test a controller in salesforce

Some developers have become frustrated when trying to write unit tests for their Controllers To be fair, if you don’t know what base you assertions on, it can be hard to test the code. So here are a couple of quick tips for getting it done:
suppose you have a controller like this


public with sharing class TestingVFController_Controller {

private string qp;

public TestingVFController_Controller(){
this.qp=ApexPages.currentPage().getParameters().get('qp');
}

public string FirstName {
get;set;}

public string LastName {
get;set;
}
public string email {
get;set;
}
public string Company {
get;set;
}

public PageReference save(){
PageReference p=null;
if(this.qp==null || !'yyyy'.equals(this.qp)){
p=Page.filenotfound;
p.getParameters().put('error','NoParam');

}
else{
try{
Lead l = new Lead(Firstname=this.firstName,LastName=this.LastName,company=this.Company, email=this.email);
insert l;
}
catch(Exception e)
{
p=Page.filenotfound;
p.getParameters().put('error','insertFailure');
}

}
if(p==null)
p=Page.homepage;

p.setRedirect(true);
return p;
}
}

Solution for "INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session"


System.out.println("LOGGING IN NOW....");
enterpriseConnection connection = new enterpriseConnection();
loginResult = connection.login(userName, Password);
System.out.println("Succesfully logged IN");
connection._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY, loginResult.getServerUrl());
SessionHeader sessionHdr = new SessionHeader();
sessionHdr.setSessionId(loginResult.getSessionId());
connection.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(),"SessionHeader", sessionHdr);

resolution for "the url returned from login must be set in the sforceservice "


EnterpriseConnection connection = new enterpriseConnection();
loginResult = connection.login(userName, Password);
System.out.println("Succesfully logged IN");
connection._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY,loginResult.getServerUrl());
SessionHeader sessionHdr = new SessionHeader();
sessionHdr.setSessionId(loginResult.getSessionId());
connection.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(),"SessionHeader", sessionHdr);