Tag Archives: Apex

SOQL Query To Get Users with Salesforce User License

Get all Users with User License:

List<User> userList = [Select Id, Name, Profile.UserLicense.Name From User];

Get Users with specific User License:

List<User> userList = [Select Id, Name, Profile.UserLicense.Name From User WHERE Profile.UserLicense.Name = 'Salesforce'];

Invoke Batch Apex From Another Batch Apex

In batch class “Execute” method being called many times but “Start” and “Finish” method only once. So, To call another batch class from a batch class, we can call another batch class either in start method or in finish method as per our requirement.

Here in below example there are two batch classes “Batch1” and “Batch2“.
As per my requirement, I want to execute “Batch2” after finish the “Batch1“.
So, I’m calling “Batch2” class in “Batch1” finish method.

Batch1:

global class Batch1 implements Database.Batchable<Sobject>{

	//Method to get the data to be proceesed  
	global database.Querylocator Start(Database.BatchableContext bc){
		String query = 'Select Id, Name From Account Limit 1000';
		return Database.getQueryLocator(query);
	}


	//Method to execute the batch
	global void execute(Database.BatchableContext bc, Sobject[] scope){
		for(Sobject s : scope){ 
		Account a = (Account)s;
			// TO DO
			// add your logic 
		}
	}

	//Method to be called after the excute
	global void finish(Database.BatchableContext bc){
		//Add your start code for the other batch job here
		Database.executeBatch(new Batch2());
	}
}

Batch2:

global class Batch2 implements Database.Batchable<Sobject>{

	//Method to get the data to be proceesed  
	global database.Querylocator start(Database.BatchableContext bc){
		string query = 'Select Id, Name From Contact Limit 1000';
		return Database.getQueryLocator(query);
	}


	//Method to execute the batch
	global void execute(Database.BatchableContext bc, Sobject[] scope){
		for(Sobject s : scope){ 
		Contact c = (Contact)s;
			// TO DO
			// add your logic 
		}
	}

	//Method to be called after the excute
	global void finish(Database.BatchableContext bc){

	}
}

Display of Validation Rule Error on Visualforce Page

Here I’ve a custom “Student__c” object. There is a validation rule on “Date_of_Birth__c” field, that Date of Birth cannot be greater than today. And I’m using a visualforce page to insert the data in “Student__c” object. So, I need to show the validation rule error message in visualforce page.

Validation Rule:

Below is my controller which gave the solution for displaying validation error message on visualforce page.

Controller:

public with sharing class StudentExt {

    public Student__c student{get;set;}
    
    public StudentExt(ApexPages.StandardController controller) {
        student = (Student__c)controller.getRecord();
    }
    
    public Pagereference saveStudent() {
        try {
            Upsert student;
            return new Pagereference('/' + student.Id);
        }
        catch(DMLException de) {
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, de.getDmlMessage(0)));
            return NULL;
        }
        catch(Exception e) {
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, e.getMessage()));
            return NULL;
        }
    }
}

Visualforce Page

<apex:page standardController="Student__c" extensions="StudentExt" >
    <apex:pageMessages id="errormsg" />
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!saveStudent}" reRender="errormsg"/>
                <apex:commandButton value="Cancel" action="{!Cancel}"/>
            </apex:pageBlockButtons>
            
            <apex:pageBlockSection columns="2" title="Information">
                <apex:inputField value="{!Student__c.First_Name__c}"/>
                <apex:inputField value="{!Student__c.Last_Name__c}"/>
                <apex:inputField value="{!Student__c.Date_of_Birth__c}"/>
                <apex:inputField value="{!Student__c.Address__c}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Label does not get displayed when inputField is in an actionRegion

Action Region will wrap only the input Field and not the complete pageBlockSectionItem. Place pageBlockSectionItem tags inside a pageBlockSection, which in turn should be in a pageBlock. This will provide the correct formatting.

<apex:page standardController="Campaign" showHeader="true" >
	<apex:form>
		<apex:outputPanel id="op1">
			<apex:pageBlock>
				<apex:pageBlockSection columns="2" title="Information">
					<apex:pageBlockSectionItem>
						<apex:actionRegion>
							<apex:inputField label="{!$ObjectType.Campaign.fields.Category__c.Label}" value="{!Campaign.Category__c}"> 
								<apex:actionSupport event="onchange" rerender="op1" />
							</apex:inputField>
						</apex:actionRegion>
					</apex:pageBlockSectionItem>
				</apex:pageBlockSection>
			</apex:pageBlock> 
		</apex:outputPanel>
	</apex:form>
</apex:page>

Salesforce Visualforce Page Lifecycle

Visualforce page’s lifecycle is, how the page is created and destroyed during the period of a user session. The lifecycle of a visualforce page is determined not just by the content of the page, but also by how the page was requested.

When a user views a Visualforce page, instances of the controller, extensions, and components associated with the page are created by the server. The order in which these elements are executed can affect how the page is displayed to the user.

There are two types of Visualforce page requests:

Visualforce Page Get Requests:
A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.

Order of Execution for Visualforce Page Get Requests: The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a get request:

In the diagram above the user initially requests a page, either by entering a URL or clicking a link or button. This initial page request is called the get request.

  • The constructor methods on the associated custom controller/extension classes are called, instantiating the controller objects.
  • If the page contains any custom components, they are created and the constructor methods on any associated custom controllers or controller extensions are executed. If attributes are set on the custom component using expressions, the expressions are evaluated after the constructors are evaluated.
  • The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are executed, expressions are evaluated, the action attribute on the component is apex:pageevaluated, and all other method calls, such as getting or setting a property value, are made.
  • If the page contains an apex:form component, all of the information necessary to maintain the state of the database between page requests is saved as an encrypted view state. The view state is updated whenever the page is updated.
  • The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser executes them.

Note:

  • Once a new get request is made by the user, the view state and controller objects are deleted.
  • If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions, a post back request is made. When a post back request is made, the view state is maintained.

Visualforce Page Postback Requests:
A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a save action.
Order of Execution for Visualforce Page Postback Requests: The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a postback request:

  • During a postback request, the view state is decoded and used as the basis for updating the values on the page. (A component with the immediate attribute set to true bypasses this phase of the request. In other words, the action executes, but no validation is performed on the inputs and no data changes on the page.)
  • After the view state is decoded, Expressions are evaluated and set methods on the controller and any controller extensions, including set methods in controllers defined for custom components, are executed. If update is not valid due to validation rule or incorrect data type, data is not updated and page redisplay with error message.
  • Data updated on action there is no evaluation for component attribute. (The action attribute on the component is not evaluated during a postback request. It is only evaluated during a get request.)
  • The resulting HTML is sent to the browser.

Note:

  • Once the user is redirected to another page, the view state and controller objects are deleted.
  • You can use the setRedirect attribute on a pageReference to control whether a postback or get request is executed. If setRedirect is set to true, a get request is executed. Setting it to false does not ignore the restriction that a postback request will be executed if and only if the target uses the same controller and a proper subset of extensions. If setRedirect is set to false, and the target does not meet those requirements, a get request will be made.