Tuesday, March 3, 2015

Populating Map + SFDC

Many times I faced that I need a Value with its "Group of values".

Getting a unique value in Set is a idea, but what if you have a group of values associated with it.

So that time Map is the best way to settle it down.
we can take Map in many ways but here I am using
Map<String, List<String>>

I used this map allot, because populating this map with Key and Values is a great method.
Here am showing two methods same but in different ways.

Here is the first one.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

    //Map of Opportunity
    Map<Id, Set<Id>> opportunityMap = new Map<Id, Set<Id>>();

    //Loop through the Opportunity records
    for(Opportunity opp : opportunities) {
     
        //Check if map key contains System Field
        if(opportunityMap.containsKey(opp.Opportunity_Field__c)) {
         
          //Get the Values of the Map and add Id to it.
          opportunityMap.get(opp.Opportunity_Field__c).add(opp.Id);
        }else {
          //Creat a new Set at values and add Id to it.
          opportunityMap.put(opp.Opportunity_Field__c, new Set<Id>{opp.Id}); 
        }
      }
    }

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


Here is the same but another way to write it
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

//Loop through list
for(Opportunity opp : opportunities) {

   //List of Opportunity
   List<Opportunity> opps = new List<Opportunity>();

  //Check for values of the Map
   if(mapOpportuinties.containsKey(opp.Fishbowl_Customer_Number__c) == false) {

    //Add to list
   opps.add(opp);

  } else {

     //Add to list
     opps = mapOpportuinties.get(opp.Fishbowl_Customer_Number__c);
     opps.add(opp);
  }

     //Populating map
     mapOpportuinties.put(opp.Fishbowl_Customer_Number__c, opps);
  }

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Using the above snippet every unique value will have a common group of values. its like

Object1 = value1, value2 value3
Object2 = value1, value2, value3
Object3 = value2, value3, value4
Object4 = value5, value6, value7


Cheers....!!!!!

Wednesday, November 12, 2014

Salesforce + Finding out "How deleted out the records"

If you need to find out who is deleting your records, you can write this code on the Execute Anonymous block (either on the force.com IDE or the Force.com Console):

for (List<Account> Accs : [SELECT Id, LastModifiedByID, LastModifiedBy.userName, LastModifiedBy.name, LastModifiedDate, Name
                           FROM Account
                           WHERE IsDeleted = true
                           ALL ROWS]) {
    for (Account acc : Accs) {
        String str = '';
        str += 'Account [' + Acc.Name + '] ';
        str += 'was deleted by [' + acc.LastModifiedBy.name + ' ';
        str += '(' + acc.LastModifiedBy.userName + ')] ';
        str += 'on [' + acc.LastModifiedDate + ']';
        System.debug(str);
    }
}

You could also perform a similar operation using Data Loader (v20 or later) by clicking on the [Export All] button and using this query:

SELECT Id, LastModifiedByID, LastModifiedBy.userName, LastModifiedBy.name, LastModifiedDate, Name
FROM Account
WHERE IsDeleted = true

This works in Data Loader because it uses the QueryAll() method when connecting to Salesforce using the Webservices API.

Trigger + Write Once Data for Field + Salesforce

This trigger will prevent records from being deleted or fields from being changed once they have been set, so they are write-once. Note, the other fields can be written many times but the specific field's value can only be set when the record is created.

trigger Trigger_Account on Account (before delete, before update) {

    if (trigger.isDelete) {
        for (Account a : trigger.old) {
            a.addError('You can’t delete accounts');
        }
    } else {
        for (Account aNew : trigger.new) {
            Account aOld = Trigger.oldMap.get(aNew.ID);
            if (aNew.Phone != aOld.Phone) {
                aNew.Phone = aOld.Phone;
            }
        }
    }
}

Thursday, July 10, 2014

Setting Profile Field Level Security (FLS) using JavaScript + Salesforce

