0

I am trying to redirect to the object New action. however it works fine for standard object, but not for custom object. if I use "{!URLFOR($Action.Account.New)}", then it works perfectly fine.

I am trying to override the Custom object New button with the below VF page.

<apex:page standardController="Apprenticeship__c" >
   <script type="text/javascript">      
           var profile = '{!$Profile.Name}'; 

           if(profile == 'System Administrator'){               
               redirectTo('{!URLFOR($Action.Apprenticeship__c.New)}');           
               }           
           function redirectTo(target) {
              window.location.href = target;
            }
   </script>
   <apex:pageMessages/>
</apex:page>

Error: Screen is just flickering nothing is happening.

0

2 Answers 2

2

You need to use the "override" option if you're redirecting to an overridden page, otherwise you'll just get an infinite loop (provide "true" as the fourth parameter to URLFOR). As a matter of principle, you don't need any JavaScript, either:

<apex:page standardController="CustomObject__c"
    action="{!IF($Profile.Name<>'System Administrator', null, URLFOR($Action.CustomObject__c.New, null, null, true))}">
    <apex:pageMessage severity="error" summary="You cannot do this" detail="You are not allowed to use this feature" />
</apex:page>
3
  • I was trying that but couldn't quite hit on the right parameters for URLFOR. Probably a little easier from a readability perspective to invert the Boolean so null comes first. I think the <apex:pageMessages/> tag is also unnecessary here. Answer might also be improved by naming that fourth parameter. :)
    – Adrian Larson
    Nov 1, 2017 at 19:49
  • @AdrianLarson Not a bad suggestion. I'll do that.
    – sfdcfox
    Nov 1, 2017 at 19:50
  • @sfdcfox: Perfect solution. clean and crisp. no Javascript:)
    – Ajay
    Nov 2, 2017 at 14:49
3

I recommend you use the action attribute here and specify nooverride=1. I would use an Apex extension so that it can be unit tested. Something like the below.

Page

<apex:page standardController="MyObject__c" extensions="Demo" action="{!redirect}">
    <apex:pageMessage severity="FATAL" summary="No access" />
</apex:page>

Extension

public with sharing class Demo
{
    public Demo(ApexPages.StandardController controller) { }
    public PageReference redirect()
    {
        Profile runningProfile = [
            SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()
        ];
        if (runningProfile.Name != 'System Administrator') return null;

        String prefix = SObjectType.MyObject__c.getKeyPrefix();
        return new PageReference('/' + prefix + '/e?nooverride=1');
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .