Metadata API Developer's Guide
Metadata API Developer's Guide
© Copyright 2000-2009 salesforce.com, inc. All rights reserved. Salesforce.com and the “no software” logo are registered trademarks, and
AppExchange, “Success On Demand,” and “The Business Web” are trademarks of salesforce.com, inc. All other trademarks mentioned in
this document are the properties of their respective owners.
Table of Contents
Table of Contents
i
Table of Contents
Component Field Data Types.....................................................................................................................................62
Supported Calls...........................................................................................................................................................62
ApexClass....................................................................................................................................................................63
ApexComponent.........................................................................................................................................................64
ApexPage.....................................................................................................................................................................65
ApexTrigger.................................................................................................................................................................66
CustomApplication.....................................................................................................................................................68
CustomDataType........................................................................................................................................................69
CustomLabels..............................................................................................................................................................69
CustomObject.............................................................................................................................................................71
CustomField....................................................................................................................................................74
ListView..........................................................................................................................................................79
Picklist.............................................................................................................................................................81
RecordType......................................................................................................................................................84
SearchLayouts..................................................................................................................................................86
SharingReason.................................................................................................................................................88
SharingRecalculation.......................................................................................................................................89
ValidationRule.................................................................................................................................................90
Weblink...........................................................................................................................................................91
Metadata Field Types......................................................................................................................................94
CustomObjectTranslation...........................................................................................................................................95
CustomPageWebLink...............................................................................................................................................100
CustomSite................................................................................................................................................................103
CustomTab................................................................................................................................................................106
Dashboard.................................................................................................................................................................108
Document..................................................................................................................................................................114
EmailTemplate..........................................................................................................................................................115
Folder.........................................................................................................................................................................118
HomePageComponent..............................................................................................................................................119
HomePageLayout......................................................................................................................................................120
Layout........................................................................................................................................................................121
Letterhead.................................................................................................................................................................127
Metadata....................................................................................................................................................................129
MetadataWithContent..............................................................................................................................................130
Portal.........................................................................................................................................................................131
Profile........................................................................................................................................................................133
Report........................................................................................................................................................................140
ReportType................................................................................................................................................................154
Scontrol.....................................................................................................................................................................157
StaticResource...........................................................................................................................................................159
Translations...............................................................................................................................................................160
Workflow...................................................................................................................................................................164
Index....................................................................................................................................................174
ii
Chapter 1
Understanding the Metadata API
Use the asynchronous metadata API to manage setup and customization information (metadata) for your organizations:
• Export the customizations in your organization as XML metadata files. See Working with the Zip File and retrieve().
• Migrate configuration changes between organizations. See deploy() and retrieve().
• Modify existing customizations in your organization using XML metadata files. See deploy() and retrieve().
• Manage customizations in your organization programmatically. See CRUD-Based Metadata Development, create(), update(),
and delete().
You can modify metadata in test organizations on Developer Edition or Sandbox, and then deploy tested changes to production organizations
on Enterprise Edition or Unlimited Editions. You can also create scripts to populate a new organization with your custom objects, custom
fields, and other components.
3
Understanding the Metadata API Development Platforms
Development Platforms
The metadata API supports both CRUD-based and file-based development.
CRUD-Based Development
The CRUD-based asynchronous metadata API calls create(), update(), and delete() act upon the metadata
components in a manner similar to the way synchronous API calls in the enterprise WSDL act upon objects. For more
information about the enterprise WSDL, see the Force.com Web Services API Developer's Guide.
Note: CRUD (create, read, update, delete) implies that there is a read call, but there is no equivalent read call for
CRUD-based development. If you want to read your metadata, you should use the retrieve() call, described in
File-Based Development on page 4.
Use the create(), update(), and delete()calls with the utility call checkStatus(). For more information, see
CRUD-Based Metadata Development on page 23 and Quick Start on page 6.
File-Based Development
The declarative or file-based asynchronous metadata API deploy() and retrieve() calls deploy or retrieve a .zip file
that holds components in a set of folders, and a manifest file named package.xml. For more information, see Declarative
Metadata Development on page 32. The easiest way to access this functionality is to use the Force.com IDE or Force.com
Migration Tool. However, the underlying calls have been exposed for you to use directly, if needed. For more information
about the Force.com IDE or Force.com Migration Tool, see developer.force.com.
Standards Compliance
The metadata API is implemented to comply with the following specifications:
Backward Compatibility
Salesforce.com strives to make backward compatibility easy when using the Force.com platform.
Each new Salesforce release consists of two components:
4
Understanding the Metadata API What’s New in Version 15.0
API End-of-Life
Salesforce.com is committed to supporting each API version for a minimum of three years from the date of first release. In
order to mature and improve the quality and performance of the API, versions that are more than three years old may cease
to be supported.
When an API version is to be deprecated, advance end-of-life notice will be given at least one year before support for the API
version is ended. Salesforce.com will directly notify customers using API versions planned for deprecation.
Related Resources
The salesforce.com developer website provides a full suite of developer toolkits, sample code, sample SOAP messages,
community-based support, and other resources to help you with your development projects. Be sure to visit
https://wiki.apexdevnet.com/index.php/Getting_Started for more information, or visit http://developer.force.com/join to sign
up for a free Developer Edition account.
You can visit these websites to find out more about Salesforce applications:
• Developer Force provides a wealth of information for developers.
• Salesforce.com for information about the Salesforce application.
• Force.com AppExchange for access to apps created for Salesforce.
• Salesforce.com Community for services to ensure Salesforce customer success.
5
Chapter 2
Quick Start
This quick start gives you all the information you need to start writing applications that use the metadata API to manage customizations for
your organization. It shows you how to get started with CRUD-Based Development and file-based development.
The easiest way to start working with file-based development is to use the Force.com IDE or Force.com Migration Tool. However, the
underlying calls have been exposed for you to use directly, if needed. For more information about the Force.com IDE or Force.com Migration
Tool, see developer.force.com.
Prerequisites
Before you can start using the metadata metadata API, you need to do some background work:
• Identify a user that has a profile with the "API Enabled" and "Modify All Data" permissions. These permissions are
required to access metadata API calls.
• Install a SOAP client. The metadata API works with current SOAP development environments, including, but not limited
to, Visual Studio .NET 2005, and Apache Axis. In this document, we provide examples in Java. The Java examples are
based on Apache Axis 1.3 and JDK 5.0 ( Java 2 Platform Standard Edition Development Kit 5.0). For more information
about Apache Axis 1.3, go to http://ws.apache.org/axis/. To see a complete list of compatible development platforms and
more sample code, go to developer.force.com.
Note: Development platforms vary in their SOAP implementations. Implementation differences in certain
development platforms might prevent access to some or all of the features in the metadata API. If you are using
Visual Studio for .NET development, we recommend that you use Visual Studio 2003 or higher.
6
Quick Start Step 2: Generate or Obtain the Web Service WSDLs
7
Quick Start Step 4: Walk Through the Sample Code
The -a switch generates code for all elements, referenced or not, which may be necessary depending on your WSDL. For
more information, see the WSDL2Java documentation.
If you have JAR files in more than one location, list them with a semicolon separating the files. For example, if the Axis JAR
files are installed in C:\axis-1.3, and the WSDL is named my_metadata.wsdl and is stored in C:\mywsdls, use
the following command to generate the Java stub files:
java –classpath
c:\axis-1.3\lib\axis.jar;c:\axis-1.3\lib\axis-ant.jar;c:\axis-1.3\lib\axis-schema.jar;
c:\axis-1.3\lib\commons-discovery-0.2.jar;c:\axis-1.3\lib\commons-logging-1.0.4.jar;
c:\axis-1.3\lib\jaxrpc.jar;c:\axis-1.3\lib\log4j-1.2.8.jar;c:\axis-1.3\lib\saaj.jar;
c:\axis-1.3\lib\wsdl4j-1.5.2.jar;c:\axis-1.3\mail.jar;c:\axis-1.3\activation.jar;c:\axis-1.3\wsdl4j.jar;
org.apache.axis.wsdl.WSDL2Java -a C:\mywsdls\my_metadata.wsdl
To generate stub files for the enterprise WSDL, use a similar command:
java –classpath
c:\axis-1.3\lib\axis.jar;c:\axis-1.3\lib\axis-ant.jar;c:\axis-1.3\lib\axis-schema.jar;
c:\axis-1.3\lib\commons-discovery-0.2.jar;c:\axis-1.3\lib\commons-logging-1.0.4.jar;
c:\axis-1.3\lib\jaxrpc.jar;c:\axis-1.3\lib\log4j-1.2.8.jar;c:\axis-1.3\lib\saaj.jar;
c:\axis-1.3\lib\wsdl4j-1.5.2.jar;c:\axis-1.3\mail.jar;c:\axis-1.3\activation.jar;c:\axis-1.3\wsdl4j.jar;
org.apache.axis.wsdl.WSDL2Java -a C:\mywsdls\my_enterprise.wsdl
These commands generate a set of folders and Java source code files in the same directory in which they were run. After these
files are compiled, they can be included in your Java programs for use in creating client applications.
For most Java development environments, you can use wizard-based tools for this process instead of the command line. For
more information about using WSDL2Java, see http://ws.apache.org/axis/java/reference.html. For more information about
using WSDL2Java with Force.com, visit the message boards at http://www.salesforce.com/developer/boards.jsp.
8
Quick Start Step 4: Walk Through the Sample Code
All client applications that access the metadata API must complete the tasks in this step before attempting any subsequent
metadata API calls.
package com.doc.samples;
import java.io.*;
import javax.xml.rpc.ServiceException;
import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
import com.sforce.soap._2006._04.metadata.MetadataBindingStub;
import com.sforce.soap._2006._04.metadata.MetadataServiceLocator;
import com.sforce.soap._2006._04.metadata.AsyncResult;
import com.sforce.soap._2006._04.metadata.CustomField;
import com.sforce.soap._2006._04.metadata.CustomObject;
import com.sforce.soap._2006._04.metadata.DeploymentStatus;
import com.sforce.soap._2006._04.metadata.FieldType;
import com.sforce.soap._2006._04.metadata.SharingModel;
/**
* Title: Sample that logs in and creates a custom object.
*
* Description: Console application illustrating login, session management,
* and server redirection.
*
* Assumptions:
* 1. The Enterprise WSDL has been downloaded and sample stub code has been generated
* by a tool like WSDL2Java. The Enterprise or Partner WSDL must be used to
* use the login() call for authentication. In this case, we use the Enterprise WSDL.
* 2. The Metadata WSDL has been downloaded and sample stub code has been generated
* by a tool like WSDL2Java.
*
*/
public class CreateSample {
// binding for the Enterprise WSDL used for login() call
private SoapBindingStub binding;
// binding for the metadata WSDL used for create() and checkStatus() calls
private MetadataBindingStub metadatabinding;
public CreateSample() {
}
9
Quick Start Step 4: Walk Through the Sample Code
/**
* The login call is used to obtain a token from Salesforce.
* This token must be passed to all other calls to provide
* authentication.
*/
private boolean login() throws ServiceException {
String userName = getUserInput("Enter username: ");
String password = getUserInput("Enter password: ");
/** Next, the sample client application initializes the binding stub.
*
* This is our main interface to the API for the Enterprise WSDL.
* The getSoap method takes an optional parameter,
* (a java.net.URL) which is the endpoint.
* For the login call, the parameter always starts with
* http(s)://www.salesforce.com. After logging in, the sample
* client application changes the endpoint to the one specified
* in the returned loginResult object.
*/
binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
10
Quick Start Step 4: Walk Through the Sample Code
/** The sample client application now has an instance of the MetadataBindingStub
* that is pointing to the correct endpoint. Next, the sample client application
* sets a persistent SOAP header (to be included on all subsequent calls that
* are made with the SoapBindingStub) that contains the valid sessionId
* for our login credentials. To do this, the sample client application
* creates a new SessionHeader object and set its sessionId property to the
* sessionId property from the LoginResult object.
*/
// Create a new session header object and add the session id
// from the login return object
SessionHeader sh = new SessionHeader();
sh.setSessionId(loginResult.getSessionId());
/** Next, the sample client application calls the setHeader method of the
* SoapBindingStub to add the header to all subsequent method calls. This
* header will persist until the binding is destroyed or until the header
* is explicitly removed. The "SessionHeader" parameter is the name of the
* header to be added.
*/
// set the session header for subsequent call authentication
metadatabinding.setHeader(
new MetadataServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader", sh);
/**
* Create a custom object. This method demonstrates usage of the
* create() and checkStatus() calls.
*/
private void createCustomObject() {
CustomObject co = new CustomObject();
String name = "My Custom Object";
co.setFullName("MyCustomObject" + "__c");
co.setDeploymentStatus(DeploymentStatus.Deployed);
co.setDescription("Created by the Metadata API Sample");
co.setEnableActivities(true);
co.setLabel(name);
co.setPluralLabel(co.getLabel() + "s");
co.setSharingModel(SharingModel.ReadWrite);
CustomField nf = new CustomField();
nf.setType(FieldType.Text);
nf.setDescription("The custom object identifier on page layouts, " +
"related lists etc");
nf.setLabel("My Custom Object");
nf.setFullName("MyCustomObject" + " __c");
11
Quick Start Step 4: Walk Through the Sample Code
// The name field appears in page layouts, related lists, and elsewhere.
co.setNameField(nf);
try {
AsyncResult[] ars = metadatabinding.create(new CustomObject[] { co });
if (ars == null) {
System.out.println("The object was not created successfully");
return;
}
/**
* After the create() call completes, we must poll the results
* of the checkStatus() call until it indicates that the create
* operation is completed.
*/
while (!done) {
arsStatus = metadatabinding.checkStatus(ids);
if (arsStatus == null) {
System.out.println("The object status cannot be retrieved");
return;
}
done = arsStatus[0].isDone();
if (arsStatus[0].getStatusCode() != null ) {
System.out.println("Error status code: " +
arsStatus[0].getStatusCode());
System.out.println("Error message: " + arsStatus[0].getMessage());
}
Thread.sleep(waitTimeMilliSecs);
// double the wait time for the next iteration
waitTimeMilliSecs *= 2;
System.out.println("The object state is " + arsStatus[0].getState());
}
12
Quick Start Step 4: Walk Through the Sample Code
2. Calls login() which is part of the enterprise WSDL and, if the login succeeds:
• Sets the returned sessionId into the session header for the metadata SOAP binding. This is required for session
authentication on subsequent metadata API calls.
• Resets the endpoint to the returned metadataServerUrl, which is the target of subsequent metadata API calls.
All client applications that access the metadata API must complete the tasks in this step before attempting any subsequent
metadata API calls.
3. Prompts the user to execute a retrieve() and deploy() call. The user can execute retrieve() or deploy()
calls until they choose the exit option.
The retrieve() and deploy() calls both operate on a zip file named components.zip. The retrieve() call retrieves
components from your organization into components.zip, and the deploy() call deploys the components in components.zip
to your organization. If you save the sample to your computer and execute it, you should run the retrieve option first so that
you have a components.zip file that you can subsequently deploy.
The retrieve() call uses a manifest file to determine the components to retrieve from your organization. A sample
package.xml manifest file is listed below. For more details on the manifest file structure, see Working with the Zip File on
page 32. For the purposes of this sample, it is sufficient to know that this manifest file retrieves all custom objects, custom
tabs, and page layouts.
Note the error handling code that follows each API call.
Note: This sample was created using Apache Axis. The WSDL2Java utility generates a _package class, even though
the metadata type is defined as Package in the Metadata WSDL. Other SOAP clients may generate a different
name for the _package class.
package com.doc.samples;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.rmi.RemoteException;
13
Quick Start Step 4: Walk Through the Sample Code
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ServiceException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sforce.soap._2006._04.metadata.AsyncRequestState;
import com.sforce.soap._2006._04.metadata.AsyncResult;
import com.sforce.soap._2006._04.metadata.CodeCoverageWarning;
import com.sforce.soap._2006._04.metadata.DeployMessage;
import com.sforce.soap._2006._04.metadata.DeployOptions;
import com.sforce.soap._2006._04.metadata.DeployResult;
import com.sforce.soap._2006._04.metadata.MetadataBindingStub;
import com.sforce.soap._2006._04.metadata.MetadataServiceLocator;
import com.sforce.soap._2006._04.metadata.PackageTypeMembers;
import com.sforce.soap._2006._04.metadata.RetrieveMessage;
import com.sforce.soap._2006._04.metadata.RetrieveRequest;
import com.sforce.soap._2006._04.metadata.RetrieveResult;
import com.sforce.soap._2006._04.metadata.RunTestFailure;
import com.sforce.soap._2006._04.metadata.RunTestsResult;
// Note that Axis generates a _package class, even though it is defined as Package
// in the WSDL. Other SOAP clients may generate a different name for the _package class.
import com.sforce.soap._2006._04.metadata._package;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.SessionHeader;
import com.sforce.soap.enterprise.SforceServiceLocator;
import com.sforce.soap.enterprise.SoapBindingStub;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
14
Quick Start Step 4: Walk Through the Sample Code
showMenu();
String choice = getUserInput("");
// Show the options to retrieve or deploy until user exits
while (choice != null && !choice.equals("99")) {
try {
if (choice.length() == 1 || choice.length() == 2) {
switch (new Integer(choice).intValue()) {
case 1:
retrieveZip();
break;
case 2:
deployZip();
break;
}
}
// show the menu again
showMenu();
} catch (Exception e) {
System.out.println("An unexpected error has occurred: "
+ e.getMessage());
e.printStackTrace();
}
//wait for the user input.
choice = getUserInput("");
}
}
}
if (asyncResult.getState() != AsyncRequestState.Completed) {
throw new Exception(asyncResult.getStatusCode() + " msg: " +
asyncResult.getMessage());
}
15
Quick Start Step 4: Walk Through the Sample Code
/**
* Read in the zip file contents into a byte array.
* @return byte[]
* @throws Exception - if cannot find the zip file to deploy
*/
private byte[] readZipFile()
throws Exception
{
// We assume here that you have a deploy.zip file.
// See the retrieve sample for how to retrieve a zip file.
File deployZip = new File(ZIP_FILE);
if (!deployZip.exists() || !deployZip.isFile())
throw new Exception("Cannot find the zip file to deploy. Looking for " +
deployZip.getAbsolutePath());
/**
* Print out any errors, if any, related to the deploy.
* @param result - DeployResult
*/
private void printErrors(DeployResult result)
{
DeployMessage messages[] = result.getMessages();
StringBuilder buf = new StringBuilder("Failures:\n");
for (DeployMessage message : messages) {
if (!message.isSuccess()) {
String loc = (message.getLineNumber() == null ? "" :
("(" + message.getLineNumber() + "," +
message.getColumnNumber() + ")"));
if (loc.length() == 0
&& !message.getFileName().equals(message.getFullName())) {
loc = "(" + message.getFullName() + ")";
}
buf.append(message.getFileName() + loc + ":" +
message.getProblem()).append('\n');
}
}
RunTestsResult rtr = result.getRunTestResult();
if (rtr.getFailures() != null) {
for (RunTestFailure failure : rtr.getFailures()) {
String n = (failure.getNamespace() == null ? "" :
(failure.getNamespace() + ".")) + failure.getName();
buf.append("Test failure, method: " + n + "." +
failure.getMethodName() + " -- " +
failure.getMessage() + " stack " +
failure.getStackTrace() + "\n\n");
}
}
if (rtr.getCodeCoverageWarnings() != null) {
for (CodeCoverageWarning ccw : rtr.getCodeCoverageWarnings()) {
buf.append("Code coverage issue");
if (ccw.getName() != null) {
String n = (ccw.getNamespace() == null ? "" :
(ccw.getNamespace() + ".")) + ccw.getName();
16
Quick Start Step 4: Walk Through the Sample Code
System.out.println(buf.toString());
}
if (asyncResult.getState() != AsyncRequestState.Completed) {
throw new Exception(asyncResult.getStatusCode() + " msg: " +
asyncResult.getMessage());
}
17
Quick Start Step 4: Walk Through the Sample Code
/**
* Helper method to copy from a readable channel to a writable channel,
* using an in-memory buffer.
*/
private void copy(ReadableByteChannel src, WritableByteChannel dest)
throws IOException
{
// use an in-memory byte buffer
ByteBuffer buffer = ByteBuffer.allocate(8092);
while (src.read(buffer) != -1) {
buffer.flip();
while(buffer.hasRemaining()) {
dest.write(buffer);
}
buffer.clear();
}
}
if (!unpackedManifest.exists() || !unpackedManifest.isFile())
throw new Exception("Should provide a valid retrieve manifest " +
"for unpackaged content. " +
"Looking for " + unpackedManifest.getAbsolutePath());
// Note that we populate the _package object by parsing a manifest file here.
// You could populate the _package based on any source for your
// particular application.
_package p = parsePackage(unpackedManifest);
request.setUnpackaged(p);
}
18
Quick Start Step 4: Walk Through the Sample Code
}
}
_package r = new _package();
r.setTypes(pd.toArray(new PackageTypeMembers[pd.size()]));
r.setVersion(API_VERSION + "");
return r;
} catch (ParserConfigurationException pce) {
throw new Exception("Cannot create XML parser", pce);
} catch (IOException ioe) {
throw new Exception(ioe);
} catch (SAXException se) {
throw new Exception(se);
}
}
/**
* Utility method to present options to retrieve or deploy.
* This method prints all the possible sample names to the console
* so that the user can select a particular sample by entering the corresponding
* number of the sample. Once the user enters the sample number, that particular
* sample will be invoked and run.
*/
private void showMenu() {
System.out.println(" 1: Retrieve");
System.out.println(" 2: Deploy");
System.out.println("99: Exit");
System.out.println(" ");
System.out.print("Enter 1 to retrieve, 2 to deploy, or 99 to exit: ");
}
/**
* The login call is used to obtain a token from Salesforce.
* This token must be passed to all other calls to provide
* authentication.
*/
private boolean login() throws ServiceException {
String userName = getUserInput("Enter username: ");
String password = getUserInput("Enter password: ");
/** Next, the sample client application initializes the binding stub.
*
* This is our main interface to the API for the Enterprise WSDL.
* The getSoap method takes an optional parameter,
* (a java.net.URL) which is the endpoint.
* For the login call, the parameter always starts with
* http(s)://www.salesforce.com. After logging in, the sample
* client application changes the endpoint to the one specified
* in the returned loginResult object.
*/
binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
19
Quick Start Step 4: Walk Through the Sample Code
exCode == ExceptionCode.LOGIN_DURING_RESTRICTED_TIME ||
exCode == ExceptionCode.ORG_LOCKED ||
exCode == ExceptionCode.PASSWORD_LOCKOUT ||
exCode == ExceptionCode.SERVER_UNAVAILABLE ||
exCode == ExceptionCode.TRIAL_EXPIRED ||
exCode == ExceptionCode.UNSUPPORTED_CLIENT) {
System.out.println("Please be sure that you have a valid username " +
"and password.");
} else {
// Write the fault code to the console
System.out.println(ex.getExceptionCode());
// Write the fault message to the console
System.out.println("An unexpected error has occurred." + ex.getMessage());
}
return false;
} catch (Exception ex) {
System.out.println("An unexpected error has occurred: " + ex.getMessage());
ex.printStackTrace();
return false;
}
// Check if the password has expired
if (loginResult.isPasswordExpired()) {
System.out.println("An error has occurred. Your password has expired.");
return false;
}
/** The sample client application now has an instance of the MetadataBindingStub
* that is pointing to the correct endpoint. Next, the sample client application
* sets a persistent SOAP header (to be included on all subsequent calls that
* are made with the SoapBindingStub) that contains the valid sessionId
* for our login credentials. To do this, the sample client application
* creates a new SessionHeader object and set its sessionId property to the
* sessionId property from the LoginResult object.
*/
// Create a new session header object and add the session id
// from the login return object
SessionHeader sh = new SessionHeader();
sh.setSessionId(loginResult.getSessionId());
/** Next, the sample client application calls the setHeader method of the
* SoapBindingStub to add the header to all subsequent method calls. This
* header will persist until the binding is destroyed or until the header
* is explicitly removed. The "SessionHeader" parameter is the name of the
* header to be added.
*/
// set the session header for subsequent call authentication
metadatabinding.setHeader(
new MetadataServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader", sh);
20
Quick Start Step 4: Walk Through the Sample Code
21
Chapter 3
Error Handling
The metadata API calls return error information that your client application can use to identify and resolve runtime errors. The metadata
API provides the following types of error handling:
• Since the metadata API uses the enterprise or partner WSDLs to authenticate, it uses SOAP fault messages defined in those WSDLs
for errors resulting from badly formed messages, failed authentication, or similar problems. Each SOAP fault has an associated
ExceptionCode. For more details, see "Error Handling" in the Force.com Web Services API Developer's Guide.
• For errors with create(), update(), and delete(), see the error status code in the statusCode field in the AsyncResult
object for the associated component. For sample code, see Java Sample Code for CRUD-Based Development on page 8.
• For errors with deploy(), see the problem and success fields in the DeployMessage object for the associated component. For
sample code, see Java Sample Code for File-Based Development on page 12.
• For errors with retrieve(), see the problem field in the RetrieveMessage object for the associated component. For sample code,
see Java Sample Code for File-Based Development on page 12.
22
Chapter 4
CRUD-Based Metadata Development
Use the CRUD-based metadata calls to create, update, or delete setup and configuration components for your organization or application.
These configuration components include custom objects, custom fields, and other configuration metadata. The metadata calls mimic the
behavior in the Salesforce user interface for creating, updating, or deleting components. Whatever rules apply there also apply to these calls.
Note: CRUD (create, read, update, delete) implies that there is a read call, but there is no equivalent read call for
CRUD-based development. If you want to read your metadata, you should use the retrieve() call, described in
File-Based Development on page 4.
Metadata calls are different from the core, synchronous API calls in the following ways:
• Metadata API calls are available in a separate WSDL. To download the WSDL, log into Salesforce, select Setup ➤ Develop ➤ API
and click the Download Metadata WSDL link.
• After logging in, you must send metadata API calls to the metadata API endpoint, which has a different URL than the Web Services
API. Retrieve the metadataServerUrl from the LoginResult returned by your Web Services API login() call. For more
information about the Web Services API, see the Force.com Web Services API Developer's Guide.
• There are three metadata calls with the same name as the corresponding core synchronous calls but with different signatures: create(),
update(), and delete(). There is also a special utility call, checkStatus(), which you use to poll for the completion of the
asynchronous call.
• Metadata calls are asynchronous, which means that the results are not returned in a single call; the API core calls are synchronous; the
results are returned in one call.
• The responses returned are all of type AsyncResult, unlike core API calls, which return different result types.
The following development workflow is common for CRUD-based metadata calls:
1. The logged-in user issues a metadata call, specifying all required fields to be created or updated.
2. Salesforce returns an AsyncResult object for each component you tried to create or update. The AsyncResult object is updated with status
information as the operation moves from a queue to completed or error state.
3. Call checkStatus() in a loop until the status values in AsyncResult indicate that all the create or update operations are completed.
Start with a wait time of one second between iterations of checkStatus() calls, and double the wait time each time you make a
subsequent call.
Note: There are two metadata calls that support declarative or file-based metadata development. For more information,
see Declarative Metadata Development.
checkStatus()
Checks the status of asynchronous metadata calls create(), update(), or delete(), or the declarative metadata calls
deploy() or retrieve().
23
CRUD-Based Metadata Development create()
Syntax
Usage
Use this call to check whether or not an asynchronous metadata call or declarative metadata call has completed.
Sample Code—Java
See Step 4: Walk Through the Sample Code for sample Java code using this call.
Arguments
Response
AsyncResult[]
See Also:
update()
delete()
create()
create()
Adds one or more new metadata components to your organization’s data. This call can be used to create any of the objects
that extend Metadata. For more details, see Metadata Components on page 62.
Syntax
Usage
Use this call to add one or more metadata components to your organization’s information.
Permissions
Your client application must be logged in with the "Modify All Data" permission.
Required Fields
Required fields are determined by the metadata components being created. For more information about specific component
types, see Metadata Components on page 62.
24
CRUD-Based Metadata Development AsyncResult
String Values
When storing values in string fields, the API trims any leading and trailing whitespace. For example, if the value of a label
field is entered as "MyObject ", the value is stored in the database as "MyObject".
Sample Code—Java
See Step 4: Walk Through the Sample Code for sample Java code using the create() call.
Arguments
Response
AsyncResult[]
See Also:
update()
delete()
checkStatus()
AsyncResult
Poll the values in this object to determine when an asynchronous metadata call has completed, and whether it was successful
or not. The asynchronous metadata calls create(), update(), and delete() return an array of AsyncResult objects.
Each element in the array corresponds to an element in the array of metadata components passed in the call.
25
CRUD-Based Metadata Development delete()
Use the checkStatus() call against each object to discover when the call is completed for that object. Salesforce updates
each AsyncResult object as the call completes, and errors, if any, are encountered.
Each AsyncResult object has the following properties:
statusCode StatusCode If an error occurred during the create(), update(), or delete() call, a
(enumeration of status code is returned, and the message corresponding to the status code is returned
type string) in the message field.
For a description of each StatusCode value, see "StatusCode" in the Force.com Web
Services API Developer's Guide.
delete()
Deletes one or more components from your organization’s data. This call can be used to delete any of the objects that extend
Metadata. For more details, see Metadata Components on page 62.
Syntax
Usage
Use this call to delete one or more components from your organization’s data.
Permissions
Your client application must be logged in with the "Modify All Data" permission.
26
CRUD-Based Metadata Development AsyncResult
• In addition, you might also need permission to access this component’s parent component.
• To ensure referential integrity, this call supports cascading deletions. If you delete a parent component, you delete its
children automatically, as long as each child component can be deleted.
• Unlike some standard objects, all metadata components can be deleted.
Sample Code—Java
Arguments
Response
AsyncResult[]
See Also:
create()
update()
checkStatus()
AsyncResult
Poll the values in this object to determine when an asynchronous metadata call has completed, and whether it was successful
or not. The asynchronous metadata calls create(), update(), and delete() return an array of AsyncResult objects.
Each element in the array corresponds to an element in the array of metadata components passed in the call.
27
CRUD-Based Metadata Development update()
Use the checkStatus() call against each object to discover when the call is completed for that object. Salesforce updates
each AsyncResult object as the call completes, and errors, if any, are encountered.
Each AsyncResult object has the following properties:
statusCode StatusCode If an error occurred during the create(), update(), or delete() call, a
(enumeration of status code is returned, and the message corresponding to the status code is returned
type string) in the message field.
For a description of each StatusCode value, see "StatusCode" in the Force.com Web
Services API Developer's Guide.
update()
Updates one or more components in your organization’s data. This call can be used to update any of the objects that extend
Metadata. For more details, see Metadata Components on page 62.
Syntax
Usage
Use this call to update one or more components. This call is analogous to the ALTER TABLE statement in SQL.
Permissions
Your client application must be logged in with the "Modify All Data" permission.
Updateable Objects
Unlike standard objects, all metadata components can be updated.
28
CRUD-Based Metadata Development update()
Required Fields
You must supply values for all the required fields in the component.
String Values
When storing values in string fields, the API trims any leading and trailing white space. For example, if the value of a label
field is entered as " MyObject ", the value is stored in the database as "MyObject".
Sample Code—Java
co.setNameField(nf);
29
CRUD-Based Metadata Development AsyncResult
Arguments
UpdateMetadata
One or more UpdateMetadata objects are defined in the metadata argument. This object can be used to update any of the
objects that extend Metadata. For more details, see Metadata Components on page 62. Each UpdateMetadata object has the
following fields:
Response
AsyncResult[]
See Also:
create()
delete()
checkStatus()
AsyncResult
Poll the values in this object to determine when an asynchronous metadata call has completed, and whether it was successful
or not. The asynchronous metadata calls create(), update(), and delete() return an array of AsyncResult objects.
Each element in the array corresponds to an element in the array of metadata components passed in the call.
Use the checkStatus() call against each object to discover when the call is completed for that object. Salesforce updates
each AsyncResult object as the call completes, and errors, if any, are encountered.
Each AsyncResult object has the following properties:
30
CRUD-Based Metadata Development AsyncResult
statusCode StatusCode If an error occurred during the create(), update(), or delete() call, a
(enumeration of status code is returned, and the message corresponding to the status code is returned
type string) in the message field.
For a description of each StatusCode value, see "StatusCode" in the Force.com Web
Services API Developer's Guide.
31
Chapter 5
Declarative Metadata Development
Use the file-based metadata API deploy() and retrieve() calls to facilitate Salesforce application development and deployment.
These two calls allow you to manage applications in your own source-code control system such as CVS or Perforce. You can create text files
that define components, such as custom objects, custom fields, s-controls, Apex code packages, and other Salesforce objects, and then deploy
these artifacts to a Salesforce organization.
The Salesforce supported tools, Force.com IDE and Force.com Migration Tool, use the file-based metadata API calls. Most developers
should use these tools instead of writing code that calls the metadata API directly. However, because the metadata API calls are designed to
manipulate text files, all of the behavior and concepts around the file directory structure, manifests, packaging, and file contents for components
such as custom objects and Apex-related components apply equally to the metadata API, Force.com IDE, and Force.com Migration Tool.
Declarative metadata development has no impact on packaging or the Force.com AppExchange. Packaging is still the mechanism by which
applications can be distributed to others. Declarative metadata development is instead designed for the following tasks:
• Team development of an application in a Developer Edition organization. When development and testing is completed, the application
is then distributed via Force.com AppExchange.
• Development of a custom application (or customization) in a Developer Edition organization or a sandbox. The application or customization
is then deployed into a production organization using the metadata metadata API as opposed to AppExchange packaging.
The existing asynchronous metadata API calls create(), update(), and delete() work with the same structures as the file-based
metadata API calls deploy() and retrieve().
Note that deploy() operates transactionally, so if something in the deployment fails, such as a problem with the code or a test run failure,
the entire transaction fails and your organization will be unchanged.
Every .zip file contains the manifest, a file named package.xml, and a set of directories that contain the components.
The manifest file defines the components you are trying to retrieve or deploy in the .zip file.
32
Declarative Metadata Development Working with the Zip File
The following is a sample package.xml manifest file. You can retrieve an individual component for a metadata type by specifying
its fullName field value in a members element, or you can also retrieve all components of a metadata type, by
using<members>*</members>.
Note how the standard Account object is retrieved by specifying it as a member of a CustomObject type. However,
standard objects cannot be retrieved by wildcard, they must be specified by name.
33
Declarative Metadata Development Working with the Zip File
The MyCustomField custom field in the MyCustomObject custom object is uniquely identified by its full name,
MyCustomObject__c.MyCustomField__c.
Component Folders
The following table lists a descriptive title for the component, the XML name used in the package.xml file for the metadata
type, the folder the component is retrieved into, whether or not the component may be retrieved with the wildcard (*) symbol
in package.xml, and a short description:
34
Declarative Metadata Development Working with the Zip File
35
Declarative Metadata Development deploy()
deploy()
Uses file representations of components to create, update, or delete those components in an organization.
Syntax
Usage
Use this call to take file representations of components and deploy them into an organization by creating, updating, or deleting
the components they represent.
Note: A .zip file can contain a maximum of 1500 files. If you are working with a large number of components, you
should use the listMetadata() call to identify the subset of files that you want to deploy, or you should deploy
batches of components in different .zip files.
36
Declarative Metadata Development deploy()
Permissions
Your client application must be logged in with the "Modify All Data" permission.
Sample Code—Java
This sample shows how to deploy components in a zip file. See the retrieve() sample code for details on how to retrieve
a zip file.
package com.doc.samples;
import java.io.*;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import com.sforce.soap._2006._04.metadata.AsyncRequestState;
import com.sforce.soap._2006._04.metadata.AsyncResult;
import com.sforce.soap._2006._04.metadata.MetadataBindingStub;
import com.sforce.soap._2006._04.metadata.MetadataServiceLocator;
import com.sforce.soap._2006._04.metadata.DeployOptions;
import com.sforce.soap._2006._04.metadata.DeployResult;
import com.sforce.soap._2006._04.metadata.DeployMessage;
import com.sforce.soap._2006._04.metadata.RunTestsResult;
import com.sforce.soap._2006._04.metadata.RunTestFailure;
import com.sforce.soap._2006._04.metadata.CodeCoverageWarning;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.SessionHeader;
import com.sforce.soap.enterprise.SforceServiceLocator;
import com.sforce.soap.enterprise.SoapBindingStub;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
/**
* Deploy a zip file of metadata components.
* Prerequisite: Have a deploy.zip file that includes a package.xml manifest file that
* details the contents of the zip file.
*/
public class DeploySample {
// binding for the Enterprise WSDL used for login() call
private SoapBindingStub binding;
// binding for the metadata WSDL used for create() and checkStatus() calls
private MetadataBindingStub metadatabinding;
37
Declarative Metadata Development deploy()
if (asyncResult.getState() != AsyncRequestState.Completed) {
throw new Exception(asyncResult.getStatusCode() + " msg: " +
asyncResult.getMessage());
}
/**
* Read in the zip file contents into a byte array.
* @return byte[]
* @throws Exception - if cannot find the zip file to deploy
*/
private byte[] readZipFile()
throws Exception
{
// We assume here that you have a deploy.zip file.
38
Declarative Metadata Development deploy()
/**
* Print out any errors, if any, related to the deploy.
* @param result - DeployResult
*/
private void printErrors(DeployResult result)
{
DeployMessage messages[] = result.getMessages();
StringBuilder buf = new StringBuilder("Failures:\n");
for (DeployMessage message : messages) {
if (!message.isSuccess()) {
String loc = (message.getLineNumber() == null ? "" :
("(" + message.getLineNumber() + "," +
message.getColumnNumber() + ")"));
if (loc.length() == 0
&& !message.getFileName().equals(message.getFullName())) {
loc = "(" + message.getFullName() + ")";
}
buf.append(message.getFileName() + loc + ":" +
message.getProblem()).append('\n');
}
}
RunTestsResult rtr = result.getRunTestResult();
if (rtr.getFailures() != null) {
for (RunTestFailure failure : rtr.getFailures()) {
String n = (failure.getNamespace() == null ? "" :
(failure.getNamespace() + ".")) + failure.getName();
buf.append("Test failure, method: " + n + "." +
failure.getMethodName() + " -- " +
failure.getMessage() + " stack " +
failure.getStackTrace() + "\n\n");
}
}
if (rtr.getCodeCoverageWarnings() != null) {
for (CodeCoverageWarning ccw : rtr.getCodeCoverageWarnings()) {
buf.append("Code coverage issue");
if (ccw.getName() != null) {
String n = (ccw.getNamespace() == null ? "" :
(ccw.getNamespace() + ".")) + ccw.getName();
buf.append(", class: " + n);
}
buf.append(" -- " + ccw.getMessage() + "\n");
}
}
System.out.println(buf.toString());
}
/**
* The login call is used to obtain a token from Salesforce.
39
Declarative Metadata Development deploy()
40
Declarative Metadata Development deploy()
*/
metadatabinding = (MetadataBindingStub)
new MetadataServiceLocator().getMetadata();
metadatabinding._setProperty(MetadataBindingStub.ENDPOINT_ADDRESS_PROPERTY,
loginResult.getMetadataServerUrl());
/** The sample client application now has an instance of the MetadataBindingStub
* that is pointing to the correct endpoint. Next, the sample client application
* sets a persistent SOAP header (to be included on all subsequent calls that
* are made with the SoapBindingStub) that contains the valid sessionId
* for our login credentials. To do this, the sample client application
* creates a new SessionHeader object and set its sessionId property to the
* sessionId property from the LoginResult object.
*/
// Create a new session header object and add the session id
// from the login return object
SessionHeader sh = new SessionHeader();
sh.setSessionId(loginResult.getSessionId());
/** Next, the sample client application calls the setHeader method of the
* SoapBindingStub to add the header to all subsequent method calls. This
* header will persist until the binding is destroyed or until the header
* is explicitly removed. The "SessionHeader" parameter is the name of the
* header to be added.
*/
// set the session header for subsequent call authentication
metadatabinding.setHeader(
new MetadataServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader", sh);
Arguments
DeployOptions
The following deployment options can be selected for this call:
41
Declarative Metadata Development deploy()
autoUpdatePackage boolean
If a file is in the .zip file but not specified in the
package.xml, specifies whether the file should be
automatically added to the package (true or not false).
A retrieve() is automatically issued with the updated
package.xml that includes the .zip file.
Do not set this argument for deployment to production
organizations.
checkOnly boolean
Indicates whether Apex classes and triggers are saved to
the organization as part of the deployment (false) or
not (true). Any errors or messages that would have been
issued are still generated. This parameter is similar to the
Salesforce Ant tool’s checkOnly parameter.
performRetrieve boolean
Indicates whether a retrieve() call is performed
immediately after the deployment (true) or not (false).
Set to true in order to retrieve whatever was just
deployed.
rollbackOnError boolean
Indicates whether any failure causes a complete rollback
(true) or not (false). If false, whatever set of actions
can be performed without errors are performed, and errors
are returned for the remaining actions. This parameter
must be set to true if you are deploying to a production
organization.
runAllTests boolean
If true, all Apex tests defined in the organization are run.
For deployment to a production organization, all tests are
automatically run regardless of this argument. If any of the
tests fail, the entire deployment will roll back.
<runTests>positive_test</runTests>
<runTests>negative_test</runTests>
<runTests>namespace.third_test</runTests>
singlePackage boolean Indicates whether the specified .zip file is returned and
the top level of the .zip file structure is skipped (true)
42
Declarative Metadata Development checkDeployStatus()
Response
AsyncResult
See Also:
retrieve()
describeMetadata()
listMetadata()
checkDeployStatus()
checkDeployStatus()
Checks the status of declarative metadata call deploy().
Syntax
Usage
checkDeployStatus is used as part of the process for deploying packaged or unpackaged components to an organization:
1. Issue a deploy() call to start the asynchronous deployment. An AsyncResult object is returned. If the call is completed,
the done field contains true. Most often, the call is not completed quickly enough to be noted in the first result. If it is
completed, note the value in the id field returned and skip the next step.
2. If the call is not complete , issue a checkStatus() call in a loop using the value in the id field of the AsyncResult
object returned by the deploy() call in the previous step. Check the AsyncResult object which is returned until the done
field contains true. The time taken to complete a deploy() call depends on the size of the zip file being deployed, so
a longer wait time between iterations should be used as the size of the zip file increases.
3. Issue a checkDeployStatus() call to obtain the results of the deploy() call, using the id value returned in the
first step.
Sample Code—Java
See the deploy() sample code for sample usage of this call.
Arguments
43
Declarative Metadata Development DeployResult
Response
DeployResult
See Also:
deploy()
DeployResult
The asynchronous metadata call checkDeployStatus() returns a DeployResult object, which contains information about
the success or failure of the associated deploy() call:
Usage
Contains information about the success or failure of a deploy() call.
DeployMessage
Each DeployResult object contains one or more DeployMessage objects. Each DeployMessage object contains information
about the deployment success or failure of a component in the deployment .zip file:
44
Declarative Metadata Development DeployResult
RunTestsResult
The call returns information about whether or not the compilation of the specified Apex was successful and if the unit tests
completed successfully.
A RunTestsResult object has the following properties:
codeCoverageWarnings CodeCoverageWarning[]
An array of one or more code coverage warnings for the test run. The
results include both the total number of lines that could have been
executed, as well as the number, line, and column positions of code that
was not executed.
failures RunTestFailure[]
An array of one or more RunTestFailure objects that contain information
about the unit test failures, if there are any.
numFailures int
The number of failures for the unit tests.
numTestsRun int
The number of unit tests that were run.
successes RunTestSuccess[]
An array of one or more RunTestSuccesses objects that contain
information about successes, if there are any.
totalTime double
The total cumulative time spent running tests. This can be helpful for
performance monitoring.
CodeCoverageResult
The RunTestsResult object contains this object. It contains information about whether or not the compile of the specified
Apex and run of the unit tests was successful.
45
Declarative Metadata Development DeployResult
id ID
The ID of the CodeLocation. The ID is unique within an organization.
locationsNotCovered CodeLocation[]
For each class or trigger tested, if any code is not covered, the line and column
of the code not tested, and the number of times the code was executed.
methodInfo CodeLocation[]
For each class or trigger tested, the method invocation locations, the number
of times the code was executed, and the total cumulative time spent in these
calls. This can be helpful for performance monitoring.
name string
The name of the class covered.
namespace string
The namespace that contained the unit tests, if one is specified.
numLocations int
The number of locations covered.
soqlInfo CodeLocation[]
For each class or trigger tested, the location of SOQL statements in the code,
the number of times this code was executed, and the total cumulative time
spent in these calls. This can be helpful for performance monitoring.
type string
Deprecated. Do not use. Used to specify class or package in early, unsupported
releases.
CodeCoverageWarning
The RunTestsResult object contains this object. It contains information about the Apex class which generated warnings.
This object has the following properties:
name string
The namespace that contained the unit tests, if one is specified.
namespace string
The namespace that contained the unit tests, if one is specified.
RunTestFailure
The RunTestsResult object returns information about failures during the unit test run.
46
Declarative Metadata Development DeployResult
message string
The failure message.
methodName string
The name of the method that failed.
name string
The name of the class that failed.
namespace string
The namespace that contained the class, if one was specified.
stackTrace string
The stack trace for the failure.
time double
The time spent running tests for this failed operation. This can be helpful for
performance monitoring.
type string
Deprecated. Do not use. Used to specify class or package in early, unsupported
releases.
RunTestSuccess
The RunTestsResult object returns information about successes during the unit test run.
This object has the following properties:
methodName string
The name of the method that succeeded.
name string
The name of the class that succeeded.
namespace string
The namespace that contained the unit tests, if one is specified.
time double
The time spent running tests for this operation. This can be helpful for
performance monitoring.
CodeLocation
The RunTestsResult object contains this object in a number of fields.
This object has the following properties:
47
Declarative Metadata Development retrieve()
line int
The line location of the Apex tested.
numExecutions int
The number of times the Apex was executed in the test run.
time double
The total cumulative time spent at this location. This can be helpful for
performance monitoring.
retrieve()
This call retrieves XML file representations of components in an organization.
Syntax
Usage
Use this call to retrieve file representations of components in an organization.
Note: A .zip file can contain a maximum of 1500 files. If you are working with a large number of components, you
should use the listMetadata() call to identify the subset of files that you want to retrieve, or you should retrieve
batches of components in different .zip files.
Permissions
Your client application must be logged in with the "Modify All Data" permission.
Sample Code—Java
This sample shows how to retrieve components into a zip file. See the deploy() sample code for details on how to deploy
a zip file.
48
Declarative Metadata Development retrieve()
Note: This sample was created using Apache Axis. The WSDL2Java utility generates a _package class, even though
the metadata type is defined as Package in the Metadata WSDL. Other SOAP clients may generate a different
name for the _package class.
package com.doc.samples;
import java.io.*;
import java.util.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.SessionHeader;
import com.sforce.soap.enterprise.SforceServiceLocator;
import com.sforce.soap.enterprise.SoapBindingStub;
import com.sforce.soap.enterprise.fault.ExceptionCode;
import com.sforce.soap.enterprise.fault.LoginFault;
import com.sforce.soap._2006._04.metadata.MetadataBindingStub;
import com.sforce.soap._2006._04.metadata.MetadataServiceLocator;
import com.sforce.soap._2006._04.metadata.AsyncResult;
import com.sforce.soap._2006._04.metadata.RetrieveRequest;
import com.sforce.soap._2006._04.metadata.AsyncRequestState;
import com.sforce.soap._2006._04.metadata.RetrieveResult;
import com.sforce.soap._2006._04.metadata.RetrieveMessage;
// Note that Axis generates a _package class, even though it is defined as Package
// in the WSDL. Other SOAP clients may generate a different name for the _package class.
import com.sforce.soap._2006._04.metadata._package;
import com.sforce.soap._2006._04.metadata.PackageTypeMembers;
49
Declarative Metadata Development retrieve()
sample.run();
}
if (asyncResult.getState() != AsyncRequestState.Completed) {
throw new Exception(asyncResult.getStatusCode() + " msg: " +
asyncResult.getMessage());
}
50
Declarative Metadata Development retrieve()
/**
* Helper method to copy from a readable channel to a writable channel,
* using an in-memory buffer.
*/
private void copy(ReadableByteChannel src, WritableByteChannel dest)
throws IOException
{
// use an in-memory byte buffer
ByteBuffer buffer = ByteBuffer.allocate(8092);
while (src.read(buffer) != -1) {
buffer.flip();
while(buffer.hasRemaining()) {
dest.write(buffer);
}
buffer.clear();
}
}
if (!unpackedManifest.exists() || !unpackedManifest.isFile())
throw new Exception("Should provide a valid retrieve manifest " +
"for unpackaged content. " +
"Looking for " + unpackedManifest.getAbsolutePath());
// Note that we populate the _package object by parsing a manifest file here.
// You could populate the _package based on any source for your
// particular application.
_package p = parsePackage(unpackedManifest);
request.setUnpackaged(p);
}
51
Declarative Metadata Development retrieve()
}
}
_package r = new _package();
r.setTypes(pd.toArray(new PackageTypeMembers[pd.size()]));
r.setVersion(API_VERSION + "");
return r;
} catch (ParserConfigurationException pce) {
throw new Exception("Cannot create XML parser", pce);
} catch (IOException ioe) {
throw new Exception(ioe);
} catch (SAXException se) {
throw new Exception(se);
}
}
/**
* The login call is used to obtain a token from Salesforce.
* This token must be passed to all other calls to provide
* authentication.
*/
private boolean login() throws ServiceException {
String userName = getUserInput("Enter username: ");
String password = getUserInput("Enter password: ");
/** Next, the sample client application initializes the binding stub.
*
* This is our main interface to the API for the Enterprise WSDL.
* The getSoap method takes an optional parameter,
* (a java.net.URL) which is the endpoint.
* For the login call, the parameter always starts with
* http(s)://www.salesforce.com. After logging in, the sample
* client application changes the endpoint to the one specified
* in the returned loginResult object.
*/
binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
52
Declarative Metadata Development retrieve()
/** The sample client application now has an instance of the MetadataBindingStub
* that is pointing to the correct endpoint. Next, the sample client application
* sets a persistent SOAP header (to be included on all subsequent calls that
* are made with the SoapBindingStub) that contains the valid sessionId
* for our login credentials. To do this, the sample client application
* creates a new SessionHeader object and set its sessionId property to the
* sessionId property from the LoginResult object.
*/
// Create a new session header object and add the session id
// from the login return object
SessionHeader sh = new SessionHeader();
sh.setSessionId(loginResult.getSessionId());
/** Next, the sample client application calls the setHeader method of the
* SoapBindingStub to add the header to all subsequent method calls. This
* header will persist until the binding is destroyed or until the header
* is explicitly removed. The "SessionHeader" parameter is the name of the
* header to be added.
*/
// set the session header for subsequent call authentication
metadatabinding.setHeader(
new MetadataServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader", sh);
53
Declarative Metadata Development checkRetrieveStatus()
Arguments
Response
AsyncResult
See Also:
deploy()
describeMetadata()
listMetadata()
RetrieveResult
checkRetrieveStatus()
Checks the status of declarative metadata call retrieve() and returns the zip file contents.
Syntax
Usage
checkRetrieveStatus is part of the procedure for retrieving metadata components from an organization. It is used
together with the checkStatus call which indicates when the asynchronous retrieve call has completed. Once
checkStatus indicates that the call is completed, call checkRetrieveStatus to get the zip file contents:
1. Issue a retrieve() call to start the asynchronous retrieval. An AsyncResult object is returned. If the call is completed,
the done field contains true. Most often, the call is not completed quickly enough to be noted in the result. If it is
completed, note the value in the id field returned and skip the next step.
2. If the call is not complete, issue a checkStatus() call in a loop using the value in the id field of the AsyncResult object
returned by the retrieve() call in the previous step. Check the AsyncResult object returned, until the done field
contains true. The time taken to complete a retrieve() call depends on the size of the zip file being deployed, so a
longer wait time between iterations should be used as the size of the zip file increases.
3. Issue a checkRetrieveStatus() call to obtain the results of the retrieve() call, using the id value returned in
the first step.
Sample Code—Java
See the retrieve() sample code for sample usage of this call.
54
Declarative Metadata Development RetrieveRequest
Arguments
Response
RetrieveResult
See Also:
retrieve()
RetrieveRequest
The RetrieveRequest object specified in a retrieve() call consists of the following properties:
Package
This extension of Metadata is specified in a RetrieveRequest as part of a retrieve() call. Use it to specify metadata
components to be retrieved.
55
Declarative Metadata Development RetrieveRequest
PackageTypeMembers
This object is specified in a Package component as part of a retrieve() call. Each PackageTypeMembers contains the
following arguments:
name string
The type of metadata component to be retrieved. For
example <name>CustomObject</name> will retrieve
one or more custom objects as specified in the
<members> element.
56
Declarative Metadata Development RetrieveResult
RetrieveResult
The metadata call retrieve() returns a RetrieveResult object, which contains information about the success or failure of
the associated retrieve() call.
Each RetrieveResult object has the following fields:
See Also:
retrieve()
RetrieveResult
FileProperties
This component contains information about the properties of each component in the .zip file, and the manifest file
package.xml. One object per component is returned. Note that this component does not contain information about any
associated metadata files in the .zip file, only the component files and manifest file. FileProperties contains the following
properties:
57
Declarative Metadata Development describeMetadata()
RetrieveMessage
RetrieveResult returns this object, which contains information about the success or failure of the retrieve() call. One
object per problem is returned:
describeMetadata()
This call retrieves the metadata which describes your organization. This information includes Apex classes and triggers, custom
objects, custom fields on standard objects, tab sets that define an app, and many other components.
Syntax
Arguments
Permissions
Your client application must be logged in with the "Modify All Data" permission.
58
Declarative Metadata Development DescribeMetadataResult
Sample Code—Java
Response
DescribeMetadataResult
See Also:
deploy()
retrieve()
listMetadata()
DescribeMetadataResult
The call describeMetadata() returns information about the organization that is useful for developers working with
declarative metadata.
Each DescribeMetadataResult object has the following properties:
59
Declarative Metadata Development listMetadata()
DescribeMetadataObject
This object is returned as part of the DescribeMetadataResult. Each DescribeMetadataObject has the following properties:
listMetadata()
This call retrieves property information about metadata components in your organization. Data is returned for the components
that match the criteria specified in the queries parameter. The queries array can contain up to three ListMetadataQuery
queries for each call. This call supports every component: both top-level, such as CustomObject and ApexClass, and child
types, such as CustomField and RecordType.
Syntax
Usage
This call is useful when you want to identify individual components in package.xml for a retrieve() call or if you want a
high-level view of particular metadata types in your organization. For example, you could use this call to return a list of names
of all the CustomObject or Layout components in your organization, and use this information to make a subsequent
retrieve() call to return a subset of these components. For more information about working with package.xml, see
Declarative Metadata Development on page 32.
Note: This is a synchronous call so the results are returned in one call. This differs from asynchronous calls, such as
retrieve(), where at least one subsequent call is needed to get the results.
60
Declarative Metadata Development ListMetadataQuery
Permissions
Your client application must be logged in with the "Modify All Data" permission.
Sample Code—Java
The sample code below lists information about your custom objects. The code assumes that the SOAP binding has already
been established.
Response
FileProperties
See Also:
deploy()
retrieve()
describeMetadata()
ListMetadataQuery
The ListMetadataQuery parameter specified in a listMetadata() call consists of the following properties:
61
Chapter 6
Metadata Components
Metadata components are not based on sObjects, as objects in the API are. Instead, they are based on metadata types, such as ApexClass and
CustomObject, which extend Metadata. A component is an instance of a metadata type.
Metadata components can be manipulated by asynchronous metadata API calls or declarative (or file-based) metadata API calls.
Most of the components can be accessed using Force.com IDE. Exceptions are noted in the description of the object.
Enumeration Fields
Some component fields have a data type that is an enumeration. An enumeration is the API equivalent of a picklist. The valid
values of the field are restricted to a strict set of possible values, all having the same data type. These values are listed in the
field description column for each enumeration field. See sortBy for an example of an enumeration field of type string. The
XML below shows a sample definition of an enumeration of type string in the WSDL.
<xsd:simpleType name="DashboardComponentFilter">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="RowLabelAscending"/>
<xsd:enumeration value="RowLabelDescending"/>
<xsd:enumeration value="RowValueAscending"/>
<xsd:enumeration value="RowValueDescending"/>
</xsd:restriction>
</xsd:simpleType>
Supported Calls
All of the metadata types are supported by the main calls, unless it is stated otherwise in the individual component sections.
The main metadata API calls are create(), delete(), update(), deploy(), retrieve(), listMetadata(),
62
Metadata Components ApexClass
and describeMetadata(). All other calls, such as checkStatus(), are considered utility calls as they are used in
conjunction with one of the main calls.
ApexClass
Represents an Apex class. An Apex class is a template or blueprint from which Apex objects are created. Classes consist of
other classes, user-defined methods, variables, exception types, and static initialization code. For more information, see the
Apex Language Reference. This metadata type extends the MetadataWithContent component and shares its fields.
Supported Calls
deploy(), retrieve(), describeMetadata(), listMetadata()
Note: This metadata type is not supported by the create(), delete(), and update() calls.
Version
Apex classes are available in API version 10.0 and later.
Fields
This metadata type contains the following fields:
content base64 The Apex class definition. Base 64-encoded binary data. Prior to making
an API call, client applications must encode the binary attachment data as
base64. Upon receiving a response, client applications must decode the
base64 data to binary. This conversion is usually handled for you by a
SOAP client. This field is inherited from the MetadataWithContent
component.
fullName string The Apex class name. The name can only contain characters, letters, and
the underscore (_) character, must start with a letter, and cannot end with
an underscore or contain two consecutive underscore characters. This field
is inherited from the Metadata component.
status ApexCodeUnitStatus
The current status of the Apex class. The following string values are valid:
(enumeration of type string)
• Active - The class is active.
• Deleted - The class is marked for deletion. This is useful for managed
packages, because it allows a class to be deleted when a managed
package is updated.
63
Metadata Components ApexComponent
MyHelloWorld.cls-meta.xml:
See Also:
ApexTrigger
ApexComponent
Represents a Visualforce component. For more information, see "What is Visualforce?" in the Salesforce online help. This
metadata type extends the MetadataWithContent component and shares its fields.
Version
Visualforce components are available in API version 12.0 and later.
Fields
This metadata type contains the following fields:
64
Metadata Components ApexPage
See Also:
ApexPage
ApexPage
Represents a Visualforce page. For more information, see "What is Visualforce?" in the Salesforce online help. This metadata
type extends the MetadataWithContent component and shares its fields.
Version
Visualforce pages are available in API version 11.0 and later.
Fields
This metadata type contains the following fields:
65
Metadata Components ApexTrigger
<apex:page>
<h1>Congratulations</h1>
This is your new Page.
</apex:page>
SampleApexPage.page-meta.xml:
See Also:
ApexComponent
ApexTrigger
Represents an Apex trigger. A trigger is an Apex script that executes before or after specific data manipulation language (DML)
events occur, such as before object records are inserted into the database, or after records have been deleted. For more
information, see "Managing Apex Triggers " in the Salesforce online help. This metadata type extends the MetadataWithContent
component and shares its fields.
Supported Calls
deploy(), retrieve(), describeMetadata(), listMetadata()
Note: This metadata type is not supported by the create(), delete(), and update() calls.
66
Metadata Components ApexTrigger
Apex triggers are stored in the triggers folder in the corresponding package directory.
Version
Triggers are available in API version 10.0 and later.
Fields
This metadata type contains the following fields:
MyHelloWorld.trigger-meta.xml:
See Also:
ApexClass
67
Metadata Components CustomApplication
CustomApplication
An application is a list of tab references, with a description and a logo. CustomApplication represents a custom application.
It extends the Metadata metadata type and inherits its fullName field.
Version
Custom applications are available in API version 10.0 and later.
Fields
This metadata type contains the following fields:
68
Metadata Components CustomDataType
<tab>Lead</tab>
<tab>Account</tab>
<tab>Contact</tab>
<tab>Myriad Publications</tab>
<tab>Document</tab>
<tab>report</tab>
</CustomApplication>
See Also:
CustomTab
CustomDataType
Reserved for future use.
CustomDataTypeComponent
Reserved for future use.
CustomLabels
This metadata type allows you to create custom labels that can be localized for use in different languages, countries, and
currencies. It extends the Metadata metadata type and inherits its fullName field. Custom labels are custom text values, up
to 1,000 characters in length, that can be accessed from Apex classes or Visualforce pages. For more information, see "What
are Custom Labels?" in the Salesforce online help.
Version
CustomLabels components are available in API version 14.0 and later.
Fields
69
Metadata Components CustomLabels
CustomLabel
This metadata type represents a custom label. It extends the Metadata metadata type and inherits its fullName field.
See Also:
Translations
70
Metadata Components CustomObject
CustomObject
Represents a custom object that stores data unique to your organization. It extends the Metadata metadata type and inherits
its fullName field. You must specify all relevant fields when you create or update a custom object. You cannot update a single
field on the object. For more information about custom objects, see "What is a Custom Object Record?" in the Salesforce
online help.
All metadata components have a fullName field, which must be fully specified for any custom object.
For example, the following are fully specified names:
Account
MyCustomObject__c
For sample Java code that creates a custom object, see Step 4: Walk Through the Sample Code on page 8 .
Version
Custom objects are available in API version 10.0 and later.
Fields
Unless otherwise noted, all fields are creatable, filterable, and nillable.
71
Metadata Components CustomObject
gender Gender
Gender of the name to support translation for languages
that indicate gender in nouns. Valid values are:
• Neuter
• Masculine
• Feminine
72
Metadata Components CustomObject
sharingReasons SharingReason[] The reasons why the custom object is being shared.
sharingRecalculations SharingRecalculation[] A list of custom sharing recalculations associated with
the custom object.
startsWith StartsWith (enumeration of Indicates whether the name starts with a vowel,
type string) consonant, or is a special character. This is used for
languages where words need different treatment
depending on the first character. Valid values are listed
in StartsWith on page 95.
validationRules ValidationRule[] An array of one or more validation rules on this object.
webLinks Weblink[] An array of one or more weblinks defined for the object.
<label>Comments</label>
<length>32000</length>
<type>LongTextArea</type>
<visibleLines>30</visibleLines>
</fields>
<label>MyFirstObject</label>
73
Metadata Components CustomField
<nameField>
<label>MyFirstObject Name</label>
<type>Text</type>
</nameField>
<pluralLabel>MyFirstObjects</pluralLabel>
<sharingModel>ReadWrite</sharingModel>
</CustomObject>
See Also:
CustomField
Metadata
Picklist
SearchLayouts
Weblink
CustomObjectTranslation
ListView
CustomField
Represents the metadata associated with a custom field. Use this metadata type to create, update, or delete custom field
definitions. It extends the Metadata metadata type and inherits its fullName field.
You must specify the full name whenever you create or update a custom field. For example, a custom field on a custom object:
MyCustomObject__c.MyCustomField__c
Account.MyAcctCustomField__c
<types>
<members>MyCustomObject__c.MyCustomField__c</members>
<members>Account.MyCustomAccountField__c</members>
<name>CustomField</name>
</types>
Version
Custom fields are available in API version 10.0 and later.
74
Metadata Components CustomField
Fields
Unless otherwise noted, all fields are creatable, filterable, and nillable.
defaultValue string
If specified, represents the default value of the field.
description string
Description of the field.
displayFormat string
The display format.
externalId boolean
Indicates whether the field is an external ID field (true)
or not (false).
formula string
If specified, represents a formula on the field.
formulaTreatBlankAs TreatBlanksAs
Indicates how to treat blanks in a formula. Valid values are
(enumeration of type
BlankAsBlank and BlankAsZero.
string)
fullName string Inherited from Metadata, this field is not defined in the
WSDL for this metadata type. It must be specified when
creating, updating, or deleting. See create() to see an
example of this field specified for a call.
This value cannot be null.
maskType EncryptedFieldMaskType For encrypted text fields, specifies the format of the masked
(enumeration of type and unmasked characters in the field. Valid values are
string) enumerated in EncryptedFieldMaskType For more
information on encrypted fields, see "About Encrypted
Custom Fields" in the Salesforce online help.
75
Metadata Components CustomField
summaryFilterItems FilterItem[] Represents the set of filter conditions for this field if it is
a summary field. This field will be summed on the child
if the filter conditions are met.
summaryForeignKey string Represents the master-detail field on the child that defines
the relationship between the parent and the child.
summaryOperation SummaryOperations Represents the sum operation to be performed. Valid values
(enumeration of type are enumerated in SummaryOperations.
string)
trackHistory boolean Indicates whether history tracking is enabled for the field
(true) or not (false). For more information, see
"Tracking Field History" in the Salesforce online help.
76
Metadata Components CustomField
Custom fields use additional data types. For more information, see Metadata Field Types on page 94.
EncryptedFieldMaskChar
This field type is used in maskChar. It is a string with two valid values: asterisk or X. For more information on encrypted
fields, see About Encrypted Custom Fields in the Salesforce online help.
EncryptedFieldMaskType
This field type is used in maskType. Valid values are:
all
All characters in the field are hidden. This option is equivalent to the Mask All Characters option in Salesforce.
creditCard
The first 12 characters are hidden and the last four display. This option is equivalent to the Credit Card Number
option in Salesforce.
ssn
The first five characters are hidden and the last four display. This option is equivalent to the Social Security Number
option in Salesforce.
77
Metadata Components CustomField
lastFour
All characters are hidden but the last four display. This option is equivalent to the Last Four Characters Clear
option in Salesforce.
sin
All characters are hidden but the last four display. This option is equivalent to the Social Insurance Number option
in Salesforce.
nino
All characters are hidden. Salesforce automatically inserts spaces after each pair of characters if the field contains nine
characters. This option is equivalent to the National Insurance Number option in Salesforce.
For more information on encrypted fields, see About Encrypted Custom Fields in the Salesforce online help.
FilterItem
FilterItem is used in summaryFilterItems. It contains the following properties:
operation FilterOperation
Represents the filter operation for this filter item. Valid values
(enumeration of
are enumerated in FilterOperation.
type string)
value string
Represents the value of the filter item being operated upon, for
example, if the filter is my_number_field__c > 1, the
value of value is 1.
FilterOperation
This is an enumeration of type string that lists different filter operations. Valid values are:
• equals
• notEqual
• lessThan
• greaterThan
• lessOrEqual
• greaterOrEqual
• contains
• notContain
• startsWith
• includes
• excludes
SummaryOperations
Represents the type of a summaryOperation. Valid values are:
• Count
• Min
78
Metadata Components ListView
• Max
• Sum
Java Sample
The following Java sample illustrates how to specify a picklist and set of values:
<label>Comments</label>
<length>32000</length>
<type>LongTextArea</type>
<visibleLines>30</visibleLines>
</fields>
....
</CustomObject>
See Also:
CustomObject
Picklist
Metadata
ListView
List views allow you to see a filtered list of custom objects. For more information, see "Creating Custom List Views" in the
Salesforce online help. It extends the Metadata metadata type and inherits its fullName field.
Note: The ListView component only supports list views for custom objects. It does not support list views for standard
objects, such as accounts or contacts.
Version
ListView components are available in API version 14.0 and later.
79
Metadata Components ListView
Fields
ListViewFilter
ListViewFilter represents a filter line item.
FilterScope
This is an enumeration of type string that represents the filtering criteria for the records. The valid values are listed in the table
below:
80
Metadata Components Picklist
See Also:
CustomObject
Picklist
Represents a picklist definition for a custom field in a custom object. Note that picklist values cannot be deleted from a picklist
that has been saved to your organization, since data rows might exist that would need to be interactively remapped.
Version
Picklists are available in API version 12.0 and later.
81
Metadata Components Picklist
Fields
Picklist contains the following fields:
sorted boolean
Required. Indicates whether values should be sorted (true), or
not (false).
PicklistValue
This metadata type defines a value in the picklist and specifies whether this value is the default value. It extends the Metadata
metadata type and inherits its fullName field.
Java Sample
The following sample uses a picklist. For a complete sample of using a picklist with record types and profiles, see Profile on
page 133.
// Create a picklist
Picklist expenseStatus = new Picklist();
PicklistValue unsubmitted = new PicklistValue();
unsubmitted.setFullName("Unsubmitted");
PicklistValue submitted = new PicklistValue();
submitted.setFullName("Submitted");
PicklistValue approved = new PicklistValue();
approved.setFullName("Approved");
PicklistValue rejected = new PicklistValue();
rejected.setFullName("Rejected");
expenseStatus.setPicklistValues(new PicklistValue[] {unsubmitted, submitted, approved,
rejected});
82
Metadata Components Picklist
expenseStatusField.setFullName("ExpenseReport__c.ExpenseStatus__c");
expenseStatusField.setLabel("Expense Report Status");
expenseStatusField.setType(FieldType.Picklist);
expenseStatusField.setPicklist(expenseStatus);
create(expenseStatusField);
83
Metadata Components RecordType
<picklistValues>
<fullName>PT Cruiser</fullName>
<controllingFieldValues>Chrysler</controllingFieldValues>
<default>false</default>
</picklistValues>
<picklistValues>
<fullName>Pacifica</fullName>
<controllingFieldValues>Chrysler</controllingFieldValues>
<default>false</default>
</picklistValues>
<picklistValues>
<fullName>Accord</fullName>
<controllingFieldValues>Honda</controllingFieldValues>
<default>false</default>
</picklistValues>
<picklistValues>
<fullName>Civic</fullName>
<controllingFieldValues>Honda</controllingFieldValues>
<default>false</default>
</picklistValues>
<picklistValues>
<fullName>Prius</fullName>
<controllingFieldValues>Toyota</controllingFieldValues>
<default>false</default>
</picklistValues>
<picklistValues>
<fullName>Camry</fullName>
<controllingFieldValues>Toyota</controllingFieldValues>
<default>false</default>
</picklistValues>
<sorted>false</sorted>
</picklist>
<type>Picklist</type>
</fields>
....
</CustomObject>
RecordType
Represents the metadata associated with a record type. Record types allow you to offer different business processes, picklist
values, and page layouts to different users based on their profiles. For more information, see "Managing Record Types" in the
Salesforce online help. Use this metadata type to create, update, or delete record type definitions for a custom object. It extends
the Metadata metadata type and inherits its fullName field.
Note: Retrieving a component of this metadata type in a project makes the component appear in the Profile component
as well.
Version
Record types are available in API version 12.0 and later.
Fields
84
Metadata Components RecordType
label string Required. Descriptive label for the record type. The list of characters
allowed in the fullName field has been reduced for versions 14.0
and later. This field contains the value contained in the fullName
field before version 14.0.
picklistValues RecordTypePicklistValue[] Represents a set of values for a picklist.
RecordTypePicklistValue
RecordTypePicklistValue represents the combination of picklists and valid values that define a record type:
Java Sample
The following sample uses two record types. For the complete sample the includes profiles and picklists, see Profile on page
133.
// Employees and managers have different access to the state of the expense sheet
RecordType edit = new RecordType();
edit.setFullName("ExpenseReport__c.Edit");
RecordTypePicklistValue editStatuses = new RecordTypePicklistValue();
editStatuses.setPicklist("ExpenseStatus__c");
editStatuses.setValues(new PicklistValue[] {unsubmitted, submitted});
edit.setPicklistValues(new RecordTypePicklistValue[] {editStatuses});
create(edit);
85
Metadata Components SearchLayouts
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
. . .
<recordTypes>
<fullName>My First Recordtype</fullName>
</recordTypes>
. . .
</CustomObject>
SearchLayouts
Represents the metadata associated with the Search Layouts related list for a custom object. You can customize which custom
object fields display for users in search results, in lookup dialogs, and in the key lists on custom tab home pages. For more
information, see "Customizing Search Layouts for Custom Objects" in the Salesforce online help.
Version
Search layouts are available in API version 14.0 and later.
Fields
lookupDialogsAdditionalFields string[] The list of fields displayed in a lookup dialog for the
custom object. The name field is mandatory and is always
displayed as the first column header, so it is not included
in this list; all additional fields are included. The field
name relative to the custom object name, for example
MyCustomField__c, is specified for each custom field.
86
Metadata Components SearchLayouts
lookupFilterFields string[] The list of fields that can be used to filter enhanced
lookups for the custom object. Enhanced lookups are
optionally enabled by your administrator. The field name
relative to the custom object name, for example
MyCustomField__c, is specified for each custom field.
searchFilterFields string[] The list of fields that can be used to filter a search for
the custom object. The field name relative to the custom
object name, for example MyCustomField__c, is
specified for each custom field.
This field is equivalent to the Search Filter Fields
in the Search Layouts related list on the custom object
detail page in the application user interface.
87
Metadata Components SharingReason
See Also:
CustomObject
SharingReason
Apex managed sharing allows developers to use Apex to programmatically share custom objects. When you use Apex managed
sharing to share a custom object, only users with the "Modify All Data" permission can add or change the sharing on the
custom object's record, and the sharing access is maintained across record owner changes. A sharing reason is used to indicate
why sharing was implemented for a custom object. For more information, see "Managing the Sharing Settings" in the Salesforce
online help.
Use SharingReason to create, update, or delete sharing reason definitions for a custom object. It extends the Metadata metadata
type and inherits its fullName field.
Version
Sharing reasons are available in API version 14.0 and later.
88
Metadata Components SharingRecalculation
Fields
label string Required. Descriptive label for the sharing reason. Maximum of 40
characters.
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
. . .
<sharingReasons>
<fullName>recruiter__c</fullName>
<label>Recruiter</label>
</sharingReasons>
. . .
</CustomObject>
SharingRecalculation
Developers can write Apex classes that recalculate the Apex managed sharing for a specific custom object. For more information,
see "Recalculating Apex Managed Sharing" in the Salesforce online help.
Version
Sharing recalculations are available in API version 14.0 and later.
Fields
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
. . .
<sharingRecalculations>
<className>RecruiterRecalculation</className>
</sharingRecalculations>
89
Metadata Components ValidationRule
. . .
</CustomObject>
ValidationRule
Represents a validation rule, which is used to verify that the data a user enters in a record is valid and can be saved. A validation
rule contains a formula or expression that evaluates the data in one or more fields and returns a value of true or false.
Validation rules also include an error message that your client application can display to the user when the rule returns a value
of true due to invalid data. It extends the Metadata metadata type and inherits its fullName field.
Version
Validation rules are available in API version 12.0 and later.
Fields
90
Metadata Components Weblink
<referenceTo>Cat__c</referenceTo>
<relationshipName>Cats</relationshipName>
<type>Lookup</type>
</fields>
<label>Cat</label>
<nameField>
<label>Cat Name</label>
<type>Text</type>
</nameField>
<pluralLabel>Cats</pluralLabel>
<sharingModel>ReadWrite</sharingModel>
<validationRules>
<fullName>CatsRule</fullName>
<active>true</active>
<errorConditionFormula>OR(Name = 'Milo',Name =
'Moop')</errorConditionFormula>
<validationMessage>Name must be that of one of my cats</validationMessage>
</validationRules>
</CustomObject>
Weblink
Represents a Weblink defined in a custom object. It extends the Metadata metadata type and inherits its fullName field.
Version
Weblinks are available in API version 12.0 and later.
Fields
The Weblink definition contains the following fields.
fullName string The name of the weblink with white spaces and special characters
escaped for validity. The name can only contain characters, letters,
and the underscore (_) character, must start with a letter, and cannot
end with an underscore or contain two consecutive underscore
characters.
Inherited from the Metadata component, this field is not defined
in the WSDL for this component. It must be specified when creating,
updating, or deleting. See create() to see an example of this field
specified for a call.
91
Metadata Components Weblink
page string If the value of linkType is page, this field represents the
Visualforce page; otherwise, this field should not be specified.
position WebLinkPosition If the openType is newWindow, how the new window should be
(enumeration of type string) displayed. Otherwise this field should not be specified.
Valid values:
• fullScreen
• none
• topLeft
92
Metadata Components Weblink
Java Sample
93
Metadata Components Metadata Field Types
See Also:
HomePageComponent
HomePageLayout
CustomPageWebLink
FieldType Custom field Indicates the type of a custom field. Valid values are:
• AutoNumber
• Lookup
• MasterDetail
• Checkbox
• Currency
• Date
• DateTime
• Email
94
Metadata Components CustomObjectTranslation
Picklist Custom field Represents a picklist, a set of labels and values that can be selected from a picklist.
SharingModel Custom object Represents the sharing model for the custom object or custom field. Valid values are:
Custom field • Private
• Read
• ReadWrite
StartsWith Custom object Indicates whether the name starts with a vowel, consonant, or is a special character.
This is used for languages where words need different treatment depending on the first
Custom field
character. Valid values are:
• Consonant
• Vowel
• Special
TreatBlanksAs Custom field Indicates how blanks should be treated. Valid values are:
• BlankAsBlank
• BlankAsZero
CustomObjectTranslation
This metadata type allows you to translate custom objects for a variety of languages. It extends the Metadata metadata type
and inherits its fullName field. The ability to translate component labels is part of the Translation Workbench. For more
information, see "Setting Up Translation Workbench" in the Salesforce online help.
95
Metadata Components CustomObjectTranslation
Version
CustomObjectTranslation components are available in API version 14.0 and later.
Fields
gender Gender
Gender of the name to support translation for languages
that indicate gender in nouns. Valid values are:
• Neuter
• Masculine
• Feminine
96
Metadata Components CustomObjectTranslation
CustomFieldTranslation
CustomFieldTranslation contains details for a custom field translation. For more details, see CustomField on page 74.
LayoutTranslation
LayoutTranslation contains details for a page layout translation. For more details, see Fields on page 122.
LayoutSectionTranslation
LayoutSectionTranslation contains details for a page layout section translation. For more details, see LayoutSection on page
123.
ObjectNameCaseValue
ObjectNameCaseValue supports multiple cases and definitions of the custom object name to allow usage in various grammatical
contexts.
97
Metadata Components CustomObjectTranslation
caseType CaseType (enumeration of The case of the custom object name. The valid values are:
type string) • Ablative
• Accusative
• Adessive
• Allative
• Causalfinal
• Dative
• Delative
• Distributive
• Elative
• Essive
• Essiveformal
• Genitive
• Illative
• Inessive
• Instrumental
• Locative
• Nominative
• Objective
• Partitive
• Prepositional
• Subjective
• Sublative
• Superessive
• Termanative
• Translative
• Vocative
98
Metadata Components CustomObjectTranslation
PicklistValueTranslation
PicklistValueTranslation contains details for a picklist value translation. For more details, see Picklist on page 81.
RecordTypeTranslation
RecordTypeTranslation contains details for a record type name translation. For more details, see RecordType on page 84.
SharingReasonTranslation
SharingReasonTranslation contains details for a sharing reason translation. For more details, see SharingReason on page 88.
ValidationRuleTranslation
ValidationRuleTranslation contains details for a validation rule translation. For more details, see ValidationRule on page 90.
WebLinkTranslation
WebLinkTranslation contains details for a web link translation. For more details, see Weblink on page 91.
99
Metadata Components CustomPageWebLink
See Also:
CustomObject
Translations
CustomPageWebLink
Represents a web link defined in a home page component. It extends the Metadata metadata type and inherits its fullName
field. All other web links are stored as a Weblink in a CustomObject.
Version
CustomPageWebLinks are available in API version 13.0 and later.
100
Metadata Components CustomPageWebLink
Fields
The CustomPageWebLink definition has the following fields:
fullName string The name used as a unique identifier for API access. The fullName
can only contain characters, letters, and the underscore (_) character,
must start with a letter, and cannot end with an underscore or contain
two consecutive underscore characters.
hasMenubar boolean If the openType is newWindow, whether to show the browser
menu bar for the window (true or not (false). Otherwise this
field should not be specified.
hasScrollbars boolean If the openType is newWindow, whether to show the scroll bars
for the window (true) or not (false). Otherwise this field should
not be specified.
hasToolbar boolean If the openType is newWindow, whether to show the browser
toolbar for the window (true) or not (false). Otherwise this field
should not be specified.
height int Height in pixels of the window opened by this Weblink. Required
if the openType is newWindow, otherwise should not be specified
isResizable boolean If the openType is newWindow, whether to allow resizing of the
window (true) or not (false). Otherwise this field should not
be specified.
linkType WebLinkType (enumeration Required. Represents whether the content of this Weblink is
of type string) specified by a URL, an sControl, or by a JavaScript code block.
Valid values:
• url
• sControl
• javascript
• page
101
Metadata Components CustomPageWebLink
page string If the value of linkType is page, this field represents the
Visualforce page; otherwise, this field should not be specified.
position WebLinkPosition If the openType is newWindow, how the new window should be
(enumeration of type string) displayed. Otherwise this field should not be specified.
Valid values:
• fullScreen
• none
• topLeft
Java Sample
102
Metadata Components CustomSite
weblink.setLinktype(WebLinkType.url);
weblink.setOpentype(WebLinkWindowType.newWindow);
weblink.setHeight(600);
weblink.setWidth(600);
weblink.setShowsLocation(false);
weblink.setHasScrollbars(true);
weblink.setHasToolbar(false);
weblink.setHasMenubar(false);
weblink.setShowsStatus(false);
weblink.setIsResizable(true);
weblink.setPosition(WebLinkPosition.none);
weblink.setMasterLabel("google");
weblink.setDisplayType(WebLinkDisplayType.link);
weblink.setRequireRowSelection(true);
See Also:
HomePageComponent
HomePageLayout
Weblink
CustomSite
Force.com Sites enables you to create public websites and applications that are directly integrated with your Salesforce
organization—without requiring users to log in with a username and password. For more information, see "About Force.com
Sites" in the Salesforce online help.
Note: CustomSite does not support syndication feeds at this time.
103
Metadata Components CustomSite
Version
Force.com CustomSite components are available in API version 14.0 and later.
Fields
104
Metadata Components CustomSite
See Also:
Portal
105
Metadata Components CustomTab
CustomTab
A custom tab is a user interface component you create to display custom object data or other web content embedded in the
application. When a tab displays a custom object, the tab name is the same as the custom object name; for page, s-control, or
URL tabs, the name is arbitrary. For more information, see "What is a Custom Tab?" in the Salesforce online help. It extends
the Metadata metadata type and inherits its fullName field.
Version
Tabs are available in API version 10.0 and later.
Fields
This metadata type contains the following fields:
106
Metadata Components CustomTab
splashPageLink string The custom link used as the introductory splash page when users
click the tab. References a HomePageComponent.
url string The URL for the external web-page to embed in this tab.
Only one of these fields should have a value set:
• customObject
• page
• scontrol
• url
urlEncodingKey Encoding The default encoding setting is Unicode: UTF-8. Change it if you
(enumeration of are passing information to a URL that requires data in a different
type string) format. This option is available when the value URL is selected in
the tab type.
107
Metadata Components Dashboard
<mobileReady>true</mobileReady>
<motif>Custom53: Bell</motif>
<url>http://www.myriadpubs.com</url>
<urlEncodingKey>UTF-8</urlEncodingKey>
</CustomTab>
See Also:
CustomApplication
Dashboard
Dashboards are visual representations of data that allow you to see key metrics and performance at a glance. It extends the
Metadata metadata type and inherits its fullName field. For more information, see "Editing Dashboards" in the Salesforce
online help.
Version
Dashboard components are available in API version 14.0 and later.
Fields
backgroundStartColor string Required. The starting color for the gradient color change
on the dashboard's charts. See backgroundEndColor for
more information. The color is in hexadecimal format; for
example #FF6600.
description string Description for the dashboard. Maximum of 255 characters.
fullName string Inherited from Metadata, this field is not defined in the
WSDL for this metadata type. It must be specified when
108
Metadata Components Dashboard
textColor string Required. Color of the text on each chart in the dashboard.
The color is in hexadecimal format; for example #FF6600.
title string Required. The dashboard title.
titleColor string Required. Color of the titles on each dashboard component.
The color is in hexadecimal format; for example #FF6600.
titleSize int Required. Size of characters in title text. For example, a
value of 12 indicates 12pt text.
DashboardComponentSection
DashboardComponentSection represents one of the sections or columns in a dashboard.
DashboardComponentSize
DashboardComponentSize is an enumeration of type string that lists different size categories. The valid values are listed in
the table below:
109
Metadata Components Dashboard
DashboardComponent
A dashboard consists of a group of different components or elements that display data. Each component can use a custom
report or a custom s-control as their data source to display corporate metrics or key performance indicators. You can create
several dashboard components and display them all in one dashboard aligned in up to three columns.
chartAxisRangeMax double The maximum axis range to be displayed. This only applies
to bar and line charts in which the manual axis range is
selected for the chartAxisRange field.
chartAxisRangeMin double The minimum axis range to be displayed. This only applies
to bar and line charts in which the manual axis range is
selected for the chartAxisRange field.
componentType DashboardComponentType Required. Dashboard component type. The valid values
(enumeration of type string) are:
• Bar
• BarGrouped
• BarStacked
• BarStacked100
• Column
• ColumnGrouped
• ColumnStacked
• ColumnStacked100
• gauge
• Line
• lineCumulative
• LineGrouped
• lineGroupedCumulative
• Metric
• Pie
• Scontrol
• Table
110
Metadata Components Dashboard
drillDownUrl string If the component is a chart, you can embed a URL other
than the source report to allow users to click the dashboard
component and drill down to another dashboard, report,
record detail page, or another system that uses a web
interface.
footer string Footer displayed at the bottom of the dashboard component.
Maximum of 255 characters.
gaugeMax double The maximum value on a gauge. A gauge is used to see how
far you are from reaching a goal. It looks like a speedometer
in a car.
gaugeMin double The minimum value on a gauge.
header string Header displayed at the top of the dashboard component.
Maximum of 80 characters.
indicatorBreakpoint1 double The value that separates the indicatorLowColor from
the indicatorMiddleColor on the dashboard.
indicatorBreakpoint2 double The value that separates the indicatorMiddleColor
from the indicatorHighColor on the dashboard.
indicatorHighColor string The color representing a high number range on the gauge.
indicatorLowColor string The color representing a low number range on the gauge.
indicatorMiddleColor string The color representing a medium number range on the
gauge.
legendPosition ChartLegendPosition
The location of the legend with respect to the chart. The
(enumeration of type string)
valid values are:
• LEGEND_NONE
• LEGEND_RIGHT
• LEGEND_BOTTOM
111
Metadata Components Dashboard
112
Metadata Components Dashboard
<scontrolHeightInPixels>300</scontrolHeightInPixels>
</leftComponents>
<middleColumnSize>medium</middleColumnSize>
<middleComponents>
<componentType>scontrol</componentType>
<footer>scontrol</footer>
<header>scontrol</header>
<scontrol>helloSControl</scontrol>
<scontrolHeightInPixels>300</scontrolHeightInPixels>
</middleComponents>
<rightColumnSize>medium</rightColumnSize>
<rightComponents>
<componentType>scontrol</componentType>
<footer>scontrol</footer>
<header>scontrol</header>
<scontrol>helloSControl</scontrol>
<scontrolHeightInPixels>300</scontrolHeightInPixels>
</rightComponents>
<rightComponents>
<componentType>table</componentType>
<report>reportFolder/TPS_Report</report>
<footer>table</footer>
<header>table</header>
<indicatorBreakpoint1>20.0</indicatorBreakpoint1>
<indicatorBreakpoint2>30.0</indicatorBreakpoint2>
<indicatorHighColor>#54C254</indicatorHighColor>
<indicatorLowColor>#C25454</indicatorLowColor>
<indicatorMiddleColor>#C2C254</indicatorMiddleColor>
<title>table</title>
</rightComponents>
<rightComponents>
<componentType>metric</componentType>
<report>reportFolder/TPS_Report</report>
<drillDownUrl>http://plywood.com</drillDownUrl>
<footer>metric</footer>
<header>metric</header>
<indicatorBreakpoint1>5.0</indicatorBreakpoint1>
<indicatorBreakpoint2>500.0</indicatorBreakpoint2>
<indicatorHighColor>#54C254</indicatorHighColor>
<indicatorLowColor>#C25454</indicatorLowColor>
<indicatorMiddleColor>#C2C254</indicatorMiddleColor>
<metricLabel>metriclabel</metricLabel>
</rightComponents>
<rightComponents>
<componentType>gauge</componentType>
<report>reportFolder/TPS_Report</report>
<footer>gauge</footer>
<gaugeMax>30.0</gaugeMax>
<gaugeMin>0.0</gaugeMin>
<header>gauge</header>
<indicatorBreakpoint1>10.0</indicatorBreakpoint1>
<indicatorBreakpoint2>20.0</indicatorBreakpoint2>
<indicatorHighColor>#54C254</indicatorHighColor>
<indicatorLowColor>#C25454</indicatorLowColor>
<indicatorMiddleColor>#C2C254</indicatorMiddleColor>
<title>gauge</title>
</rightComponents>
<runningUser>user@salesforcecustomer.com</runningUser>
<textColor>#000000</textColor>
<title>My Dashboard</title>
<titleColor>#000000</titleColor>
113
Metadata Components Document
<titleSize>12</titleSize>
</Dashboard>
See Also:
Folder
Report
Document
Represents a Document. All documents must be in a document folder, for example sampleFolder/TestDocument.txt. This
metadata type extends the MetadataWithContent component and shares its fields.
Currently, users are not able to export document metadata to a local file system using the Force.com IDE.
Version
Documents are available in API version 10.0 and later.
Fields
This metadata type contains the following fields:
114
Metadata Components EmailTemplate
For a sample of using a document within a folder, see Folder on page 118.
See Also:
Folder
EmailTemplate
Represents an email template. This metadata type extends the MetadataWithContent component and shares its fields.
Version
Email templates are available in API version 12.0 and later.
Fields
This metadata type contains the following fields:
115
Metadata Components EmailTemplate
description string The email template description. This can be useful to describe the reason
for creating the template.
encodingKey Encoding (enumeration Required. The default encoding setting is Unicode: UTF-8. Change it if
of type string) your template requires data in a different format.
Valid values include:
• UTF-8
• ISO-8859-1
• Shift_JIS
• ISO-2022-JP
• EUC-JP
• ks_c_5601-1987
• ks_c_5601-1987
• Big5
• GB2312
fullName string The email template developer name used as a unique identifier for API
access. The fullName can only contain characters, letters, and the
underscore (_) character, must start with a letter, and cannot end with an
underscore or contain two consecutive underscore characters. If this field
contained characters before version 14.0 that are no longer allowed, the
characters were stripped out of this field, and the previous value of the field
was saved in the name field. This field is inherited from the Metadata
component.
letterhead string The letterhead name associated with this email template. Only available
when type is set to html.
name string Required. Email template name. The list of characters allowed in the
fullName field has been reduced for versions 14.0 and later. This field
contains the value contained in the fullName field before version 14.0.
116
Metadata Components EmailTemplate
Attachment
Attachment represents an email attachment.
117
Metadata Components Folder
<encodingKey>ISO-8859-1</encodingKey>
<name>Sample Email Template</name>
<style>none</style>
<subject>Sample email subject</subject>
<textOnly>Your case has been resolved.</textOnly>
<type>custom</type>
</EmailTemplate>
See Also:
Letterhead
Folder
Represents a folder. It extends the Metadata metadata type and inherits its fullName field. Four folder types currently exist
in application:
• Document folder
• Email template folder
• Report folder
• Dashboard folder
Note the following limitations for this component:
• Currently, users are not able to export Folder metadata to a local file system using the Force.com IDE.
• If the value of accessType is Shared, granting access by group, role, or role and subordinates is not supported. For
more information about granting access to records, see Granting Access to Records in the Salesforce online help.
Version
Folders are available in API version 11.0 and later.
Fields
This metadata type contains the following fields:
fullName string The internal name of the folder, based on the name, but with white
spaces and special characters escaped out for validity.
name string Required. The name of the document folder.
118
Metadata Components HomePageComponent
See Also:
Document
HomePageComponent
Represents the metadata associated with a home page component. You can customize the Home tab to include components
such as sidebar links, a company logo, or a dashboard snapshot. For more information, see "Customizing Home Tab Page
Layouts" in the Salesforce online help. It extends the Metadata metadata type and inherits its fullName field. Use to create,
update, or delete home page component definitions.
Version
Home page components are available in API version 12.0 and later.
HomePageComponent
This metadata type represents the valid values that define a home page component:
119
Metadata Components HomePageLayout
width PageComponentWidth This field is only available for HTML components, and indicates
(enumeration of type whether this is a narrow or wide home page component. Valid values
string) are the following:
• narrowComponents
• wideComponents
See Also:
HomePageLayout
Weblink
HomePageLayout
Represents the metadata associated with a home page layout. You can customize home page layouts and assign the layouts to
users based on their user profile. For more information, see "Customizing Home Tab Page Layouts" in the Salesforce online
help.
120
Metadata Components Layout
Version
Home page components are available in API version 12.0 and later. It extends the Metadata metadata type and inherits its
fullName field.
Fields
This metadata type represents the valid values that define a home page layout:
narrowComponents string[] The list of elements in the narrow column on the left side of the
home page.
wideComponents string[] The list of elements in the wide column on the right side of the
home page.
See Also:
HomePageComponent
Weblink
Layout
Represents the metadata associated with a page layout. For more information, see "Managing Page Layouts" in the Salesforce
online help. It extends the Metadata metadata type and inherits its fullName field.
121
Metadata Components Layout
Note: If you want to edit the Ideas layout, you must specify it by name in the package.xml file. In package.xml, use
the following code to retrieve the Ideas layout:
<types>
<members>Idea-Idea Layout</members>
<name>Layout</name>
</types>
Version
Layouts are available in API version 13.0 and later.
Fields
This metadata type represents the valid values that define a page layout:
layoutSections LayoutSection[] The main sections of the layout containing fields, s-controls,
and custom links. The order here determines the layout order.
122
Metadata Components Layout
MiniLayout
A mini layout is used in the mini view of a record in the console, hover details, and event overlays.
LayoutSection
LayoutSection represents a section of a page layout, such as the Custom Links section.
123
Metadata Components Layout
LayoutColumn
LayoutColumn represents the items in a column within a layout section.
LayoutItem
LayoutItem represents the valid values that define a layout item. An item must have only one of the following set: customLink,
field, scontrol, page.
124
Metadata Components Layout
RelatedListItem
RelatedListItem represents a related list in a page layout.
125
Metadata Components Layout
</layoutItems>
</layoutColumns>
<style>TwoColumnsTopToBottom</style>
</layoutSections>
<layoutSections>
<editHeading>true</editHeading>
<label>System Information</label>
<layoutColumns>
<layoutItems>
<behavior>Readonly</behavior>
<field>CreatedById</field>
</layoutItems>
<layoutItems>
<behavior>Readonly</behavior>
<field>Alpha1__c</field>
</layoutItems>
</layoutColumns>
<layoutColumns>
<layoutItems>
<behavior>Readonly</behavior>
<field>LastModifiedById</field>
</layoutItems>
<layoutItems>
<behavior>Edit</behavior>
<field>TextArea__c</field>
</layoutItems>
</layoutColumns>
<style>TwoColumnsTopToBottom</style>
</layoutSections>
<layoutSections>
<customLabel>true</customLabel>
<detailHeading>true</detailHeading>
<label>Custom Links</label>
<layoutColumns>
<layoutItems>
<customLink>CustomWebLink</customLink>
</layoutItems>
</layoutColumns>
<style>CustomLinks</style>
</layoutSections>
<miniLayoutFields>Name</miniLayoutFields>
<miniLayoutFields>OwnerId</miniLayoutFields>
<miniLayoutFields>CurrencyIsoCode</miniLayoutFields>
<miniLayoutFields>Alpha1__c</miniLayoutFields>
<miniLayoutFields>TextArea__c</miniLayoutFields>
<miniRelatedLists>
<relatedList>RelatedNoteList</relatedList>
</miniRelatedLists>
<relatedLists>
<fields>StepStatus</fields>
<fields>CreatedDate</fields>
<fields>OriginalActor</fields>
<fields>Actor</fields>
<fields>Comments</fields>
<fields>Actor.Alias</fields>
<fields>OriginalActor.Alias</fields>
<relatedList>RelatedProcessHistoryList</relatedList>
</relatedLists>
<relatedLists>
<relatedList>RelatedNoteList</relatedList>
</relatedLists>
</Layout>
126
Metadata Components Letterhead
Letterhead
Represents formatting options for the letterhead in an email template. Letterheads define the look and feel of your HTML
email templates. Your HTML email templates can inherit the logo, color, and text settings from a letterhead. For more
information, see "Creating Letterheads" in the Salesforce online help. It extends the Metadata metadata type and inherits its
fullName field.
Version
Letterheads are available in API version 12.0 and later.
Fields
With the exception of logo, and horizontal and vertical alignment, all of these fields are required.
backgroundColor string
Required. The background color, in hexadecimal, for
example #FF6600.
bodyColor string
Required. The body color in hexadecimal.
description string
Text description of how this letterhead differs from
other letterheads.
fullName string
The internal name of the letterhead, based on the name,
but with white spaces and special characters escaped out
for validity.
footer LetterheadHeaderFooter
Required. The style for the footer.
header LetterheadHeaderFooter
Required. The style for the header.
127
Metadata Components Letterhead
LetterheadHeaderFooter
LetterheadHeaderFooter represents the properties of a header or footer.
LetterheadLine
LetterheadLine represents the properties of a line.
128
Metadata Components Metadata
Metadata
This is the base class for all metadata types. You cannot edit this object. A component is an instance of a metadata type.
Metadata is analogous to sObject, which represents all standard objects. Metadata represents all components and fields in the
metadata API. Instead of identifying each component with an ID, each custom object or custom field has a unique fullName,
which must be distinct from standard object names, as it must be when you create custom objects or custom fields in the
Salesforce user interface.
Version
Metadata components are available in API version 10.0 and later.
129
Metadata Components MetadataWithContent
Fields
See Also:
CustomObject
CustomField
MetadataWithContent
MetadataWithContent
This is the base type for all metadata types that contain content, such as documents or email templates. It extends Metadata.
You cannot edit this object.
Version
MetadataWithContent components are available in API version 14.0 and later.
Fields
See Also:
Metadata
130
Metadata Components Portal
Portal
The Portal metadata type represents a Partner Portal or Customer Portal, and extends Metadata and inherits its fullName
field. To use this metadata type, you must have a Partner Portal or Customer Portal enabled for your organization. For more
information, see "About the Partner Portal" and "Enabling Your Customer Portal" in the Salesforce online help.
Version
Force.com Portal components are available in API version 15.0 and later.
Fields
headerDocument string The file to be used as the header for this portal.
isSelfRegistrationActivated boolean Determines whether self-registration is active or not for
this portal.
131
Metadata Components Portal
132
Metadata Components Profile
<showActionConfirmation>false</showActionConfirmation>
<type>CustomerSuccess</type>
</Portal>
See Also:
CustomSite
Profile
Represents a user profile. A profile defines a user’s permission to perform different functions within Salesforce. For more
information, see "Managing Profiles" in the Salesforce online help. It extends the Metadata metadata type and inherits its
fullName field.
Version
Profiles are available in API version 10.0 and later.
Fields
The contents of a profile returned by the metadata API depends on the contents requested in the RetrieveRequest message.
For example, profiles only include field-level security for fields included in custom objects returned in the same RetrieveRequest
as the profiles. The profile definition contains the following fields:
133
Metadata Components Profile
ProfileApplicationVisibility
ProfileApplicationVisibility represents an application that is visible to a user assigned to this profile:
ProfileApexClassAccess
ProfileApexClassAccess determines which top-level Apex classes have methods that users assigned to this profile can execute.
For more information, see "Setting Apex Class Security" in the Salesforce online help.
ProfileFieldLevelSecurity
ProfileFieldLevelSecurity represents the field level security for users assigned to a profile:
ProfileLayoutAssignments
ProfileLayoutAssignments determines which layout to use for a profile and a given entity:
134
Metadata Components Profile
ProfileObjectPermissions
ProfileObjectPermissions represents the field level security for objects whose permissions are altered by this profile:
allowDelete boolean Indicates whether the object referenced by the object field can be
deleted by the users assigned to this profile (true) or not (false).
This field is named revokeDelete before version 14.0 and the
logic is reversed. The field name change and the update from true
to false and vice versa is automatically handled between versions
and does not require any manual editing of existing XML
component files.
allowEdit boolean Indicates whether the object referenced by the object field can be
edited by the users assigned to this profile (true) or not (false).
This field is named revokeEdit before version 14.0 and the logic
is reversed. The field name change and the update from true to
false and vice versa is automatically handled between versions
and does not require any manual editing of existing XML
component files.
allowRead boolean Indicates whether the object referenced by the object field can be
seen by the users assigned to this profile (true) or not (false).
This field is named revokeRead before version 14.0 and the logic
is reversed. The field name change and the update from true to
false and vice versa is automatically handled between versions
and does not require any manual editing of existing XML
component files.
modifyAllRecords boolean Indicates whether the object referenced by the object field can be
read, edited, or deleted by the users assigned to this profile (true)
or not (false), regardless of the sharing settings for the object.
This is equivalent to the "Modify All Data" user permission limited
to the individual object level. This is a new field in API version
15.0.
135
Metadata Components Profile
ProfileApexPageAccess
ProfileApexPageAccess determines which custom Visualforce controllers or controller extensions applied to a Visualforce page
have methods that users assigned to this profile can execute. For more information, see "Setting Apex Class Security" in the
Salesforce online help.
ProfileRecordTypeVisibility
ProfileRecordTypeVisibility represents the visibility of record types for this profile. Record types allow you to offer different
business processes, picklist values, and page layouts to different users based on their profiles. For more information, see
"Managing Record Types" in the Salesforce online help.
136
Metadata Components Profile
ProfileTabVisibility
ProfileTabVisibility represents the visibility of tabs for this profile:
TabVisibility
TabVisibility represents the tab customizations for users assigned to this profile:
Java Sample
The following sample uses picklists, profiles, and record types:
expenseRecord.setDeploymentStatus(DeploymentStatus.Deployed);
expenseRecord.setSharingModel(SharingModel.ReadWrite);
create(expenseRecord);
137
Metadata Components Profile
// But employees and managers have different access to the state of the expense sheet
RecordType edit = new RecordType();
edit.setFullName("ExpenseReport__c.Edit");
RecordTypePicklistValue editStatuses = new RecordTypePicklistValue();
editStatuses.setPicklist("ExpenseStatus__c");
editStatuses.setValues(new PicklistValue[] {unsubmitted, submitted});
edit.setPicklistValues(new RecordTypePicklistValue[] {editStatuses});
create(edit);
138
Metadata Components Profile
<default>false</default>
<visible>true</visible>
</applicationVisibilities>
<objectPermissions>
<object>TestWeblinks__c</object>
</objectPermissions>
<recordTypeVisibilities>
<default>true</default>
<recordType>TestWeblinks__c.My First Recordtype</recordType>
<visible>true</visible>
</recordTypeVisibilities>
<tabVisibilities>
<tab>Myriad Publications</tab>
<visibility>DefaultOn</visibility>
</tabVisibilities>
</Profile>
Usage
When you use the retrieve() call to get information about profiles in your organization, the returned .profile files only
include security settings for the other metadata types referenced in the retrieve request. For example, the package.xml file
below contains a types element that matches all custom objects, so the returned profiles contain object and field permissions
for all custom objects in your organization, but do not include permissions for standard objects, such as Account, and standard
fields.
The wildcard “*” on CustomObject does not match standard objects and this helps to avoid making unintended, high-impact
profile changes. If you create a few custom objects in a Developer Edition organization, retrieve() the information, and
subsequently deploy() the custom objects to your production organization, the profile and field-level security for all your
standard objects, such as Account, and standard fields are not overwritten unless you explicitly create separate types elements
for the standard objects or fields. For more information about profiles, see "User Permissions on Profiles" in the Salesforce
online help.
The metadata API intentionally makes it somewhat difficult to include standard fields in retrieve() calls in order to
prevent unexpected profile changes. However, you can still retrieve and deploy profile permissions for custom and standard
fields in standard objects, such as Account.
The next package.xml file allows you to return profile permissions for Account standard and custom fields. Note how the
standard Account object is defined in a types element by specifying it as a member of a CustomObject type.
139
Metadata Components Report
<version>15.0</version>
</Package>
The final package.xml file allows you to return profile permissions for the MyCustomField__c custom field in the Account
object.
Report
Represents a custom report. It extends the Metadata metadata type and inherits its fullName field. This metadata type only
supports custom reports; standard reports are not supported. For more information, see "What Is a Report?" in the Salesforce
online help.
Version
Report components are available in API version 14.0 and later.
Fields
The following information assumes that you are familiar with creating and running reports. For more information on these
fields, see "Creating a Custom Report" in the Salesforce online help.
140
Metadata Components Report
<operator>greaterThan</operator>
<value>1000</value>
</filters>
format ReportFormat (enumeration of type string) Defines the report format. For example,
Tabular for a simple data list without
subtotals.
fullName string The report unique developer name used as
an identifier for API access. The fullName
can only contain characters, letters, and the
underscore (_) character, must start with a
letter, and cannot end with an underscore or
contain two consecutive underscore
characters. This field is inherited from the
Metadata component.
groupingsAcross ReportGrouping[] List that defines the fields by which you want
to group and subtotal data across a matrix
report (row headings). When grouping by a
date field, you can further group the data by
a specific time period such as days, weeks, or
months. Maximum: 2 fields.
groupingsDown ReportGrouping[] For Summary and Matrix reports: List that
defines the fields by which you want to group
and subtotal. For summary reports, choosing
more than one sort field allows you to subsort
your data. For matrix reports, specifies
141
Metadata Components Report
142
Metadata Components Report
ReportAggregate
ReportAggregate defines custom summary formulas on summary or matrix reports. For more information on these fields, see
"Building Custom Summary Formulas" in the Salesforce online help.
ReportGrouping
ReportGrouping defines how to group and subtotal data for summary and matrix reports.
SortOrder
An enumeration of type string that defines the order in which data is sorted in the report fields. Valid values:
143
Metadata Components Report
Field Description
Asc Sorts data in ascending alphabetical and numerical order.
Desc Sorts data in descending alphabetical and numerical order.
UserDateGranularity
An enumeration of type string that defines the time period by which to group data. Valid values:
ReportSummaryType
An enumeration of type string that defines how report fields are summarized. Valid values:
ReportColorRange
ReportColorRange defines conditional highlighting for report summary data.
144
Metadata Components Report
ReportColumn
ReportColumn defines how fields (columns) are displayed in the report.
ReportFilter
ReportFilter limits the report results by filtering data on specified fields.
ReportFilterItem
ReportFilterItem limits the report results by filtering data on specified fields.
145
Metadata Components Report
ReportFormat
An enumeration of type string that defines the report format. Valid values:
ReportParam
ReportParam represents settings specific to a report type, especially options that let you filter a report to certain useful subsets.
CustomFieldDatatypes
An enumeration of type string that specifies the data type for formatting and display of custom summary formula results. Valid
values:
Enumeration Value
Number
Percent
Currency
ReportChart
ReportChart represents charts on summary and matrix reports.
146
Metadata Components Report
chartType ChartType (enumeration of Required. Specifies the chart type. Available chart types
type string) depend on the report type.
groupingColumn string Specifies the field by which to group data. This data is
displayed on the X-axis for vertical column charts and on
the Y-axis for horizontal bar charts.
legendPosition ChartLegendPosition Required.
(enumeration of type string)
The location of the legend with respect to the chart. The
valid values are:
• LEGEND_NONE
• LEGEND_RIGHT
• LEGEND_BOTTOM
location ChartPosition (enumeration Required. Specifies whether the chart is displayed at the
of type string) top or bottom of the report.
secondaryGroupingColumn string For grouped chart types: Specifies the field by which to
group the data.
showAxisLabels boolean For bar and line charts: Specifies whether the chart displays
names for each axis.
size ReportChartSize Required. Specifies the chart size.
(enumeration of type string)
summaryAggregate ReportSummaryType Defines how to summarize the chart data. For example,
(enumeration of type string) Sum
summaryAxisManualRangeEnd double When specifying the axis range manually: Defines the
ending value.
summaryAxisManualRangeStart double When specifying the axis range manually: Defines the
starting value.
summaryAxisRange ChartRangeType Required. For bar, line, and column charts: Defines whether
(enumeration of type string) to specify the axis range manually or automatically.
summaryColumn string Required. Specifies the field by which to summarize the
chart data. Typically this field is displayed on the Y-axis.
147
Metadata Components Report
ChartType
An enumeration of type string that defines the chart type. For information on each of these chart types, see "Chart Types" in
the Salesforce online help. Valid values:
Enumeration Value
None
HorizontalBar
HorizontalBarGrouped
HorizontalBarStacked
HorizontalBarStackedTo100
VerticalColumn
VerticalColumnGrouped
VerticalColumnStacked
VerticalColumnStackedTo100
Line
LineGrouped
148
Metadata Components Report
Enumeration Value
LineCumulative
LineCumulativeGrouped
Pie
ChartPosition
An enumeration of type string that specifies the position of the chart in the report. Valid values:
Enumeration Value
CHART_TOP
CHART_BOTTOM
ReportChartSize
An enumeration of type string that specifies the chart size. Valid values:
Enumeration Value
Tiny
Small
Medium
Large
Huge
ChartRangeType
An enumeration of type string that defines the report format. Valid values:
Enumeration Value
Manual
Automatic
ReportTimeFrameFilter
ReportTimeFrameFilter represents the report time period.
149
Metadata Components Report
UserDateInterval
An enumeration of type string that defines the period of time. Valid values:
150
Metadata Components Report
151
Metadata Components Report
152
Metadata Components Report
<columns>
<field>CLOSE_DATE</field>
</columns>
<columns>
<field>STAGE_NAME</field>
</columns>
<columns>
<field>ROLLUP_DESCRIPTION</field>
</columns>
<columns>
<field>CREATED_DATE</field>
</columns>
<columns>
<field>PRODUCT_NAME</field>
</columns>
<columns>
<field>QUANTITY</field>
</columns>
<columns>
<field>UNIT_PRICE</field>
</columns>
<columns>
<field>TOTAL_PRICE</field>
</columns>
<columns>
<field>SERVICE_DATE</field>
</columns>
<columns>
<field>SERVICE_MONTH</field>
</columns>
<columns>
<field>PRODUCT_DESCRIPTION</field>
</columns>
<columns>
<field>PRODUCT_PRICE</field>
</columns>
<columns>
<field>PRODUCT_CUSTOMER_ID</field>
</columns>
<columns>
<field>PRODUCT_ACTIVE</field>
</columns>
<columns>
<field>ACCOUNT_NAME</field>
</columns>
<currency>AED</currency>
<filter>
<booleanFilter>(1 or 2 or 3 or 4 or 5 or 6)</booleanFilter>
<criteriaItems>
<column>AMOUNT</column>
<operator>greaterThan</operator>
<value>USD 1000.0</value>
</criteriaItems>
<criteriaItems>
<column>ACCOUNT_NAME</column>
<operator>startsWith</operator>
<value>Acme</value>
</criteriaItems>
<criteriaItems>
<column>OPPORTUNITY.CURRENCY_ISO_CODE</column>
<operator>equals</operator>
<value>USD,GBP,ADP</value>
</criteriaItems>
<criteriaItems>
<column>FORECAST_CATEGORY</column>
<operator>equals</operator>
<value>Omitted,Pipeline</value>
153
Metadata Components ReportType
</criteriaItems>
<criteriaItems>
<column>Account.Animal__c</column>
<operator>equals</operator>
<value>Dog;Cow,Cat;Pig</value>
</criteriaItems>
<criteriaItems>
<column>STAGE_NAME</column>
<operator>equals</operator>
<value>Prospecting</value>
</criteriaItems>
<language>en_US</language>
</filter>
<format>Matrix</format>
<groupingsAcross>
<field>INDUSTRY</field>
<sortOrder>Asc</sortOrder>
</groupingsAcross>
<groupingsDown>
<dateGranularity>Month</dateGranularity>
<field>CLOSE_DATE</field>
<sortOrder>Asc</sortOrder>
</groupingsDown>
<name>Simple Opportunity Report</name>
<params>
<name>open</name>
<value>all</value>
</params>
<params>
<name>probability</name>
<value>>0</value>
</params>
<reportType>OpportunityProduct</reportType>
<scope>organization</scope>
<showDetails>true</showDetails>
<timeFrameFilter>
<dateColumn>CLOSE_DATE</dateColumn>
<interval>INTERVAL_CURRENT</interval>
</timeFrameFilter>
</Report>
See Also:
Dashboard
ReportType
Represents the metadata associated with a custom report type. It extends the Metadata metadata type and inherits its fullName
field. Custom report types allow you to build a framework from which users can create and customize reports. For more
information, see "What Is a Custom Report Type?" in the Salesforce online help.
Version
Custom report types are available in API version 14.0 and later.
154
Metadata Components ReportType
Fields
deployed boolean Required. Indicates whether the report type is available for use in
the report wizard (true) or whether it's still in development
(false).
description string The description of the custom report type.
fullName string The report type developer name used as a unique identifier for API
access. The fullName can only contain characters, letters, and the
underscore (_) character, must start with a letter, and cannot end
with an underscore or contain two consecutive underscore characters.
join ObjectRelationship The object joined to the baseObject. For example, Contacts may
be joined to the primary Accounts object.
label string Required. The report type label.
sections ReportLayoutSection[] The groups of columns available for the report type. Though columns
are not strictly required, a report without columns is not very useful.
ObjectRelationship
ObjectRelationship represents a join to another object. For more information, see "Choosing the Object Relationships that
Display on Reports Created from Custom Report Types" in the Salesforce online help.
155
Metadata Components ReportType
ReportLayoutSection
ReportLayoutSection represents a group of columns used in the custom report type.
ReportTypeColumn
ReportTypeColumn represents a column in the custom report type.
156
Metadata Components Scontrol
<columns>
<checkedByDefault>true</checkedByDefault>
<field>obj_lookup__c.Id</field>
<table>Account</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>obj_lookup__c.Name</field>
<table>Account</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Opportunity__c.Amount</field>
<table>Account</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Owner.IsActive</field>
<table>Account</table>
</columns>
<masterLabel>Accounts</masterLabel>
</sections>
<sections>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Owner.Email</field>
<table>Account.Contacts</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>byr__c</field>
<table>Account.Contacts</table>
</columns>
<columns>
<checkedByDefault>true</checkedByDefault>
<field>ReportsTo.CreatedBy.Contact.Owner.MobilePhone</field>
<table>Account.Contacts</table>
</columns>
<masterLabel>Contacts</masterLabel>
</sections>
</ReportType>
Scontrol
Represents an Scontrol component, corresponding to an s-control in the Salesforce user interface. For more information, see
"About S-Controls" in the Salesforce online help. This metadata type extends the MetadataWithContent component and
shares its fields.
Version
Scontrols are available in API version 10.0 and later.
157
Metadata Components Scontrol
Fields
This metadata type contains the following fields:
description string Optional text that describes the s-control. This only displays to
users with "View All Data" permission (administrator).
encodingKey Encoding (enumeration of type Required. The default encoding setting is Unicode: UTF-8.
string) Change it if you are passing information to a URL that requires
data in a different format. This option is available when you select
URL as the value for contentSource.
fileContent base64 File contents displayed if you add this s-control to a custom link.
The file can contain a Java applet, Active-X control, or any other
type of content you want. This option only applies to s-controls
with a value of HTML for contentSource.
fileName string The unique name for the s-control. It must contain alphanumeric
characters only and begin with a letter. This field cannot be
changed for components installed by a managed package. It is
only relevant if the fileContent field also has a value. This is
a new field in API version 14.0.
fullName string The s-control developer name used as a unique identifier for API
access. The fullName can only contain characters, letters, and the
underscore (_) character, must start with a letter, and cannot end
with an underscore or contain two consecutive underscore
characters. If this field contained characters before version 14.0
that are no longer allowed, the characters were stripped out of
this field, and the previous value of the field was saved in the
name field. This field is inherited from the Metadata component.
name string Required. The unique name for the s-control. It must contain
alphanumeric characters only and begin with a letter. For example
example_s_control.
supportsCaching boolean Required. Indicates whether the s-control supports caching
(true) or not (false). Caching optimizes the page so that it
158
Metadata Components StaticResource
http://www.myriadpubs.com
Myriad_Publishing.scf-meta.xml:
StaticResource
Represents a static resource file, often a code library in a ZIP file. This metadata type extends the MetadataWithContent
component and shares its fields.
Static resources allow you to upload content that you can reference in a Visualforce page, including archives (such as .zip and
.jar files), images, stylesheets, JavaScript, and other files.
Version
Static resources are available in API version 12.0 and later.
Fields
This metadata type contains the following fields:
159
Metadata Components Translations
Translations
This metadata type allows you to work with translations for a variety of languages. The supported languages are listed in
Language on page 160. It extends the Metadata metadata type and inherits its fullName field. The ability to translate component
labels is part of the Translation Workbench. For more information, see "Setting Up Translation Workbench" in the Salesforce
online help.
Language
The translation languages supported are identified by a five-character locale code or a two-character language code. These
codes are listed in the table below. A complete locale includes a two-character ISO language code, followed by an underscore
(_) and a two-character ISO country code. For example, the locale is “en_US” for the United States. Some of the locales below
only specify a two-character ISO language code, for example “fr.”
160
Metadata Components Translations
Version
Translations components are available in API version 14.0 and later.
Fields
161
Metadata Components Translations
CustomApplicationTranslation
CustomApplicationTranslation contains details for a custom application translation. For more details, see CustomApplication
on page 68.
CustomLabelTranslation
CustomLabelTranslation contains details for a custom label translation. For more details, see CustomLabels on page 69.
CustomPageWebLinkTranslation
CustomPageWebLinkTranslation contains details for a translation of a web link defined in a home page component. For
more details, see CustomPageWebLink on page 100.
CustomTabTranslation
CustomTabTranslation contains details for a translation of a custom tab. For more details, see CustomTab on page 106.
162
Metadata Components Translations
ReportTypeTranslation
ReportTypeTranslation contains details for a translation of a custom report type. For more details, see ReportType on page
154.
ReportTypeSectionTranslation
ReportTypeSectionTranslation contains details for a report type section translation.
ReportTypeColumnTranslation
ReportTypeColumnTranslation contains details for a report type column translation.
ScontrolTranslation
ScontrolTranslation contains details for a translation of an s-control. For more information, see "About S-Controls" in the
Salesforce online help.
163
Metadata Components Workflow
See Also:
CustomLabels
Workflow
Represents the metadata associated with a workflow rule. A workflow rule sets workflow actions into motion when its designated
conditions are met. You can configure workflow actions to execute immediately when a record meets the conditions in your
workflow rule, or set time triggers that execute the workflow actions on a specific day. For more information, see "Managing
Workflow and Approvals" in the Salesforce online help. It extends the Metadata metadata type and inherits its fullName
field. Use this metadata type to create, update, or delete workflow rule definitions.
When using a manifest file, retrieve all workflow components using the following code:
<types>
<members>*</members>
<name>Workflow</name>
</types>
Version
Workflow rules are available in API version 13.0 and later.
Workflow
This metadata type represents the valid types of workflow rules and actions associated with a standard or custom object.
164
Metadata Components Workflow
WorkflowAlert
WorkflowAlert represents an email alert associated with a workflow rule.
WorkflowEmailRecipient
WorkflowEmailRecipient represents a recipient for an email alert associated with a workflow rule.
165
Metadata Components Workflow
166
Metadata Components Workflow
WorkflowFieldUpdate
WorkflowFieldUpdate represents a workflow field update. Field updates allow you to automatically update a field value to
one that you specify when a workflow rule is triggered. For more information, see "Defining Field Updates" in the Salesforce
online help.
notifyAssignee boolean Required. Notify the assignee when the field is updated.
operation FieldUpdateOperation Required. The operation that computes the value with which
(enumeration of type string) to update the field. Valid values are:
• Formula - Indicates the field will be set to a formula. If
set, the formula must be a valid formula.
• Literal - Indicates the field will be set to a literal value.
If set, the literalValue must be a valid literal value for this
field.
• LookupValue - Similar to Literal, but for an object
reference, such as a contact, user, account, etc. If set, the
lookupValue element must be set. Only User is
supported in the current API.
• NextValue - Indicates the field will be set its next value;
this is only allowed when the field update references a
picklist.
• Null - Indicates the field will be set to null.
• PreviousValue - Indicates the field will be set its
previous value; this is only allowed when the field update
references a picklist.
167
Metadata Components Workflow
WorkflowOutboundMessage
WorkflowOutboundMessage represents an outbound message associated with a workflow rule. Outbound messages are
workflow and approval actions that send the information you specify to an endpoint you designate, such as an external service.
An outbound message sends the data in the specified fields in the form of a SOAP message to the endpoint. For more
information, see "Defining Outbound Messages" in the Salesforce online help.
WorkflowRule
This metadata type represents a workflow rule. It extends the Metadata metadata type and inherits its fullName field.
168
Metadata Components Workflow
WorkflowActionReference
WorkflowActionReference represents one of the four workflow actions.
WorkflowTask
This metadata type references an assigned workflow task.
169
Metadata Components Workflow
fullName string The developer name used as a unique identifier for API
access. The fullName can only contain characters,
letters, and the underscore (_) character, must start
with a letter, and cannot end with an underscore or
contain two consecutive underscore characters. This
field is inherited from the Metadata component.
notifyAssignee boolean Required. Set to send an email notification when the
task is assigned.
offsetFromField string Optional field reference of the date field from which
the dueDate should be computed.
priority string Required. The priority to assign the created task.
protected boolean Required. Indicates whether this component is
protected (true) or not (false). Protected
components cannot be linked to or referenced by
components created in the installing organization.
status string Required. The status to assign the created task.
170
Metadata Components Workflow
171
Metadata Components Workflow
<rules>
<fullName>BooleanFilter</fullName>
<active>false</active>
<booleanFilter>1 AND 2 OR 3</booleanFilter>
<criteriaItems>
<field>CustomObjectForWorkflow__c.CreatedById</field>
<operation>notEqual</operation>
</criteriaItems>
<criteriaItems>
<field>CustomObjectForWorkflow__c.CreatedById</field>
<operation>notEqual</operation>
<value>abc</value>
</criteriaItems>
<criteriaItems>
<field>CustomObjectForWorkflow__c.CreatedById</field>
<operation>equals</operation>
<value>xyz</value>
</criteriaItems>
<triggerType>onCreateOrTriggeringUpdate</triggerType>
</rules>
<rules>
<fullName>Custom Rule1</fullName>
<actions>
<name>AnotherAlert</name>
<type>Alert</type>
</actions>
<actions>
<name>EnumFieldUpdate2</name>
<type>FieldUpdate</type>
</actions>
<actions>
<name>FieldUpdate</name>
<type>FieldUpdate</type>
</actions>
<active>true</active>
<criteriaItems>
<field>CustomObjectForWorkflow__c.Name</field>
<operation>startsWith</operation>
<value>ABC</value>
</criteriaItems>
<description>Custom Rule1 desc</description>
<triggerType>onCreateOrTriggeringUpdate</triggerType>
</rules>
<rules>
<fullName>IsChangedFunctionRule</fullName>
<active>true</active>
<description>IsChangedDesc</description>
<formula>ISCHANGED(Name)</formula>
<triggerType>onAllChanges</triggerType>
</rules>
<tasks>
<fullName>AnotherTask</fullName>
<assignedToType>owner</assignedToType>
<description>Random Comment</description>
<dueDateOffset>20</dueDateOffset>
<notifyAssignee>true</notifyAssignee>
<priority>High</priority>
<protected>false</protected>
<status>Completed</status>
</tasks>
<tasks>
<fullName>RoleTask</fullName>
<assignedTo>R11</assignedTo>
<assignedToType>role</assignedToType>
<dueDateOffset>-2</dueDateOffset>
<notifyAssignee>true</notifyAssignee>
<offsetFromField>CustomObjectForWorkflow__c.CreatedDate</offsetFromField>
172
Metadata Components Workflow
<priority>High</priority>
<protected>false</protected>
<status>Completed</status>
</tasks>
<tasks>
<fullName>UserTask</fullName>
<assignedTo>admin@acme.com</assignedTo>
<assignedToType>user</assignedToType>
<dueDateOffset>-2</dueDateOffset>
<notifyAssignee>true</notifyAssignee>
<offsetFromField>User.CreatedDate</offsetFromField>
<priority>High</priority>
<protected>false</protected>
<status>Completed</status>
</tasks>
</Workflow>
173
Index
Index
A components (continued)
ValidationRule 90
ApexClass component 63 Workflow 164
ApexComponent component 64 create call (asynchronous) 24
ApexPage component 65 Custom report type component 154
ApexTrigger component 66 CustomApplication component 68
CustomDataType component 69
CustomField component 74
C CustomLabels component 69
calls CustomObject
checkDeployStatus 43 Weblink component 91
checkRetrieveStatus 54 CustomObject component 71
checkStatus 23 CustomObjectTranslation component 95
create (asynchronous) 24 CustomPageWebLink component 100
delete (asynchronous) 26 CustomSite component 103
deploy 36 CustomTab component 106
describeMetadata 58
listMetadata 60, 61 D
retrieve 48
retrieve request 55 Dashboard component 108
update (asynchronous) 28 Declarative development 32
checkDeployStatus metadata call 43 delete (asynchronous) call 26
checkRetrieveStatus metadata call 54 deploy call 36
checkStatus metadata call 23 describeMetadata call 58
components Document component 114
ApexClass 63
ApexComponent 64
ApexPage 65
E
ApexTrigger 66 EmailTemplate component 115
CustomApplication 68 error handling 22
CustomDataType 69 expiration of session ID 22
CustomField 74
CustomFieldTranslation 95
CustomLabel 69 F
CustomLabels 69
CustomObject 71 field types 94
CustomObjectTranslation 95 File-based metadata 32
CustomPageWebLink 100 Folder component 118
CustomTab 106
Dashboard 108 H
Document 114
EmailTemplate 115 HomePageComponent component 119
Folder 118 HomePageLayout component 120
HomePageComponent 119
HomePageLayout 120
Layout 121
L
Letterhead 127 Layout component 121
ListView 79 Letterhead component 127
ListViewFilter 79 listMetadata call 60
Metadata 129 ListMetadataQuery 61
MetadataWithContent 130 ListView component 79
ObjectRelationship 154
Picklist 81
Profile 133 M
RecordType 84
ReportType 154 Metadata 32
Scontrol 157 metadata calls 3
SearchLayouts 86 Metadata component 129, 130
SharingReason 88 metadata components
SharingRecalculation 89 CustomSite 103
Static resource 159 Portal 131 174
Translations 160 Report 140
Index
Metadata components 62 Static resource component 159
support policy
backward compatibility 4
O call deprecation 4
outer join 154 deprecated calls 4
metadata API 4
supported calls 62
P
Picklist definitions 81 T
Portal component 131
Profile component 133 Translations component 160
types of fields 94
Q
U
quick start 6
understanding metadata calls and components
metadata 3
R update (asynchronous) call 28
RecordType component 84
Report component 140 V
retrieve call 48
retrieve request 55 ValidationRule component 90
Visualforce component, see ApexComponent 64
Visualforce page, see ApexPage 65
S
sample code 6 W
Scontrol component 157
SearchLayouts component 86 Weblink component of CustomObject 91
session ID expiration 22 Workflow component 164
SharingReason component 88 WSDL integration 6
SharingRecalculation component 89
175