Have you ever had to set FLS settings on Account for over 500 fields for a particular profile ?
I'm sure you had encountered this situation and we all know what a pain it can become. Manually checking each and every checkbox.
Well, here I'm with an easy solution. With a little bit of JavaScript magic we can get this task done in seconds. Here I've mentioned two JavaScript code snippets which can be run in the console of and get this task done in no time.
Run the below Code Snippet in Console of Firefox or Chrome to check all the check boxes of Visible type.
var elem = document.getElementsByTagName("tr");
for (var i = 0; i < elem.length; i++) {
    for (var j = 0; j < elem[i].childNodes.length; j++) {
        if (elem[i].childNodes[j].nodeName == "TD" && elem[i].childNodes[j].firstChild.nodeName == 'INPUT'
            && elem[i].childNodes[j].firstChild.type == 'checkbox' && elem[i].childNodes[j].firstChild.title == 'Visible') {
            var checkTD = elem[i].childNodes[j].firstChild.checked = true;
        }
    }
}
Run the below Code Snipped in Console of Firefox or Chrome to check all the check boxes of Read-Only type.
var elem = document.getElementsByTagName("tr");
for (var i = 0; i < elem.length; i++) {
    for (var j = 0; j < elem[i].childNodes.length; j++) {
        if (elem[i].childNodes[j].nodeName == "TD" && elem[i].childNodes[j].firstChild.nodeName == 'INPUT' && elem[i].childNodes[j].firstChild.type == 'checkbox'
            && elem[i].childNodes[j].firstChild.title == 'Read-Only') {
            var checkTD = elem[i].childNodes[j].firstChild.checked = true;
        }
    }

}
To Uncheck the Checkboxes just change the last line in above snippets to
var checkTD = elem[i].childNodes[j].firstChild.checked = false;

I hope this will get rid of a major pain point that us Developers and Administrators had to encounter on a daily basis.

Thanks
Enjoy Coding....

Wednesday, December 11, 2013

Salesforce : Sorting a wrapper list using Comparable Interface

The Comparable interface adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.

To add List sorting support for your Apex class, you must implement the Comparable interface with its compareTo method in your class.

When a class implements the Comparable interface it has to implement a method called compareTo(). In that method the code has to be written to decide if two objects match or if one is larger than the other.

Apex Class

public class AccountHistoryController {

    public List<AccountHistoryWrapper> accountHistoriesWrapList {get; set;}

    //Calling cosnturctor
    public AccountHistoryController() {
 
        //Memory Allocation
        accountHistoriesWrapList = new List<AccountHistoryWrapper>();
     
        //Loop through Accounts
        for(Account acc : [Select Id, Name, (Select ID, Field, AccountId, CreatedDate, Createdby.Name,                                                       Oldvalue,Newvalue, Account.Name From Account.Histories
                                                Where Field = 'Name' ORDER BY CreatedDate DESC LIMIT 200)
                                                FROM Account]) {
            //Populate wrapper list with values
            accountHistoriesWrapList.add(new AccountHistoryWrapper(acc, acc.Histories));                                      
                                                             
        }
     
        //Get List of wrapper and sort it
        accountHistoriesWrapList.sort();
    }

}

Wrapper Class

global class AccountHistoryWrapper implements Comparable {
 
    public Account account {get; set;}
    public List<AccountHistory> accountHistories {get; set;}
 
    //Calling Constructor
    global AccountHistoryWrapper(Account account, List<AccountHistory> accountHistories) {
        this.account = account;
        this.accountHistories = accountHistories;
    }

     // Compare opportunities based on the opportunity amount.
    global Integer compareTo(Object compareTo) {
     
        // Cast argument to AccountHistoryWrapper
        AccountHistoryWrapper aHW = (AccountHistoryWrapper)compareTo;
     
        // The return value of 0 indicates that both elements are equal.
        Integer returnValue = 0;
        if (account.Name > aHW.account.Name) {
            // Set return value to a positive value.
            returnValue = 1;
        } else if (account.Name < aHW.account.Name) {
            // Set return value to a negative value.
            returnValue = -1;
        }
     
        return returnValue;    
    }

}

Visualforce Page

<apex:page controller="AccountHistoryController">
    <apex:form >
        <apex:pageBlock >
            <apex:repeat value="{!accountHistoriesWrapList}" var="accountHistoryWrap">
                {!accountHistoryWrap.account.Name}
                <BR></BR>
                <apex:pageBlockTable value="{!accountHistoryWrap.accountHistories}" var="aHW">
               
                    <!-- Content of Table-->
                    <apex:column style="width:50%">
                        <apex:facet name="header">Activity</apex:facet>
                        Changed Grade from <b>"{!aHW.oldvalue}"</b> to <b>"{!aHW.newvalue}"</b>
                    </apex:column>
     
                    <!--More Information-->
                    <apex:column headerValue="Date" value="{!aHW.createddate}" style="width:40%"/>
                    <apex:column headerValue="Changed By" value="{!aHW.createdby.Name}" style="width:10%"/>
           
                 </apex:pageBlockTable>
            </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Saturday, November 2, 2013

