Monday, March 23, 2015

Useful Visualforce Actions for any object

You may have come across a case where you need to create custom links in a Visualforce page to create, view edit any object or a link to open a object list page. Also, When you click on Cancel button from Create, View or edit pages it will automatically taken you back to the Originated page.

Here are the quick snippets for the same.

Create an Object: 

You can replace Contact with any other object.

<!-- Create New Contact Action -->
<apex:outputLink value="{!URLFOR($Action.Contact.NewContact)}">
Create a New Contact
</apex:outputLink>

<!-- Create New Contact Action -->
<apex:outputLink value="{!URLFOR($Action.CustomObject__c.NewCustomObject__c)}">
Create a New Custom Object
</apex:outputLink>

View an Object: 

<apex:outputLink value="{!URLFOR($Action.Contact.View, '003G0000016qPH5')}">
    Contact1
</apex:outputLink>

<apex:outputLink value="{!URLFOR($Action.CustomObject__c.View, 'a00900000016iUl')}">
CustomObject__c Record
</apex:outputLink>

Edit an Object: 

<apex:outputLink value="{!URLFOR($Action.Contact.Edit, '003G0000016qPH5')}">
    Edit Contact1
</apex:outputLink>

<apex:outputLink value="{!URLFOR($Action.CustomObject__c.Edit, 'a00900000016iUl')}">
CustomObject__c Record
</apex:outputLink>

Go to Object List Page: 

<!-- For Standard Object like Contact -->
<apex:outputLink value="{!URLFOR($Action.Contact.List,  $ObjectType.Contact)}">
Contact List
</apex:outputLink>

<!-- For Custom Object -->
<apex:outputLink value="{!URLFOR($Action.CustomObject__c.List,  $ObjectType.CustomObject__c)}">
CustomObject__c List
</apex:outputLink>

Friday, March 20, 2015

Creating an sObject Dynamically by passing an object type


The one liner code to create any type of sObject Dynamically - Replace/pass ObjectType:

sObject sObj = Schema.getGlobalDescribe().get(ObjectType).newSObject() ;
More formal implementation:

public class UndefinedSObjectTypeException extends Exception {}

// typeName must be a valid API name (i.e. custom objects should be suffixed with "__c"):
public static SObject newSObject(String typeName) {
    Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
    if (targetType == null) {
        // calling code should usually handle this exception:
        throw new UndefinedSObjectTypeException('The requested SObject type [' + typeName + 
                '] cannot be constructed; it is not configured on this org.');
    }
    // SObjects offer the only way in Apex to instantiate an object with a type determined at 
    // runtime -- you can optionally pass an Id argument to instantiate an SObject for an 
    // existing record:
    return targetType.newSObject();
}

public static SObject newOpptyTeamMember() {
    return newSObject('OpptyTeamMember');
}

System.debug('Created new instance of: ' + newOpptyTeamMember().getSObjectType());