Apex Scheduler

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm

Apex Scheduler Notes and Best Practices

  • Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.
  • Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the limit. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time.
  • Though it’s possible to do additional processing in the execute method, we recommend that all processing take place in a separate class.
  • You can’t use the getContent and getContentAsPDF PageReference methods in scheduled Apex.
  • Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class. See Using Batch Apex.
  • Apex jobs scheduled to run during a Salesforce service maintenance downtime will be scheduled to run after the service comes back up, when system resources become available. If a scheduled Apex job was running when downtime occurred, the job is rolled back and scheduled again after the service comes back up. Note that after major service upgrades, there might be longer delays than usual for starting scheduled Apex jobs because of system usage spikes.

Apex Scheduler

To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.

Important

Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.

You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs.

Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the limit. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time.

If there are one or more active scheduled jobs for an Apex class, you cannot update the class or any classes referenced by this class through the Salesforce user interface. However, you can enable deployments to update the class with active scheduled jobs by using the Metadata API (for example, when using the Force.com IDE). See “Deployment Connections and Options” in the Salesforce Help.

Implementing the Schedulable Interface

To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interfaceSchedulable.

The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.

To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, from Setup, click Monitoring |Scheduled Jobs or Jobs | Scheduled Jobs.

The Schedulable interface contains one method that must be implemented, execute.

1 global void execute(SchedulableContext sc){}

The implemented method must be declared as global or public.

Use this method to instantiate the class you want to schedule.

Tip

Though it’s possible to do additional processing in the execute method, we recommend that all processing take place in a separate class.

The following example implements the Schedulable interface for a class called mergeNumbers:

1 global class scheduledMerge implements Schedulable {
2    global void execute(SchedulableContext SC) {
3       mergeNumbers M = new mergeNumbers();
4    }
5 }

The following example uses the System.Schedule method to implement the above class.

1 scheduledMerge m = new scheduledMerge();
2 String sch = '20 30 8 10 2 ?';
3 String jobID = system.schedule('Merge Job', sch, m);

You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulableinterface for a batch Apex class called batchable:

1 global class scheduledBatchable implements Schedulable {
2    global void execute(SchedulableContext sc) {
3       batchable b = new batchable();
4       database.executebatch(b);
5    }
6 }

An easier way to schedule a batch job is to call the System.scheduleBatch method without having to implement the Schedulableinterface.

Use the SchedulableContext object to keep track of the scheduled job once it’s scheduled. The SchedulableContextgetTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string. You can queryCronTrigger to track the progress of the scheduled job.

To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the getTriggerIDmethod.

Tracking the Progress of a Scheduled Job Using Queries

After the Apex job has been scheduled, you can obtain more information about it by running a SOQL query on CronTrigger and retrieving some fields, such as the number of times the job has run, and the date and time when the job is scheduled to run again, as shown in this example.

1 CronTrigger ct =
2     [SELECT TimesTriggered, NextFireTime
3     FROM CronTrigger WHERE Id = :jobID];

The previous example assumes you have a jobID variable holding the ID of the job. The System.schedule method returns the job ID. If you’re performing this query inside the execute method of your schedulable class, you can obtain the ID of the current job by calling getTriggerId on the SchedulableContext argument variable. Assuming this variable name is sc, the modified example becomes:

1 CronTrigger ct =
2     [SELECT TimesTriggered, NextFireTime
3     FROM CronTrigger WHERE Id = :sc.getTriggerId()];

You can also get the job’s name and the job’s type from the CronJobDetail record associated with the CronTrigger record. To do so, use the CronJobDetail relationship when performing a query on CronTrigger. This example retrieves the most recent CronTrigger record with the job name and type from CronJobDetail.

1 CronTrigger job =
2     [SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType
3     FROM CronTrigger ORDER BY CreatedDate DESC LIMIT 1];

Alternatively, you can query CronJobDetail directly to get the job’s name and type. This next example gets the job’s name and type for the CronTrigger record queried in the previous example. The corresponding CronJobDetail record ID is obtained by theCronJobDetail.Id expression on the CronTrigger record.

1 CronJobDetail ctd =
2     [SELECT Id, Name, JobType
3     FROM CronJobDetail WHERE Id = :job.CronJobDetail.Id];

To obtain the total count of all Apex scheduled jobs, excluding all other scheduled job types, perform the following query. Note the value ‘7’ is specified for the job type, which corresponds to the scheduled Apex job type.

1 SELECT COUNT() FROM CronTrigger WHERE CronJobDetail.JobType = '7'

Testing the Apex Scheduler

The following is an example of how to test using the Apex scheduler.

The System.schedule method starts an asynchronous process. This means that when you test scheduled Apex, you must ensure that the scheduled job is finished before testing against the results. Use the Test methods startTest and stopTest around theSystem.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after the startTestmethod are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the System.schedule method within the startTest and stopTest methods, the scheduled job executes at the end of your test method for Apex saved using Salesforce API version 25.0 and later, but not in earlier versions.