Salesforce + SOQL Query

Salesforce SOQL Query

===============
Basic Examples
===============

1) Simple Query
SELECT Name FROM Account WHERE Name like 'Test%' AND Status__c = 'Approved' LIMIT 1000

2) Query Filter on DateTime field
SELECT Name FROM Account WHERE CreatedDate > 2011-04-26T10:00:00-08:00
SELECT Name FROM Account WHERE CreatedDate > 2011-04-26T10:00:00Z

3) Query with Date Function("http://docs.database.com/dbcom/en-us/db_sosl_soql/sforce_api_calls_soql_select_date_functions.htm?version=186.0")
SELECT Amount FROM Opportunity WHERE CALENDAR_YEAR(CreatedDate) = 2011

4) Query filter on null
SELECT AccountId FROM Event WHERE ActivityDate != null

5) Query Multi-Select Picklists

The following operators are supported for querying multi-select picklists:

Operator Description
= Equals the specified string.
!= Does not equal the specified string.
includes Includes (contains) the specified string.
excludes Excludes (does not contain) the specified string.
; Specifies AND for two or more strings.

SELECT Id, MSP1__c from Account WHERE MSP1__c includes ('AAA;BBB','CCC')
this will return record with MSP__1 example: 'AAA;BBB;DDD' ; 'CCC;EEE'

6) Querying Currency Fields in Multi-currency Organizations
SELECT Id, Name FROM Opportunity WHERE Amount > JPY5000
without currency code it will use organization's default currency

===========================
Escaped Character Examples
===========================

1)SELECT Id FROM Widget__C WHERE Name LIKE R%'
Select all widgets whose name begins with the letter 'R'.

2) SELECT Id FROM Widget__c WHERE Name LIKE 'R\%'
Select all widgets whose name exactly matches the two character sequence 'R%'.

3)SELECT Id FROM Widget__c WHERE Name LIKE 'R\%%'
Select all widgets whose name begins with the two character sequence 'R%'

==============================
Reserved characters Examples
==============================

Reserved characters, if specified in a SELECT clause as a literal string (between single quotes), must be escaped (preceded by the backslash \ character) in
order to be properly interpreted. An error occurs if you do not precede reserved characters with a backslash.

The following characters are reserved:
' (single quote)
\ (backslash)

For example, to query the Widget__c Name field for “Wally’s grommet,” use the following SELECT statement:

SELECT Id FROM Widget__c WHERE Name LIKE 'Wally\'s grommet'

==========
Order By
==========

SELECT Name FROM Widget__c ORDER BY Name DESC NULLS LAST

The following limitations apply to data types when using ORDER BY:

1) These data types are not supported: multi-select picklist, rich text area, long text area, and encrypted (if enabled).
2)All other data types are supported, with the following caveats:
a)convertCurrency() always sorts using corporate currency value, if available.
b)phone data does not include any special formatting when sorting, for example, non-numeric characters such as dash or parentheses are included in the sorting.
c)picklist sorting is defined by the picklist sort determined during setup.
d)You are limited to 32 fields in an ORDER BY query. If you exceed the limit, a malformed query fault is returned.

============================
Where Conditional Expression
=============================
You can use parentheses to define the order in which fieldExpressions are evaluated.
For example, the following expression is true

if fieldExpression1 is true and either fieldExpression2 or fieldExpression3 are true:
fieldExpression1 AND (fieldExpression2 OR fieldExpression3)

However, the following expression is true if either fieldExpression3 is true or both fieldExpression1 and fieldExpression2 are true.
(fieldExpression1 AND fieldExpression2) OR fieldExpression3

===========
Join
===========

1) Semi-Join Query
SELECT Id, Name FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won')

2) Reference Field Semi-Join Query
SELECT Id FROM Task WHERE WhoId IN (SELECT Id FROM Contact WHERE MailingCity = 'Chicago')

3) Anti-Join Query
SELECT Id FROM Account WHERE Id NOT IN (SELECT AccountId FROM Opportunity WHERE IsClosed = false)

