[SalesForce] Call pagereference method from Trigger
Can I call pagereference method from trigger.
I tried to call but I got nullPointerException.
Best Answer
You shouldn't really do this. In this post you can find some explanations why. But basically trigger runs behind the scene so users can't see it and be redirected from there.
All you need to do is change your current code to use the List<Category__c>> (i.e. Trigger.new) that you've passed into your method rather than referencing Trigger.new directly (which you can do, but then your class won't work outside of a trigger context).
I've also renamed a couple of your variables and formatted your code to make it easier to see what is going on:
public with sharing class CategoryHelper
{
public static void ValidateCategories(LIST<Category__c> newRecords)
{
List<Category__c> existingRecords = [select id, Type__c from Category__c where Type__c != null];
for(Category__c c : newRecords)
{
if(c.Type__c != null)
{
for(Category__c existrecord : existingRecords)
{
if(existrecord.Type_of_Risk__c == c.Type_of_Risk__c
|| existrecord.Type__c == 'Cost'
&& c.Type__c == '%Cost'
|| existrecord.Type__c == 'Time'
&& c.Type__c == '%Time'
|| existrecord.Type__c == '%Cost'
&& c.Type__c == 'Cost'||
existrecord.Type__c == '%Time'
&& c.Type__c == 'Time')
{
c.Type__c.adderror('Type is already used please select another one.');
}
}
}
}
}
}
I'm not sure where you're going with this because the code you posted is pretty vague. Maybe you could make this a static method if you are only calling the PageReference exactly after you're instantiating the object. Here's a way to expedite the call of an instance method. This one goes to a new opportunity.
public class A
{
public PageReference save()
{
return (new B()).pay();
}
}
public class B
{
public PageReference pay()
{
PageReference pageRef = new PageReference('/006/e');
pageRef.setRedirect(true);
return pageRef;
}
}
Best Answer
You shouldn't really do this. In this post you can find some explanations why. But basically trigger runs behind the scene so users can't see it and be redirected from there.