This is the class to be tested.

01 global class TestScheduledApexFromTestMethod implements Schedulable {
02
03 // This test runs a scheduled job at midnight Sept. 3rd. 2022
04
05    public static String CRON_EXP = '0 0 0 3 9 ? 2022';
06    
07    global void execute(SchedulableContext ctx) {
08       CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
09                 FROM CronTrigger WHERE Id = :ctx.getTriggerId()];
10
11       System.assertEquals(CRON_EXP, ct.CronExpression);
12       System.assertEquals(0, ct.TimesTriggered);
13       System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
14
15       Account a = [SELECT Id, Name FROM Account WHERE Name =
16                   'testScheduledApexFromTestMethod'];
17       a.name = 'testScheduledApexFromTestMethodUpdated';
18       update a;
19    }  
20 }
The following tests the above class:

01 @istest
02 class TestClass {
03
04    static testmethod void test() {
05    Test.startTest();
06
07       Account a = new Account();
08       a.Name = 'testScheduledApexFromTestMethod';
09       insert a;
10
11       // Schedule the test job
12
13       String jobId = System.schedule('testBasicScheduledApex',
14       TestScheduledApexFromTestMethod.CRON_EXP,
15          new TestScheduledApexFromTestMethod());
16
17       // Get the information from the CronTrigger API object
18       CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
19          NextFireTime
20          FROM CronTrigger WHERE id = :jobId];
21
22       // Verify the expressions are the same
23       System.assertEquals(TestScheduledApexFromTestMethod.CRON_EXP,
24          ct.CronExpression);
25
26       // Verify the job has not run
27       System.assertEquals(0, ct.TimesTriggered);
28
29       // Verify the next time the job will run
30       System.assertEquals('2022-09-03 00:00:00',
31          String.valueOf(ct.NextFireTime));
32       System.assertNotEquals('testScheduledApexFromTestMethodUpdated',
33          [SELECT id, name FROM account WHERE id = :a.id].name);
34
35    Test.stopTest();
36
37    System.assertEquals('testScheduledApexFromTestMethodUpdated',
38    [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);
39
40    }
41 }

Using the System.Schedule Method

After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.

Note

Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the limit. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time.

The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. This expression has the following syntax:

1 Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
Note

Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.

The System.Schedule method uses the user’s timezone for the basis of all schedules.

The following are the values for the expression:

Name Values Special Characters
Seconds 0–59 None
Minutes 0–59 None
Hours 0–23 , – * /
Day_of_month 1–31 , – * ? / L W
Month 1–12 or the following:

  • JAN
  • FEB
  • MAR
  • APR
  • MAY
  • JUN
  • JUL
  • AUG
  • SEP
  • OCT
  • NOV
  • DEC
, – * /
Day_of_week 1–7 or the following:

  • SUN
  • MON
  • TUE
  • WED
  • THU
  • FRI
  • SAT
, – * ? / L #
optional_year null or 1970–2099 , – * /
The special characters are defined as follows:

Special Character Description
, Delimits values. For example, use JAN, MAR, APR to specify more than one month.
Specifies a range. For example, use JAN-MAR to specify more than one month.
* Specifies all values. For example, if Month is specified as *, the job is scheduled for every month.
? Specifies no specific value. This is only available for Day_of_month and Day_of_week, and is generally used when specifying a value for one and not the other.
/ Specifies increments. The number before the slash specifies when the intervals will begin, and the number after the slash is the interval amount. For example, if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the month, starting on the first of the month.
L Specifies the end of a range (last). This is only available for Day_of_month and Day_of_week. When used withDay of month, L always means the last day of the month, such as January 31, February 28 for leap years, and so on. When used with Day_of_week by itself, it always means 7 or SAT. When used with a Day_of_week value, it means the last of that type of day in the month. For example, if you specify 2L, you are specifying the last Monday of the month. Do not use a range of values with L as the results might be unexpected.
W Specifies the nearest weekday (Monday-Friday) of the given day. This is only available for Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the class runs on the 19th. If you specify 1W, and the first is a Saturday, the class does not run in the previous month, but on the third, which is the following Monday.

Tip

Use the L and W together to specify the last weekday of the month.

# Specifies the nth day of the month, in the format weekday#day_of_month. This is only available for Day_of_week. The number before the # specifies weekday (SUN-SAT). The number after the # specifies the day of the month. For example, specifying 2#2 means the class runs on the second Monday of every month.

The following are some examples of how to use the expression.

Expression Description
0 0 13 * * ? Class runs every day at 1 PM.
0 0 22 ? * 6L Class runs the last Friday of every month at 10 PM.
0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 AM.
0 0 20 * * ? 2010 Class runs every day at 8 PM during the year 2010.

In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at 8 AM, on the 13th of February.