4) Reference Field Anti-Join Query
SELECT Id FROM Opportunity WHERE AccountId NOT IN (SELECT AccountId FROM Contact WHERE LeadSource = 'Web')

5) Multiple Semi-Joins Query
SELECT Id, Name FROM Account WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName LIKE 'apple%') AND Id IN (SELECT AccountId FROM Opportunity WHERE isClosed = false )

===========
Set Based
===========

Select ID FROM Account Where ID IN : setAccountIds

===============
Relationship
===============

1) Parent to Child
SELECT Id, (SELECT Id from OpportunityLineItems) FROM Opportunity (Standard Version)
Select ID, (Select ID FROM Orders__r) FROM Account (Custom Object Version)

2) Child to Parent
SELECT Id, Name, Account.Name FROM Contact
Select ID, VCR__r.Name FROM Account

In a WHERE clause that checks for a value in a parent field, if the parent does not exist, the record is returned in version 13.0 and later,
but not returned in versions before 13.0.. For example:

SELECT Id FROM Model__c WHERE Widget__r.name = null

Model record Id values are returned in version 13.0 and later, but are not returned in versions before 13.0.

When designing relationship queries, consider these limitations:

1)Relationship queries are not the same as SQL joins. You must have a relationship between objects to create a join in SOQL.
2)No more than 35 child-to-parent relationships can be specified in a query. A custom object allows up to 25 relationships, so you can reference all the child-to-parent relationships for a custom object in one query.
3)No more than 20 parent-to-child relationships can be specified in a query.
4)In each specified relationship, no more than five levels can be specified in a child-to-parent relationship.
For example, Contact.Account.Owner.FirstName (three levels).
5)In each specified relationship, only one level of parent-to-child relationship can be specified in a query.
For example, if the FROM clause specifies Account, the SELECT clause can only specify the Contact or other objects at that level.
It could not specify a child object of Contact.

3) Polymorphic
A polymorphic relationship field in object being queried that can reference multiple object types.
For example, the What relationship field of an Event could be an Account, or a Campaign, or an Opportunity.

SELECT Id FROM Event WHERE What.TYPE IN ('Account', 'Opportunity')

======================
Query History Object
=======================

Custom objects and some standard objects have an associated history object that tracks changes to an object record.
You can use relationship queries to traverse a history object to its parent object.
For example, the following query returns every history row for Foo__c and displays the name and custom fields of Foo:

SELECT OldValue, NewValue, Parent.Id, Parent.name, Parent.customfield__c FROM foo__history
This example query returns every Foo object row together with the corresponding history rows in nested subqueries:

SELECT Name, customfield__c, (SELECT OldValue, NewValue FROM foo__history) FROM foo__c

============
WITH OFFSET
============
Use OFFSET to specify the starting row offset into the result set returned by your query.
SELECT Id, Name FROM Opportunity ORDER BY Name OFFSET 5

Limitations with OFFSET
========================
1)The maximum offset is 2,000 rows. Requesting an offset greater than 2,000 will result in a NUMBER_OUTSIDE_VALID_RANGE error.
2)OFFSET is intended to be used in a top-level query, and is not allowed in most sub-queries, so the following query is invalid and
will return a MALFORMED_QUERY error.
3)A sub-query can use OFFSET only if the parent query has a LIMIT 1 clause. The following query is a valid use of OFFSET in a sub-query.

==================
Aggregate Queries
===================
From API version 18.0 and later, you can use GROUP BY with aggregate functions, such as COUNT(), SUM() or MAX().

a) With GROUP BY

SELECT Stagename, COUNT(Id) FROM Opportunity GROUP BY Stagename
SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource
SELECT Stagename, SUM(amount) FROM Opportunity GROUP BY Stagename
SELECT CALENDAR_YEAR(CloseDate), COUNT(Id) FROM Opportunity GROUP BY CALENDAR_YEAR(CloseDate) ORDER BY CALENDAR_YEAR(CloseDate)


b) With GROUP BY ROLLUP
Same with GROUP BY, with additional ROLLUP, it add subtotal for aggregated data in the last row
SELECT Stagename, COUNT(Id) FROM Opportunity GROUP BY ROLLUP(Stagename)

c) With GROUP BY ROLLUP with 2 fields
SELECT Status, LeadSource, COUNTId) FROM Lead GROUP BY ROLLUP(Status, LeadSource)

d) HAVING in GROUP BY
You can use a HAVING clause with a GROUP BY clause to filter the results returned by aggregate functions, same with WHERE with normal query

SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource HAVING COUNT(Id) > 2

SELECT Widget__c, COUNT(Name) FROM Model__c GROUP BY Widget__c HAVING COUNT(Name) > 10 and Model_Number__c LIKE 'Sirius%'

===========================
Geolocation SOQL Queries
===========================

Following are some sample geolocation SOQL queries:

SELECT warehouse_location__latitude__s, warehouse_location__longitude__s FROM Warehouse__c
This query finds all of the warehouses that are stored in the custom object Warehouse. The list will display each warehouse’s latitude and longitude values.
Note the use of the separate field components for warehouse_location__c, to select the latitude and longitude components individually.


SELECT name__c, address__c FROM Warehouse__c WHERE DISTANCE(warehouse_location__c, GEOLOCATION(37.775,-122.418), “mi”) < 20
ORDER BY DISTANCE(warehouse_location__c, GEOLOCATION(37.775,-122.418), “mi”)

This query finds all of the warehouses in the custom object Warehouse that are within 20 miles of the geolocation 37.775°, –122.418°,
which is San Francisco. The list will show the name and address of each warehouse, but not its geocoordinates.
The nearest warehouse will be first in the list; the farthest location will be last.
Note that, when used in the DISTANCE function, you use the compound geolocation field warehouse_location__c directly.

Monday, June 10, 2013

Java Script for custom buttons in salesforce

Java Script for custom buttons in salesforce

The AJAX toolkit includes built-in support for invoking Apex through anonymous blocks or public webService methods.  
To do so, include the following lines in your AJAX code:

<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a result similar to the API's result type, but as a JavaScript structure.
Use a class WSDL. For example, you can call the following Apex class:

global class myClass { 
  webService static Id makeContact(String lastName, Account a) { 
        Contact c = new Contact(LastName = lastName, AccountId = a.Id); 
        return c.id; 
    }
}

By using the following JavaScript code:

var account = sforce.sObject("Account");
var id = sforce.apex.execute("myClass","makeContact",
                             {lastName:"Smith",
                              a:account});

The execute method takes primitive data types, sObjects, and lists of primitives or sObjects.
To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute. For example, to call the following Apex class:

global class myClass{ 
   webService static String getContextUserName() {
        return UserInfo.getFirstName();
   }
}

Use the following JavaScript code:

var contextUser = sforce.apex.execute("myClass", "getContextUserName", {});
Note:- If a namespace has been defined for your organization, you must include it in the JavaScript code when you invoke the class. For example, to call the above class, the JavaScript code from above would be rewritten as follows:
var contextUser = sforce.apex.execute("myNamespace.myClass", "getContextUserName", {});
Sample code:-

Create a global class with a webservice method and call that from custom button using javascript onClick event.

Create a global class
global class OutboundEmails {

WebService static void SendEmailNotification(string id) {

//create a mail object to send a single email.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

//set the email properties
mail.setToAddresses(new string[] {'EmailAddress here'});
mail.setSenderDisplayName('SF.com Email Agent');
mail.setSubject('A new reminder');
mail.setHtmlBody('an object with ID='+ id + ' is just clicked on.');

//send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail } );

}
}
And have a custom button with display type as "Detail Page Button" and Behaviour type as "Execute JavaScript", content source as "onClick javascript".

And the code for javascript
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}

sforce.apex.execute("OutboundEmails","SendEmailNotification", {id:"{!Case.CaseNumber}"});

These are Javascript Wrappers around the Force.com API, which allow you to make Calls to your apex code, enable you for javascript remoting etc.

These javascripts are built in and cannot be modified, but you can view them by typing it directly in your browser

Connection.js : https://ap1.salesforce.com/soap/ajax/25.0/connection.js
Apex.js : https://ap1.salesforce.com/soap/ajax/25.0/apex.js

replace the ap1 instance with your server instance.

Custom buttons can be of other type like URL, Visualforce page. After summer 13 release we also global actions with us and by help of them now it is very easy to create new record with some required  fields. Enjoy coding..


Tuesday, April 2, 2013

Using Standard Controller getRecord() Method in Salesforce


Using standard controller's "getRecord" method
There seems to be a common problem using the getRecord function, so I am going to write it down here.  This problem has haunted me a few times now.

