You obviously have a few different execution paths:
- Your
Id
value is null - Your
Id
value is populated and theupdate
call succeeds - Your
Id
value is populated and theupdate
call fails
Note how my pseudocode test above calls the class instance extension
, not controller
. Please take a moment to read What is the Difference Between Controllers and Extensions? and understand what sort of class definition you are writing. There are a couple other things you could improve about your class, specifically you should use the controller.getId
method rather than the case-sensitive getParameters()
approach.
public with sharing class MyExtension
{
final Id recordId;
final Contract record;
public MyExtension(ApexPages.StandardController controller)
{
// you are accepting a controller as a parameter
// this class is actually an EXTENSION
recordId = controller.getId();
record = (Contract)controller.getRecord();
}
public PageReference myMethod()
{
if (recordId == null)
{
// you should really add an error message to the page here
return null;
}
// query related record and set some fields
try
{
update relatedRecord;
}
catch (DmlException dmx)
{
// you will greatly improve the user experience
// if you add some basic error handling
ApexPages.addMessages(dmx);
return null;
}
return somePageReference;
}
}
One final note, it is much better practice to construct the view using the StandardController
. The end of your method should simply read:
return new ApexPages.StandardController(relatedRecord).view();
You also don't need to call setRedirect(true)
since that is the default value.