1 proschedule p = new proschedule();
2         String sch = '0 0 8 13 2 ?';
3         system.schedule('One Time Pro', sch, p);

Using the System.scheduleBatch Method for Batch Jobs

You can call the System.scheduleBatch method to schedule a batch job to run once at a specified time in the future. This method is available only for batch classes and doesn’t require the implementation of the Schedulable interface. This makes it easy to schedule a batch job for one execution. For more details on how to use the System.scheduleBatch method, see Using theSystem.scheduleBatch Method.

Apex Scheduler Limits

  • You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs.

  • The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This limit is for your entire organization and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users,Customer Portal User, and partner portal User licenses aren’t included.

Format and Options for Remote Objects Query Criteria

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_remote_objects_using_retrieve_query_object.htm

Format and Options for Remote Objects Query Criteria

Remote Objects uses an object to specify criteria for retrieve() operations. Use this object to specify where, limit, and offset conditions for your queries.
The structured format of the query object enables Visualforce to validate the criteria at save time, reducing the likelihood of runtime errors. The format is straightforward.

01 var ct = new RemoteObjectModel.Contact();
02 ct.retrieve(
03     { where: {
04         FirstName: {eq: 'Marc'},
05         LastName: {eq: 'Benioff'}
06       },
07       orderby: [ {LastName: 'ASC'}, {FirstName: 'ASC'} ],
08       limit: 1 }, 
09
10     function(err, records) {
11         if (err) {
12             alert(err);
13         } else {
14             console.log(records.length);
15             console.log(records[0]);
16         }
17     }
18 );

The query criteria find a contact named Marc Benioff and limit the query to a single result.

where Conditions

where conditions enable you to filter the results of a retrieve operation, much the same way that a WHERE condition in a SOQL query does. The operators that are available for where conditions are:

  • eq: equals
  • ne: not equals
  • lt: less than
  • lte: less than or equals
  • gt: greater than
  • gte: greater than or equals
  • like: string matching. As with SOQL, use “%” as a wildcard character.
  • in: in, used for finding a value that matches any of a set of fixed values. Provide values as an array, for example, [‘Benioff’, ‘Jobs’, ‘Gates’].
  • nin: not in, used for finding a value that matches none of a set of fixed values. Provide values as an array, for example, [‘Benioff’, ‘Jobs’, ‘Gates’].
  • and: logical AND, used for combining conditions
  • or: logical OR, used for combining conditions
Within the where object, add field name and condition pairs to create complex criteria. Multiple conditions by default are treated as AND conditions. You can use and and or to create other criteria conditions. For example:

01 {
02 where:
03     {
04     or:
05         {
06         FirstName: { like: "M%" },
07         Phone: { like: '(415)%' }
08         }
09     }
10 }

orderby Conditions

orderby enables you to set a sort order for your results. You can sort on up to three fields.

Specify your orderby conditions as an array of JavaScript objects that contain name-value pairs. The field to sort on is the name, and the sort description is the value. The sort description enables you to sort ascending or descending and to sort null values first or last. For example:

1 orderby: [ {Phone: "DESC NULLS LAST"} , {FirstName: "ASC"} ]

limit and offset Conditions

limit and offset enable you to retrieve a specific number of records at a time and to page through an extended set of results.

Use limit to specify how many records to return in one batch of results. The default value is 20. The maximum is 100.

Use offset to specify how many records to skip in the overall result set before adding records to the returned results. The minimum is 1. There is no maximum.

apex:inlineEditSupport

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_inlineEditSupport.htm

apex:inlineEditSupport

This component provides inline editing support to <apex:outputField> and various container components. In order to support inline editing, this component must also be within an <apex:form> tag.

The <apex:inlineEditSupport> component can only be a descendant of the following tags:

  • <apex:dataList>
  • <apex:dataTable>
  • <apex:form>
  • <apex:outputField>
  • <apex:pageBlock>
  • <apex:pageBlockSection>
  • <apex:pageBlockTable>
  • <apex:repeat>

See also: the inlineEdit attribute of <apex:detail>

01 <!-- For this example to render properly, you must associate the Visualforce page
02
03 with a valid contact record in the URL.
04
05 For example, if 001D000000IRt53 is the contact ID, the resulting URL should be:
06
07 https://Salesforce_instance/apex/myPage?id=001D000000IRt53
08
09 See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
10
11 <apex:page standardController="Contact">
12     <apex:form >
13         <apex:pageBlock mode="inlineEdit">
14             <apex:pageBlockButtons >
15                 <apex:commandButton action="{!edit}" id="editButton" value="Edit"/>
16                 <apex:commandButton action="{!save}" id="saveButton" value="Save"/>
17                 <apex:commandButton onclick="resetInlineEdit()" id="cancelButton"value="Cancel"/>
18             </apex:pageBlockButtons>
19             <apex:pageBlockSection >
20                 <apex:outputField value="{!contact.lastname}">
21                     <apex:inlineEditSupport showOnEdit="saveButton, cancelButton"
22                         hideOnEdit="editButton" event="ondblclick"
23                         changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>
24                 </apex:outputField>
25                 <apex:outputField value="{!contact.accountId}"/>
26                 <apex:outputField value="{!contact.phone}"/>
27             </apex:pageBlockSection>
28         </apex:pageBlock>
29     </apex:form>
30 </apex:page>