Whenever you use a controller extension, extending a standard object, you can use the getRecord() to get the reference to the record.  For example, if you have an extension to the contact object, this can be what your Apex class looks like:

public class ContactExtension
{
    private Contact contact;

    public ContactExtension(ApexPages.StandardController sController)
    {
        this.contact = (Contact)sController.getRecord();
    }
}

Besides the obvious constructor, you will most likely have some other methods inside your class to manipulate the contact.  Let's say you want to provide a form so the user can change email address and phone number of the contact.  Your VisualForce class looks very simple

<apex:page standardController="Contact" extensions="ContactExtension">
    {!greeting}
    <apex:form>
        <apex:inputField value="{!contact.Email" />
        <apex:inputField value="{!contact.MobilePhone}" />
        <apex:commandButton action="{!save}" value="Save" />
    </apex:form>
</apex:page>

The {!greeting} is going to display some greeting messages.  That means we will need to write a getGreeting() method in the class.

If this is the definition of your getGreeting() inside the class,

public String getGreeting()
{
    return 'Hi ' + contact.FirstName + ' how have you been?  Please update the following.';
}

you will then get an error message that looks like this:

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.FirstName

Most of us think that as soon as we call the getRecord() method, then the entire record is loaded into the contact variable.  However if you have an object with 5000 fields, and you only need to use 2 or 3 in your Visualforce pages, do you think it really makes sense to load all 5000 fields for that record into the contact variable?  Probably not.

Then what can you do?  The easiest way is to do add this into your Visualforce page:
<apex:outputText value="{!contact.FirstName}"/>

If you say, but I don't want to display the contact name twice!  Then you can simply change this to:
<apex:outputText value="{!contact.FirstName}" rendered="false" />

By adding rendered="false", that will hide this variable.  Or perhaps use <apex:variable> instead, such as:
<apex:variable value="{!contact.FirstName}" var="contactFName" />

When you load this Visualforce page, the standard controller will scan through your Visualforce page and knows that you need this field, and when making the getRecord() method call, it automatically and implicitly adds this FirstName field into the SOQL.

Remember, if you want to use any field in your extension via the getRecord() method, you need to let it be known by making sure that the field exists in your Visualforce page!

(Another alternative is to write your own SOQL in your Apex class, but why make an extra SOQL call when you can avoid it?)

Saturday, January 5, 2013

Salesforce: Create Custom Fields using Eclipse

Today I had to add different data types fields to my Custom object (Metadata__c). I could have done this by manually creating each field, but the thought of clicking through over different screens didn't take my fancy. So, I thought I’d take the Force.com Metadata API for a spin. I decided to do it via the IDE.

Fortunately, there’s plenty of information available on this topic, the best of which are:

First I added my new Force.com project to IDE and then I simply added Metadata__c metadata to my project and it appeared in my Package Explorer.

Now I can see custom object details there in source tab.

So, It looks like as given below:---


<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
    <actionOverrides>
        <actionName>Accept</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Clone</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Delete</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Edit</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>List</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>New</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Tab</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>View</actionName>
        <type>Default</type>
    </actionOverrides>
    <deploymentStatus>Deployed</deploymentStatus>
    <enableActivities>true</enableActivities>
    <enableFeeds>false</enableFeeds>
    <enableHistory>true</enableHistory>
    <enableReports>true</enableReports>
    <label>Metadata</label>
    <listViews>
        <fullName>All</fullName>
        <filterScope>Everything</filterScope>
        <label>All</label>
    </listViews>
    <nameField>
        <displayFormat>META - {00000}</displayFormat>
        <label>Metadata Name</label>
        <trackHistory>false</trackHistory>
        <type>AutoNumber</type>
    </nameField>
    <pluralLabel>Metadata</pluralLabel>
    <searchLayouts/>
    <sharingModel>ReadWrite</sharingModel>
</CustomObject>


Now for adding custom adding custom fields. Please added XML in that source file given below and you can see change for the custom object by saving XML to the project and by refreshing the custom object definition page on browser.

Adding New Custom Fields:--

1. Auto Number

<fields>
        <fullName>Auto_Number__c</fullName>
        <description>Auto Number Creation.</description>
        <displayFormat>AN - {0000}</displayFormat>
        <externalId>false</externalId>
        <inlineHelpText>Auto Number Field</inlineHelpText>
        <label>Auto Number</label>
        <type>AutoNumber</type>
    </fields>

2. Checkbox

