3

I am trying to populate a field in a Visualforce page for custom object using a controller extension.

I would like to populate the field with one value if the User Role of the person creating the record is Sales and another value if they are Account Management. I'm not quite sure of the syntax I need to use to accomplish this in my controller.

Can anyone assist?

public class VF_CampaignCaseCreateController{
public List<Campaign_Create_Request__c> CCR {get; set;}

    private final Opportunity opp;
    public VF_CampaignCaseCreateController(ApexPages.StandardController myController){
        CCR = new List<Campaign_Create_Request__c>();
        if (!Test.isRunningTest())
        {
            myController.addFields(new List<String>{'Id', 'OwnerId'});
        }
        opp=(Opportunity)myController.getrecord();
    }

    public Campaign_Create_Request__c CCR2 = new Campaign_Create_Request__c();

    public void CampaignCaseCreate(){

        CCR2.Opportunity__c = opp.Id;

    String roleId = UserInfo.getUserRoleId();
        UserRole usrRole = [SELECT Name, Id 
                            FROM UserRole 
                            WHERE Id = :roleId LIMIT 1];
        String userRoleName = usrRole.Name;

        IF(usrRole.Name.startsWith('Senior')){
            CCR2.Sales_Rep__c = UserInfo.getUserId();
        }
        ELSE{
            CCR2.Sales_Rep__c = null;
        }

        Opportunity o = [SELECT (SELECT Id, contactId
                               FROM OpportunityContactRoles
                               WHERE role = 'Signatory')
                        FROM Opportunity
                        WHERE id = :opp.id];
        CCR2.Primary_User__c = o.opportunityContactRoles.size() != 0 
            ? o.opportunityContactRoles[0].contactId  
            : null;

        CCR.add(CCR2);
    }
}
3

You can use the Userinfo object to get what you need:

String roleId = UserInfo.getUserRoleId();
UserRole usrRole = [SELECT Name, Id 
                    FROM UserRole 
                    WHERE Id = :roleId LIMIT 1];
String userRoleName = usrRole.Name;

Then you can use these values in the code as you like.

Note, there is no error checking in this example - you will need to add that.

  • Thanks Caspar, that helped a lot!! I updated my code above with the correction you suggested. – J. Neilan Jan 12 '16 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.