Attributes

Attribute Name Attribute Type Description Required? API Version Access
changedStyleClass String The name of a CSS style class used when the contents of a field have changed. 21.0
disabled Boolean A Boolean value that indicates whether inline editing is enabled or not. If not specified, this value defaults to true. 21.0
event String The name of a standard DOM event, such as ondblclick or onmouseover, that triggers inline editing on a field. 21.0
hideOnEdit Object A comma-separated list of button IDs. These buttons hide when inline editing is activated. 21.0
id String An identifier that allows the component to be referenced by other components in the page. 10.0 global
rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this defaults to true. 21.0
resetFunction String The name of the JavaScript function that is called when values are reset. 21.0
showOnEdit Object A comma-separated list of button IDs. These buttons display when inline editing is activated. 21.0

VisualForce Workbook

http://salesforce-learning.blogspot.com/2013/09/visualforce-workbook.html

VisualForce Workbook

Static  Resource Components

    • Type of salesforce storage
    • designed to be used on visualforce pages.
    • Examples – javascripts, css, images etc
    • referenced using $Resource global variable
    • Are uploaded via Your Name|Setup|Develop|Static Resources
    • can be contained in an archive (zip)
    • limited to 5 MB per file and a 250 mb overall
    • use action attribute to redirect

 

Dependent Picklist Considerations

  • There’s a limit of 10 dependent picklist pairs per page. This is totalled across all objects. Thus, you could have five dependent picklists on Account, and five on Contact, but no more. However, you can repeat the same pair of dependent picklists, such as in an iterative tag like <apex:repeat>, without counting more than once against your limit.
  • If the user viewing the page has read-only access to the controlling field, a dependent picklist might not behave as expected. In this case, the dependent picklist shows all possible values for the picklist, instead of being filtered on the read-only value. This is a known limitation in Visualforce.
  • Don’t mix inline edit-enabled fields with regular input fields from the same dependency group. For example, don’t mix a standard input field for a controlling field with an inline edit-enabled dependent field:

    <apex:page standardController="Account">
        <apex:form>
            <!-- Don't mix a standard input field... -->
            <apex:inputField value="{!account.Controlling__c}"/>
            <apex:outputField value="{!account.Dependent__c}">
                <!-- ...with an inline-edit enabled dependent field -->
                <apex:inlineEditSupport event="ondblClick" />
            </apex:outputField>
        </apex:form>
    </apex:page>

Visualforce Dashboard Components

  • Each dashboard can have up to 20 components.
  •  Visualforce pages that use the Standard Controller can’t be used in dashboards.
  • To be included in a dashboard, a Visualforce page must have either no controller; use a custom controller; or reference a page bound to the StandardSetController Class.  If a Visualforce page does not meet these requirements, it does not appear as an option in the dashboard componentVisualforce Page drop-down list.

Enabling Inline Editing

  • Components that support inline editing must always be descendants of the <apex:form> tag. However, the <apex:detail> component doesn’t have to be a descendant of an <apex:form> to support inline editing.
  •  The <apex:inlineEditSupport> component must be a descendant of the following components:
  • <apex:dataList>
  • <apex:dataTable>
  • <apex:form>
  • <apex:outputField>
  • <apex:pageBlock>
  • <apex:pageBlockSection>
  • <apex:pageBlockTable>
  • <apex:repeat>
  • The following are cases when inline editing isn’t supported.
    • Inline editing isn’t available in:
      • Accessibility mode
      • Setup pages
      • Dashboards
      • Customer Portal
      • Descriptions for HTML solutions
    • The following standard checkboxes on case and lead edit pages are not inline editable:
      • Case Assignment (Assign using active assignment rules)
      • Case Email Notification (Send notification email to contact)
      • Lead Assignment (Assign using active assignment rule)
    • The fields in the following standard objects are not inline editable.
      • All fields in Documents and Pricebooks
      • All fields in Tasks except for Subject and Comment
      • All fields in Events except for Subject, Description, and Location
      • Full name fields of Person Accounts, Contacts, and Leads. However, their component fields are, for example, First Name and Last Name.
    • You can use inline editing to change the values of fields on records for which you have read-only access, either via field-level security or your organization’s sharing model; however,Salesforce doesn’t let you save your changes, and displays an insufficient privileges error message when you try to save the record.
    • You can use inline editing to change the values of fields on records for which you have read-only access, either via field-level security or your organization’s sharing model; however,Salesforce doesn’t let you save your changes, and displays an insufficient privileges error message when you try to save the record.
    • Inline editing isn’t supported for standard rich text area (RTA) fields, such as Idea.Body, that are bound to <apex:outputField> when Visualforce pages are served from a separate domain, other than the salesforce.com domain. By default, Visualforce pages are served from a separate domain unless your administrator has disabled this setting. Custom RTA fields aren’t affected by this limitation and support inline editing.
    • Inline editing is supported for dependent picklists that use <apex:outputField>.
  • Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime error when the page displays.