<fields>
        <fullName>Checkbox__c</fullName>
        <defaultValue>false</defaultValue>
        <description>This is a checkbox field.</description>
        <externalId>false</externalId>
        <label>Checkbox</label>
        <type>Checkbox</type>
    </fields>

3. Currency (14,2)

<fields>
        <fullName>Currency__c</fullName>
        <defaultValue>2000</defaultValue>
        <description>This is a currency field.</description>
        <externalId>false</externalId>
        <label>Currency</label>
        <precision>16</precision>
        <required>false</required>
        <scale>2</scale>
        <trackHistory>false</trackHistory>
        <type>Currency</type>
    </fields>

4. Date

<fields>
        <fullName>Date__c</fullName>
        <defaultValue>TODAY()</defaultValue>
        <description>This is a date field.</description>
        <externalId>false</externalId>
        <label>Date</label>
        <required>false</required>
        <type>Date</type>
    </fields>

5. Date Time

 <fields>
        <fullName>Date_Time__c</fullName>
        <defaultValue>Now()</defaultValue>
        <description>This is a Date Time Field.</description>
        <externalId>false</externalId>
        <label>Date Time</label>
        <required>false</required>
        <type>DateTime</type>
    </fields>

6. Email

<fields>
        <fullName>Email__c</fullName>
        <description>This is a Email field.</description>
        <externalId>false</externalId>
        <label>Email</label>
        <required>false</required>
        <trackHistory>false</trackHistory>
        <type>Email</type>
        <unique>false</unique>
    </fields>

7. Geolocation

    <fields>
        <fullName>Geolocation__c</fullName>
        <description>This is a Geostation field.</description>
        <displayLocationInDecimal>false</displayLocationInDecimal>
        <externalId>false</externalId>
        <label>Geolocation</label>
        <required>false</required>
        <scale>5</scale>
        <trackHistory>false</trackHistory>
        <type>Location</type>
    </fields>

8. Multi Select Picklist

    <fields>
        <fullName>Multi_Select_Picklist__c</fullName>
        <description>This is multi select picklist field alphabatically shorted and first value as default</description>
        <externalId>false</externalId>
        <label>Multi Select Picklist</label>
        <picklist>
            <picklistValues>
                <fullName>A</fullName>
                <default>true</default>
            </picklistValues>
            <picklistValues>
                <fullName>C</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>D</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>G</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>H</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>V</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>Y</fullName>
                <default>false</default>
            </picklistValues>
            <sorted>false</sorted>
        </picklist>
        <trackHistory>false</trackHistory>
        <type>MultiselectPicklist</type>
        <visibleLines>4</visibleLines>
    </fields>

9. Number

    <fields>
        <fullName>Number__c</fullName>
        <defaultValue>52</defaultValue>
        <externalId>false</externalId>
        <label>Number</label>
        <precision>18</precision>
        <required>false</required>
        <scale>2</scale>
        <trackHistory>false</trackHistory>
        <type>Number</type>
        <unique>false</unique>
    </fields>

10. Percent

    <fields>
        <fullName>Percent__c</fullName>
        <defaultValue>0.023</defaultValue>
        <description>This is a Percent Field.</description>
        <externalId>false</externalId>
        <label>Percent</label>
        <precision>18</precision>
        <required>false</required>
        <scale>2</scale>
        <trackHistory>false</trackHistory>
        <type>Percent</type>
    </fields>

11. Phone

    <fields>
        <fullName>Phone__c</fullName>
        <description>This is a phone field.</description>
        <externalId>false</externalId>
        <label>Phone</label>
        <required>false</required>
        <trackHistory>false</trackHistory>
        <type>Phone</type>
    </fields>

12. Picklist

    <fields>
        <fullName>Picklist__c</fullName>
        <description>This is a picklist field.</description>
        <externalId>false</externalId>
        <label>Picklist</label>
        <picklist>
            <picklistValues>
                <fullName>AD</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>FG</fullName>
                <default>false</default>
            </picklistValues>
            <picklistValues>
                <fullName>GG</fullName>
                <default>false</default>
            </picklistValues>
            <sorted>false</sorted>
        </picklist>
        <trackHistory>false</trackHistory>
        <type>Picklist</type>
    </fields>
    <fields>
        <fullName>Text_Area_Long__c</fullName>
        <defaultValue>&quot;Testing...&quot;</defaultValue>
        <description>This is a text area long field.</description>
        <externalId>false</externalId>
        <inlineHelpText>Text area long field help.</inlineHelpText>
        <label>Text Area Long</label>
        <length>32768</length>
        <trackHistory>false</trackHistory>
        <type>LongTextArea</type>
        <visibleLines>3</visibleLines>
    </fields>