Rendering a Page as a PDF

Things to note about using renderAs:

  • Currently, PDF is the only supported content converter.
  • Rendering a Visualforce page as a PDF is intended for pages that are designed and optimized for print.
  • Standard components which are not easily formatted for print or contain form elements like inputs, buttons, and any component that requires JavaScript to be formatted, shouldn’t be used. This includes but isn’t limited to any component that requires a form element.
  • PDF rendering doesn’t support JavaScript-rendered content.
  • Verify the format of your rendered page before deploying it.
  • If the PDF fails to display all the characters, adjust the fonts in your CSS to use a font that supports your needs. For example:
    <apex:page renderas="pdf">
    <html>
      <head> 
        <style> body { font-family: Arial Unicode MS; } </style> 
      </head>
      This page is rendered as a PDF
    </html>
    </apex:page>
  • The maximum response size when creating a PDF must be below 15 MB, before being rendered as a PDF. This is the standard limit for all Visualforce requests.
  • The maximum file size for a generated PDF is 60 MB.
  • The total size of all images included in a generated PDF is 30 MB.
  • PDF rendering doesn’t support images encoded in the data: URI scheme format.
  • Note that the following components do not support double-byte fonts when rendered as a PDF:
    • <apex:pageBlock>
    • <apex:sectionHeader>

    These components are not recommended for use in pages rendered as a PDF.

  • The <apex:pageBlockTable> component automatically takes on the styling of a standard Salesforce list. To display a list with your own styling, use<apex:dataTable> instead.
  •  You cannot use the reRender attribute to update content in a table in AJAX behaviour.

Styling Pages that Use Standard Controllers

For example, the following page uses the Account standard controller, but renders a page that highlights the Opportunities tab and uses the Opportunity tab’s yellow coloring:
<apex:page standardController="Account" tabStyle="Opportunity">
</apex:page>
  • To use the styling associated with MyCustomObject:
<apex:page standardController="Account" tabStyle="MyCustomObject__c">
</apex:page>
  • To use the styling associated with a custom Visualforce tab, set the attribute to the name (not label) of the tab followed by a double-underscore and the word tab. For example, to use the styling of a Visualforce tab with the name Source and a label Sources, use:
<apex:page standardController="Account" tabStyle="Source__tab">
</apex:page>
  • Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles.

–> To check if you have access to the standard Lead object, use the following code:

{!$ObjectType.Lead.accessible}

–> To ensure that a portion of your page will display only if a user has access to an object, use the render attribute on a component. For example, to display a page block if a user has access to the Lead object, you would do the following:

<apex:page standardController="Lead">
 <apex:pageBlock rendered="{!$ObjectType.Lead.accessible}">
  <p>This text will display if you can see the Lead object.</p>
 </apex:pageBlock>
 <apex:pageBlock rendered="NOT({!$ObjectType.Lead.accessible})">
  <p>Sorry, but you cannot see the data because you do not have access to the Lead object.</p>
 </apex:pageBlock>
</apex:page>

–> When using a standard list controller, the returned records sort on the first column of data, as defined by the current view, even if that column is not rendered. When using an extension or custom list controller, you can control the sort method.

–> No more than 10,000 records can be returned by a standard list controller. Custom controllers can work with larger results sets

–> By default, a list controller returns 20 records on the page. To control the number of records displayed on each page, use a controller extension to set thepageSize.

–> Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition

–> Multiple controller extensions can be defined for a single page through a comma-separated list. This allows for overrides of methods with the same name.
For example, if the following page exists:

<apex:page standardController="Account" 
    extensions="ExtOne,ExtTwo" showHeader="false">
    <apex:outputText value="{!foo}" />
</apex:page>

with the following extensions:

public class ExtOne {
    public ExtOne(ApexPages.StandardController acon) { }

    public String getFoo() {
        return 'foo-One';
    }
}
public class ExtTwo {
    public ExtTwo(ApexPages.StandardController acon) { }

    public String getFoo() {
        return 'foo-Two';
    }
}
The value of the <apex:outputText> component renders as foo-One. Overrides are defined by whichever methods are defined in the “leftmost” extension, or, the extension that is first in the comma-separated list. Thus, the getFoo method of ExtOne is overriding the method of ExtTwo.
Like other Apex classes, controller extensions run in system mode. Consequently, the current user's credentials are not used to execute controller logic, and the user's permissions and field-level security do not apply. However, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which the permissions, field-level security, and sharing rules of the current user apply.

Enabling Inline Editing

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_quick_start_inline_editing.htm

Enabling Inline Editing

Visualforce pages 21.0 and above support inline editing. Inline editing lets users quickly edit field values, right on a record’s detail page. Editable cells display a pencil icon (Editable Field) when you hover over the cell, while non-editable cells display a lock icon (Uneditable Field).

The <apex:detail> component has an attribute that activates inline editing, while the <apex:inlineEditSupport> component provides inline editing functionality to several container components.

To see the power of inline editing, create a page called inlineDetail with the following code:

1 <apex:page standardController="Account">
2     <apex:detail subject="{!account.Id}" relatedList="false" />
3 </apex:page>
Note

Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example:

Displaying Field Values with Visualforce has more information about retrieving the ID of a record.

Try to double-click one of the fields, like Account Number. You’ll notice that nothing happens.

Now, replace the page with the following code:

1 <apex:page standardController="Account">
2         <apex:detail subject="{!account.Id}" relatedList="false" inlineEdit="true"/>
3 </apex:page>

Hover over any of the fields, and you’ll notice that you can now edit their contents directly. Clicking Save at the top of the section preserves all your changed information. Components that support inline editing must always be descendants of the <apex:form>tag. However, the <apex:detail> component doesn’t have to be a descendant of an <apex:form> to support inline editing.

The <apex:inlineEditSupport> component must be a descendant of the following components:

  • <apex:dataList>
  • <apex:dataTable>
  • <apex:form>
  • <apex:outputField>
  • <apex:pageBlock>
  • <apex:pageBlockSection>
  • <apex:pageBlockTable>
  • <apex:repeat>
Here’s a sample that demonstrates how you can create a page using <apex:pageBlockTable> that makes use of inline editing:

01 <apex:page standardController="Account" recordSetVar="records" id="thePage">
02     <apex:form id="theForm">
03         <apex:pageBlock id="thePageBlock">
04             <apex:pageBlockTable value="{!records}" var="record" id="thePageBlockTable">
05                 <apex:column >
06                     <apex:outputField value="{!record.Name}" id="AccountNameDOM" />
07                     <apex:facet name="header">Name</apex:facet>
08                 </apex:column>
09                 <apex:column >
10                     <apex:outputField value="{!record.Type}" id="AccountTypeDOM" />
11                     <apex:facet name="header">Type</apex:facet>
12                 </apex:column>
13                 <apex:column >
14                     <apex:outputField value="{!record.Industry}"
15                         id="AccountIndustryDOM" />
16                         <apex:facet name="header">Industry</apex:facet>
17                 </apex:column>
18                 <apex:inlineEditSupport event="ondblClick"
19                         showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" />
20             </apex:pageBlockTable>
21             <apex:pageBlockButtons >
22                 <apex:commandButton value="Edit" action="{!save}" id="editButton" />
23                 <apex:commandButton value="Save" action="{!save}" id="saveButton" />
24                 <apex:commandButton value="Cancel" action="{!cancel}" id="cancelButton" />
25             </apex:pageBlockButtons>
26         </apex:pageBlock>
27     </apex:form>
28 </apex:page>

The following are cases when inline editing isn’t supported.

  • Inline editing isn’t available in:
    • Accessibility mode
    • Setup pages
    • Dashboards
    • Customer Portal
    • Descriptions for HTML solutions
  • The following standard checkboxes on case and lead edit pages are not inline editable:
    • Case Assignment (Assign using active assignment rules)
    • Case Email Notification (Send notification email to contact)
    • Lead Assignment (Assign using active assignment rule)
  • The fields in the following standard objects are not inline editable.
    • All fields in Documents and Pricebooks
    • All fields in Tasks except for Subject and Comment
    • All fields in Events except for Subject, Description, and Location
    • Full name fields of Person Accounts, Contacts, and Leads. However, their component fields are, for example,First Name and Last Name.
  • You can use inline editing to change the values of fields on records for which you have read-only access, either via field-level security or your organization’s sharing model; however, Salesforce doesn’t let you save your changes, and displays an insufficient privileges error message when you try to save the record.
  • Inline editing isn’t supported for standard rich text area (RTA) fields, such as Idea.Body, that are bound to<apex:outputField> when Visualforce pages are served from a separate domain, other than the Salesforce domain. By default, Visualforce pages are served from a separate domain unless your administrator has disabled this setting. Custom RTA fields aren’t affected by this limitation and support inline editing.
  • Inline editing is supported for dependent picklists that use <apex:outputField>.
  • Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime error when the page displays.

  • Don’t mix inline edit-enabled fields with regular input fields from the same dependency group. For example, don’t mix a standard input field for a controlling field with an inline edit-enabled dependent field:

    01 <apex:page standardController="Account">
    02     <apex:form>
    03         <!-- Don't mix a standard input field... -->
    04         <apex:inputField value="{!account.Controlling__c}"/>
    05         <apex:outputField value="{!account.Dependent__c}">
    06             <!-- ...with an inline-edit enabled dependent field -->
    07             <apex:inlineEditSupport event="ondblClick" />
    08         </apex:outputField>
    09     </apex:form>
    10 </apex:page>
  • If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or controlling relationships to each other as one group. Refreshing fields individually isn’t recommended and might result in inconsistent undo/redo behavior. Here’s an example of the recommended way to partially refresh a form with inline edit-enabled dependent picklists:

    01 <apex:form>
    02     <!-- other form elements ... -->
    03
    04     <apex:outputPanel id="locationPicker">
    05         <apex:outputField value="{!Location.country}">
    06             <apex:inlineEditSupport event="ondblClick" />
    07         </apex:outputField>
    08         <apex:outputField value="{!Location.state}">
    09             <apex:inlineEditSupport event="ondblClick" />
    10         </apex:outputField>
    11         <apex:outputField value="{!Location.city}">
    12             <apex:inlineEditSupport event="ondblClick" />
    13         </apex:outputField>
    14     </apex:outputPanel>
    15     <!-- ... -->
    16     <apex:commandButton value="Refresh Picklists" reRender="locationPicker" />
    17 </apex:form>

    All of the inline edit-enabled picklists are wrapped in the <apex:outputPanel> component. The <apex:outputPanel> rerenders when the <apex:commandButton> action method fires.