13. Text Area Rich

    <fields>
        <fullName>Text_Area_Rich__c</fullName>
        <description>This is a Text Area rich type field.</description>
        <externalId>false</externalId>
        <inlineHelpText>Text Area Rich Help</inlineHelpText>
        <label>Text Area Rich</label>
        <length>32768</length>
        <trackHistory>false</trackHistory>
        <type>Html</type>
        <visibleLines>25</visibleLines>
    </fields>

14. Text Area

    <fields>
        <fullName>Text_Area__c</fullName>
        <defaultValue>&quot;Test Area Test&quot;</defaultValue>
        <description>This is the text area field.</description>
        <externalId>false</externalId>
        <inlineHelpText>Text Area field Help</inlineHelpText>
        <label>Text Area</label>
        <required>true</required>
        <trackHistory>false</trackHistory>
        <type>TextArea</type>
    </fields>

15. Text Encripted

    <fields>
        <fullName>Text_Encripted__c</fullName>
        <description>This is a text encripted type field.</description>
        <externalId>false</externalId>
        <inlineHelpText>Text Encripted field Help</inlineHelpText>
        <label>Text Encripted</label>
        <length>20</length>
        <maskChar>asterisk</maskChar>
        <maskType>all</maskType>
        <required>true</required>
        <trackHistory>false</trackHistory>
        <type>EncryptedText</type>
    </fields>

16. Text

    <fields>
        <fullName>Text__c</fullName>
        <caseSensitive>false</caseSensitive>
        <description>This is a text field.</description>
        <externalId>false</externalId>
        <label>Text</label>
        <length>23</length>
        <required>false</required>
        <trackHistory>false</trackHistory>
        <type>Text</type>
        <unique>true</unique>
    </fields>

17. URL

    <fields>
        <fullName>URL__c</fullName>
        <defaultValue>&quot;https://ssl.salesforce.com/&quot;</defaultValue>
        <description>This is a URL field.</description>
        <externalId>false</externalId>
        <inlineHelpText>URL field Testing...</inlineHelpText>
        <label>URL</label>
        <required>true</required>
        <trackHistory>false</trackHistory>
        <type>Url</type>
    </fields>

18. Master Detail (Master - Account)

<fields>
        <fullName>Account__c</fullName>
        <externalId>false</externalId>
        <label>Account</label>
        <referenceTo>Account</referenceTo>
        <relationshipLabel>Metadata</relationshipLabel>
        <relationshipName>Metadata</relationshipName>
        <relationshipOrder>0</relationshipOrder>
        <reparentableMasterDetail>false</reparentableMasterDetail>
        <trackHistory>false</trackHistory>
        <type>MasterDetail</type>
        <writeRequiresMasterRead>false</writeRequiresMasterRead>
    </fields>

19. Lookup Relationship (Parent -- Contact)

<fields>
        <fullName>Contact__c</fullName>
        <deleteConstraint>SetNull</deleteConstraint>
        <externalId>false</externalId>
        <label>Contact</label>
        <referenceTo>Contact</referenceTo>
        <relationshipLabel>Metadata</relationshipLabel>
        <relationshipName>Metadata</relationshipName>
        <required>false</required>
        <trackHistory>false</trackHistory>
        <type>Lookup</type>
    </fields>

20. Formula Field

<fields>
        <fullName>Formula_Text__c</fullName>
        <externalId>false</externalId>
        <formula>Text__c</formula>
        <label>Formula Text</label>
        <required>false</required>
        <trackHistory>false</trackHistory>
        <type>Text</type>
        <unique>false</unique>
    </fields>

21.  List View

<listViews>
        <fullName>My_List_View</fullName>
        <columns>NAME</columns>
        <columns>Account__c</columns>
        <columns>Auto_Number__c</columns>
        <columns>Checkbox__c</columns>
        <columns>Contact__c</columns>
        <columns>Currency__c</columns>
        <filterScope>Everything</filterScope>
        <label>My List View</label>
    </listViews>

I think this will be useful.. Enjoy Coding,