Spring’15 – Delete Components before and after Component Updates in a deployment

Delete Components before and after Component Updates

You can control when components are deleted in a deployment. Use a manifest to specify component deletions before updates, and use another manifest to specify component deletions after updates. Specifying the processing order of deletions relative to component updates provides you with greater flexibility and enables you to delete components with dependencies.

To delete components, use the same procedure as with deploying components, but also include the appropriate delete manifest files. The format of the delete manifest is the same as package.xml except that wildcards aren’t supported.

  • To delete components before adding or updating other components, create a manifest file that’s nameddestructiveChangesPre.xml and include the components to delete.
  • To delete components after adding or updating other components, create a manifest file that’s nameddestructiveChangesPost.xml and include the components to delete.

This feature applies to the Metadata API deploy() call or Metadata API-based tools, such as the Force.com Migration Tool.

The ability to specify when deletions are processed is useful when you’re deleting components with dependencies. For example, if a custom object is referenced in an Apex class, you can’t delete it unless you modify the Apex class first to remove the dependency on the custom object. In this example, you can perform a single deployment that updates the Apex class to clear the dependency and then deletes the custom object by using destructiveChangesPost.xml. The following are samples of thepackage.xml and destructiveChangesPost.xml manifests that would be used in this example.

Sample package.xml, which specifies the class to update:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>SampleClass</members>
        <name>ApexClass</name>
    </types>
    <version>33.0</version>
</Package>

Sample destructiveChangesPost.xml, which specifies the custom object to delete after the class update:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>MyCustomObject__c</members>
        <name>CustomObject</name>
    </types>
</Package>
Note

  • The API version that the deployment uses is the API version that’s specified in package.xml.
  • The destructiveChangesPre.xml and destructiveChangesPost.xml manifests are supported starting with API version 33.0. In earlier versions, only destructiveChanges.xml is supported. In API version 33.0 and later, if the processing order for deletions and additions doesn’t matter, you can continue usingdestructiveChanges.xml.
  • When you’re using destructiveChanges.xml, deletions are processed first by default.

Salesforce Sandboxes

A sandbox is a very important tool in Salesforce for testing and development without affecting your live instance. I am not sure what types of Sandboxes you have but it’s good to have more than one if you are working on different projects that you do not want to affect eachother or if you have multiple projects that need to be worked on it all depends on your needs. Testing over all is very important.

The sandbox types are:

Developer Sandbox

Developer sandboxes are special configuration sandboxes intended for coding and testing by a single developer. Multiple users can log into a single Developer sandbox, but their primary purpose is to provide an environment in which changes under active development can be isolated until they’re ready to be shared. Just like Developer Pro sandboxes, Developer sandboxes copy all application and configuration information to the sandbox. Developer sandboxes are limited to 200 MB of test or sample data, which is enough for many development and testing tasks. You can refresh a Developer sandbox once per day.

Developer Pro Sandbox
Developer Pro sandboxes copy all of your production organization’s reports, dashboards, price books, products, apps, and customizations under Setup, but exclude all of your organization’s standard and custom object records, documents, and attachments. Creating a Developer Pro sandbox can decrease the time it takes to create or refresh a sandbox from several hours to just a few minutes, but it can only include up to 1 GB of data. You can refresh a Developer Pro sandbox once per day.

Partial Data Sandbox
Partial Data sandboxes include all of your organization’s metadata and add a selected amount of your production organization’s data that you define using a sandbox template. A Partial Data sandbox is a Developer sandbox plus the data you define in a sandbox template. It includes the reports, dashboards, price books, products, apps, and customizations under Setup (including all of your metadata). Additionally, as defined by your sandbox template, Partial Data sandboxes can include your organization’s standard and custom object records, documents, and attachments up to 5 GB of data and a maximum of 10,000 records per selected object. A Partial Data sandbox is smaller than a Full sandbox and has a shorter refresh interval. You can refresh a Partial Data sandbox every 5 days.

Full Sandbox
Full sandboxes copy your entire production organization and all its data, including standard and custom object records, documents, and attachments. You can refresh a Full sandbox every 29 days.
Sandbox templates allow you to pick specific objects and data to copy to your sandbox, so you can control the size and content of each sandbox. Sandbox templates are only available for Partial Data or Full sandboxes.

Which automation tool to use in Salesforce: comparison of Process Builder, Visual Workflow, Workflow and Approval Process

https://developer.salesforce.com/trailhead/force_com_dev_beginner/business_process_automation/process_whichtool

Automation Tool Features

Here’s a breakdown of all the features and actions that are supported in each of our automation tools. Use it to figure out which tool is best for your business needs.

Process Builder Visual Workflow Workflow Approvals
Complexity Multiple if/then statements Complex A single if/then statement A single if/then statement
Visual designer check icon indicating true check icon indicating true
Browser support All (Chrome recommended) All (Safari not recommended) All All
Starts when Record is changed
  • User clicks button or link
  • User accesses custom tab
  • Process starts
  • Apex is called
Record is changed
  • User clicks button or link
  • Process or flow starts that includes a “Submit for Approval” action
  • Apex is called
Supports time-based actions check icon indicating true(only one time supported per criteria node) check icon indicating true check icon indicating true
Supports user interaction check icon indicating true
Supported Actions
Call Apex code check icon indicating true check icon indicating true
Create records check icon indicating true check icon indicating true Tasks only Tasks only
Delete records check icon indicating true
Launch a flow check icon indicating true check icon indicating true check icon indicating true (Pilot)1
Post to Chatter check icon indicating true check icon indicating true
Send email check icon indicating true(Email alerts only) check icon indicating true check icon indicating true(Email alerts only) check icon indicating true(Email alerts only)
Send outbound messages without code check icon indicating true
Submit for approval check icon indicating true check icon indicating true
Update fields Any related record Any record The record or its parent The record or its parent

1The Process Builder has superseded flow trigger workflow actions, formerly available in a pilot program. Organizations that are using flow trigger workflow actions can continue to create and edit them, but flow trigger workflow actions aren’t available for new organizations. For information on enabling the Process Builder in your organization, contact Salesforce.

Set Up Dynamic Dashboards

https://help.salesforce.com/apex/HTViewHelpDoc?id=dashboards_dynamic_setting_up.htm

Set Up Dynamic Dashboards

To set up a dynamic dashboard, create a folder to hold the dashboard and its underlying reports, then create the dashboard.
Available in: Enterprise, Performance, Unlimited, and Developer Editions
User Permissions Needed
To create, edit, and delete dynamic dashboards: “Run Reports” AND “Manage Dynamic Dashboards”
To enable choosing a different running user for the dashboard: “View My Team’s Dashboards” OR “View All Data”

Your organization can have up to five dynamic dashboards for Enterprise Edition, 10 for Unlimited and Performance Edition, and three for Developer Edition.

Note

  • You can’t save dynamic dashboards to personal folders.
  • You can’t schedule refreshes for dynamic dashboards. They must be refreshed manually.
  1. Create folders accessible to all dashboard viewers to store dynamic dashboards and corresponding component source reports.
  2. From the Dashboards tab, create a new dashboard or edit an existing one.
  3. Click the View dashboard as drop-down button button next to the View dashboard as field.
    Note
    If you don’t have “Manage Dynamic Dashboards” permission, just enter a running user and skip to the final step. Enter “*” to see all available users.
  4. Select Run as logged-in user.
  5. Optionally, select Let authorized users change running user to enable those with permission to change the running user on the dashboard view page.
    • Users with “View My Team’s Dashboards” can view the dashboard as any user below them in the role hierarchy.
    • Users with “View All Data” can edit the dashboard and view it as any user in their organization.
    • Users with “Enable Other User’s Dashboard” can edit the dashboard if they have access to it, even if they aren’t the running user and don’t have “View All Data.”
  6. Click OK.
  7. In the View dashboard as field, enter a running user.
  8. Save your dashboard.
  9. Set the appropriate Show option on the report run page.
    For example, if you choose “My Team’s Opportunities,” each dynamic dashboard viewer can see all opportunities for the team.

Tip
To avoid restricting the dashboard’s view of the data:

  • Make sure advanced filters don’t include specific record owners (for example, Opportunity Owner equals Frank Smith).
  • Don’t click Save Hierarchy Level when saving opportunity reports.