Thursday, March 20, 2014

Fixed headertable in visualforce page.

Before Implementing this create a custom object and the fields with number data type.
Create one more (Master-detail)(Account-Custom object) relationship.

Vf page:


<apex:page StandardController="Account" extensions="CustomClass" tabStyle="Account">
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script src="{!URLFOR($Resource.jquery_vfFloatingHeaders)}"></script>
    <style>
        .tableContainer
        {
            height:175px;
            width: 100%;
            overflow: auto;
        }    
        .floatingStyle
        {
            position:relative;
        }
    </style>
    <script>
    $(document).ready(function() {
        $('.floatingHeaderTable').vfFloatingHeaders();
    });
    </script>
    <apex:pageblock mode="maindetail">
        <div class="bPageBlock brandSecondaryBrd apexDefaultPageBlock secondaryPalette">
        <div class="pbBody" >
        <div class="tableContainer" >
                    <table class="list floatingHeaderTable">
                        <thead class="rich-table-thead" >
                            <tr class="headerRow">
                                <apex:outputText value="No Records To Display" rendered="{!if(records.size == 0,'true','false')}"></apex:outputText>
                                <!-- Table for displaying field label -->
                                <apex:repeat rendered="{!(records.size != 0)}" value="{!fields}" var="f">
                                    <th style="text-align:{!if(f.Label = 'Product Code','left' , 'Right')};width:{!if(f.Label = 'Product Code','150px' , '')};" class="headerRow   floatingStyle" scope="col">
                                        {!f.Label}
                                    </th>
                                </apex:repeat>
                            </tr>
                        </thead>
                         <tbody>
                            <apex:repeat value="{!records}" var="item">
                                <!-- ListRow -->
                                <tr class="dataRow even first">
                                    <apex:repeat value="{!vfFields}" var="itm">
                                       <td align="{!if(itm = 'CustomObject__c(Roll up) Field', 'left', 'right')}" class=" zen-deemphasize" scope="col">                                    
                                            <apex:outputtext rendered="{!item[itm] != null && itm = 'CustomObject__c(Roll up) Field'}" value="{!item[itm]}"/>
                                            <apex:outputtext rendered="{!item[itm] != null && itm != 'CustomObject__c(Roll up) Field'}" value="{0, number,###,###,###,##0.00}">
                                                <apex:param value="{!item[itm]}"/>
                                            </apex:outputtext>
                                            <apex:outputtext rendered="{!if(itm = 'CustomObject__c(Roll up) Field' && item[itm] == null, True, False)}" value="Total" style="font-weight:900;"/>
                                       </td>
                                    </apex:repeat>
                                </tr>
                            </apex:repeat>                
                        </tbody>
                    </table>
</div>
</div>
</div>
    </apex:pageblock>
</apex:page>

Apex Controller:
//Custom Object and Account should have master-detail Relationship

public class CustomClass  {
    //Account
    public Account account {get; set;}

    //List to hold Custom Object records
    public List<AggregateResult> records{get; set;}

    //List to hold fields
    public List<Schema.FieldSetMember> fields{get; set;}

    public List<String> vfFields {get; set;}

    //Standard Controller
    public CustomClass (ApexPages.StandardController controller) {    
        //Get record
        account = (Account)controller.getRecord();
   
        //Memory allocation
        records = new List<AggregateResult>();
   
        //Method calling
        funds();
    }

    //This method is to get related fund data for Account record.
    public void funds() {
        String fieldvalue='';
        String namespaceval = '';
        Integer namespaceLength = 0;

        LIST<ApexClass> namespaceprefix=[SELECT NamespacePrefix FROM ApexClass WHERE Name = 'CustomObject__c'];
   
        if(namespaceprefix.size()>0)
        {
            namespaceval = namespaceprefix[0].NamespacePrefix + '__';
            namespaceLength = namespaceval.length();
        }
           
        //populate the list with the fields    
        fields = Schema.SObjectType.CustomObject__c.fieldSets.FieldSetName.getFields();
   
        // In visualforcepages the alias should not be more than 25 characters, So do concatenate .
        for(Schema.FieldSetMember f:fields){
            fieldvalue +=f.getFieldPath().subString(namespaceLength) + ',';
            /*
            if(f.getType() != Schema.DisplayType.String){
   
            System.debug(f.getFieldPath());
            fieldvalue +=f.getFieldPath().subString(0,f.getFieldPath().length()-3)+',';
            }else{
                fieldvalue +=f.getFieldPath()+',';
            }*/
            //System.debug(vfFields);
        }  
   
        fieldvalue = fieldvalue.removeEnd(',');
        vfFields=fieldvalue.split(',');

        records = getResultById(account.Id , fields);
    }
    public List<AggregateResult> getResultById(Id entityId , List<Schema.FieldSetMember> fields) {
   
        //String to hold soql string
        System.debug(entityId );
        String query = 'SELECT ';
        String querywhere = ' ';
        String namespaceval = ' ';
        Integer namespaceLength = 0;

        LIST<ApexClass> namespaceprefix=[SELECT NamespacePrefix FROM ApexClass WHERE Name = 'CustomObject__c'];
   
        if(namespaceprefix.size()>0)
        {
            namespaceval = namespaceprefix[0].NamespacePrefix + '__';
            namespaceLength = namespaceval.length();
        }    
   
        //loop through fields
        for(Schema.FieldSetMember f : fields) {
            if(f.getType() != Schema.DisplayType.String)
            {
                query += 'sum('+ f.getFieldPath()  + ') ' + f.getFieldPath().subString(namespaceLength)  + ', ';
                querywhere += 'or (' + f.getFieldPath() + ' != null) ';
            }
            else
            {
                query += f.getFieldPath() + ' ' + f.getFieldPath().subString(namespaceLength)  + ', ';
            }
        }
           
        query = query.removeEnd(', ');
        query += ' FROM '+ namespaceval + 'CustomObject__c WHERE Account(Master-Detail Field) =: entityId';            
 
        querywhere = querywhere.replaceFirst('or', 'and (');
        query += querywhere + ')';
        query += ' group by rollup ('+ namespaceval + 'CustomField__c)';
   
        List<AggregateResult> lstfundSummary = Database.query(query);
        System.debug('\n lstfundSummary'+lstfundSummary);
        return lstfundSummary;
    }
}





Wednesday, March 19, 2014

Deploy code from Sandbox to Production

How to deploy code from Sandbox to Production Preface:

this post is part of the Write Your First Trigger From Start to Finish series. 

 We’ll be deploying our simple trigger from sandbox to our normal Salesforce (aka production) org.
If you’re not using a sandbox connected to a real org, you don’t need to deploy –
your code is already live!

 We’ll be using a standard Salesforce feature called change sets to deploy.

 Step 0: Connect your Sandbox and Production orgs
             Setup >> Deploy >> Deployment Connections You’ll only need to do this once!
 Step 1: Navigate to the Outbound Change Sets page in Sandbox.
             Setup >> Deploy >> Outbound Change Sets
 Step 2: Add all necessary components to a new change set, then upload to Production

 In this case, we’ll add both the ForceForecasting trigger and the TestForceForecasting Apex class.
We can add tons of other things like custom objects and fields, but don’t worry about that for now!

 Step 3: Login to your production org, find the Inbound Change Set, and deploy!
             Setup >> Deploy >> Inbound Change Sets

 Once you hit the “Deploy” button (no need to validate!), you’ll have to wait a few minutes for the changes to go through. Grab yourself a nice cup of coffee while you wait and give yourself a pat on the back for deploying your first trigger!

Monday, March 17, 2014

Dynamic Columns in visualforce using Fieldset


Dynamically bind your columns in visual force page block table
All you need is
1- Fieldset on any salesforce standard or Custom Object
2- Apex Class(Controller)
3- Visualforce Page.

1- Fieldset- fieldset is used to dynamically bind the fields in the visualforce page or in apex class. For this first you need to create a field set like --
  1.a- Go to Setup->Customize->Account->FieldSet->New
  1.b- write the Name Account_Fields
  1.c- Now you will get a view like page layout. So you need to drag some field to the Field set Section like you do in Page Layouts.
  1.d- your field set is now created.

2- create an apex class with following code:-

public class AccountFieldSetData {

public list<AggregateResult>lstAccount {get;set;}
public AccountFieldSetData() { 
 String SOQL = ''; 
 SOQL = 'SELECT '; 
 for(Schema.FieldSetMember thisField : this.getFields()) { 
 SOQL += thisField.getFieldPath() + ', '; 
 } 
 SOQL += ' Id from Account limit 50'; 
 lstAccount = database.query(SOQL); 
 } 
 private List<AggregateResult>getFields() {
 return SobjectType.Account.FieldSets.Account_Fields.getFields(); 
 } 
 }

3- Create a visualforce page with following code---


<apex:page controller="Demo_DynamicColumnsInPBTable">
  <apex:sectionHeader title="Dynamic Columns in PageBlock Table"/>
  <apex:form >
      <apex:pageBlock >
          <apex:pageblockTable value="{!lstAccount}" var="account" >
                <apex:repeat value="{! $ObjectType.Account.Fieldsets.Account_Fields}" var="varFieldName">
                    <apex:column value="{! account[varFieldName]}"/>
                </apex:repeat>
            </apex:pageblockTable>
      </apex:pageBlock>
  </apex:form>
</apex:page>


Saturday, March 15, 2014

Avoid hitting the concurrent Batch Apex limit with error

- Count how many current jobs are being executed.
- This information is stored in the AsyncApexJob table.
- Before calling the Database.executebatch() method within a scheduled class,

you should try something like:

 //check if there are 5 active batch jobs

if ([SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex' AND (Status = 'Processing' OR Status = 'Preparing')] < 5])
{
Database.executeBatch(batchClassInstance);
}
else
{
//schedule this same schedulable class again in 30 mins
nameOfYourSchedulableClass sc = new nameOfYourSchedulableClass();
Datetime dt = Datetime.now() + (0.024305); // i.e. 30 mins
String timeForScheduler = dt.format('s m H d M \'?\' yyyy');
Id schedId = System.Schedule('MatrixRetry'+timeForScheduler,timeForScheduler,sc);
}

- In the same 'else' clause you can send an e-mail to yourselves so you're notified that the job will run a bit later than normal.

Note: - You can have more than 5 scheduled classes that will call Database.executeBatch() in a Queued status

Friday, March 14, 2014

Remove Customize page link from a Apex:detail Visualforce page

The apex detail tag has a title attribute. Setting this to false removes the links and title block at the top of the page. The title blocks can be added back by the apex:sectionheader tag.
Example:
<apex:page standardController="Account">
    <apex:sectionHeader title="Account1" subtitle="Test 1"/>
    <chatter:feed entityId="{!$CurrentPage.parameters.id}"/>
    <apex:detail subject="{!$CurrentPage.parameters.id}" title="false" relatedList="true"/>
</apex:page>

Enable Global Search

To see the Global Search Feature, turn on "Chatter and Global Search features" under
Your Name | Setup | Customize | Chatter | Settings.
Click Edit and select enable under the Chatter Settings.

Add a link to my email signature.

Go to: Setup | Personal Setup | Email | My Email Settings
- Enter the path to the website in the Signature box enclosed in HTML tags as follows

<a href="enter website address here">Enter words that display for link here</a>

For example:
>a href="http://login.salesforce.com">Link to Salesforce Login</a>

Click Save.

**NOTE** If the link does not show, type the coding into the box rather than copying/pasting as sometimes extra characters can get attached with the cut and paste process.

When sending an email from Salesforce, you need to make sure the emails are in HTML format.
On the web page to write an email (after buttons "send an email"), locate the section "Email Format". It's at the top of the page, on the right near the "To" field.
- If it says "HTML", you are ok.
- If it says "Text-Only", you need to click on "Switch to HTML".

If you send an email in "Text-Only" with the modified signature, the logo will not appear, and the signature will include as <a href="enter website address here">Enter words that display for link here
instead of the highlighted words that click to the website.

Export data in Excel or PDF format using Visualforce


Below is code that loops over Contact ID and Name fields

=========================================================
To Download PDF VISUALFORCE Page
=========================================================

<apex:page controller="contactquery" renderas="pdf" showheader="false">
    <apex:pageblock title="Export Results">
        <apex:pageblocktable value="{!cs}" var="contact">
            <apex:column value="{!contact.ID}">
            <apex:column value="{!contact.Name}">
        </apex:column></apex:column></apex:pageblocktable>
    </apex:pageblock>
</apex:page>

=========================================================
Download Excel VISUALFORCE Page
=========================================================

<apex:page cache="true" contenttype="application/vnd.ms-excel#SalesForceExport.xls" controller="contactquery">
    <apex:pageblock title="Export Results">
        <apex:pageblocktable value="{!cs}" var="contact">
            <apex:column value="{!contact.ID}">
            <apex:column value="{!contact.Name}">
        </apex:column></apex:column></apex:pageblocktable>
    </apex:pageblock>
</apex:page>

=========================================================
Query Controller (Query the data you need)
=========================================================

public class contactquery{
    public List<contact> cs{get; set;}
    public contactquery()
    {
    cs = new List<contact>();
       for (Contact c : [Select id, Name from Contact])
       {    
           cs.add(c);
       }
    }
}

Thursday, March 13, 2014

Displaying AggregateResult on Visualforce

I wanted to display records from an aggregate query on my visualforce page. I expected this to be pretty straight forward but it turns out there are many ways to get this done and most solutions on the forums were not as straight forward as I expected.

I was storing my results in a list of AggregateResult sobjects. Following is the code of my controller extension.

Controller Method:

public List<AggregateResult> resultValue() {
        AggregateResult[] results = [SELECT Name, Count(Id) Quantity FROM Opportunity GROUP BY  Name];
return results;
    }

Visualforce Page:

<apex:page controller="TestController">
    <apex:form >
         <apex:repeat value="{!results}" var="result">
            {!result.Name}: {!result.Quantity}
        </apex:repeat>
    </apex:form>

</apex:page>

Pass sObjects into future methods for DML - Salesforce


The Inut string that accepts would be JSON formated string.
public class Async
{
/***********************/ /* ASYNC DML METHODS */ /***********************/
    // insert sobjects

@future
public static void insertSObjects(String jsonString)
{
List<SObject> sObjs = new List<SObject>();
try
{
sObjs = (List<SObject>) JSON.deserialize(jsonString, List<SObject>.class);
}
catch (Exception e)
{
System.debug('Error in JSON deserialization');
}
if(!sObjs.isEmpty())
{
try
{
insert sObjs;
}
catch (Exception e)
{
System.debug('Error inserting SObjects');
}
}
}
// upsert sobjects
@future
public static void upsertSObjects(String jsonString)
{
List<SObject> sObjs = new List<SObject>();
try
{
sObjs = (List<SObject>) JSON.deserialize(jsonString, List<SObject>.class);
}
catch (Exception e)
{
System.debug('Error in JSON deserialization');
}
if(!sObjs.isEmpty())
{
try
{
upsert sObjs;
}
catch (Exception e)
{
System.debug('Error upserting SObjects');
}
}
}

// update sobjects
@future
public static void updateSObjects(String jsonString)
{
List<SObject> sObjs = new List<SObject>();
try
{
sObjs = (List<SObject>) JSON.deserialize(jsonString, List<SObject>.class);
}
catch (Exception e)
{
System.debug('Error in JSON deserialization');
}
if(!sObjs.isEmpty())
{
try
{
update sObjs;
}
catch (Exception e)
{
System.debug('Error updating SObjects');
}
}
}

// delete sobjects

@future
public static void deleteSObjects(String jsonString)
{
List<SObject> sObjs = new List<SObject>();
try
{
sObjs = (List<SObject>) JSON.deserialize(jsonString, List<SObject>.class);
}
catch (Exception e)
{
System.debug('Error in JSON deserialization');
}
if(!sObjs.isEmpty())
{
try
{
delete sObjs;
}
catch (Exception e)
{
System.debug('Error deleting SObjects');
}
}
}


/***********************/ /* HELPER METHODS */ /***********************/
// list of sobjects
public static String prepare(List<SObject> sObjs)
{
try
{
return JSON.serialize(sObjs);
}
catch (Exception e)
{
System.debug('Error in SObject List serialization');
}
return null;
}

// single sobject
public static String prepare(SObject sObj)
{
try
{
return JSON.serialize(new List<SObject>{sObj});
}
catch (Exception e)
{
System.debug('Error in SObject serialization');
}
return null;
}
}

Usage // EXAMPLE // 1. Query some leads

List<Lead> lds = [SELECT Id, FirstName, LastName FROM Lead LIMIT 2];

// 2. Make some changes

for(Lead l : lds)
{ l.FirstName = 'BLAHHH'; }
// 3. Use the prepare() helper method to serialize to JSON, then call the appropriate DML function

Async.updateSObjects(Async.prepare(lds));
// RESULT: Your DML is offloaded to an async request

Accessing Custom Settings


You can access custom settings from formula fields, validation rules, Apex, and the SOAP API.

Only the hierarchy custom settings can be accessed from the Formula fields
Syntax: {!$Setup.CustomSettingName__c.CustomFieldName__c}.
 Eg:  {!$Setup.Twillo__c.AccessLogin__c}

Accessing List Custom Setting

To get the list custom setting Dataset values

Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll(); 

This will store the data in the map which is a key value pair. Key will be the name of the data. 

 You can access all the list custom setting values using : 
 List<CustomSettingName__c> objectinstance=CustomSettingName__c.getAll().values() 

 this will be a collection of list.
From this you can access the specific data set value. 

 CustomSettingName__c mc = CustomSettingName__c.getValues(data_set_name);


From the above example the data_set_name name will be asas

Accessing Hierarchy Custom Setting

To get the hierarchy custom setting Dataset values
 CustomSettingName__c mc = CustomSettingName__c.getOrgDefaults();

 if you do specified any profile to the custom setting. 
Then access the custom setting in the following way 
 CustomSettingName__c mc = CustomSettingName__c.getInstance(Profile_ID); 

 Use the Privacy as Public if the custom setting are to be exposed to the API.

Labels

visualforce page ( 13 ) apex integration ( 5 ) apex trigger ( 4 ) csv file from vf page ( 4 ) javascript ( 4 ) csv visualforce page ( 3 ) Too many ( 2 ) call out ( 2 ) integration ( 2 ) rest api ( 2 ) salesforce rest api ( 2 ) salesforce to salesforce integration ( 2 ) sfdc rest api ( 2 ) trigger ( 2 ) 15 digit to 18 digit ( 1 ) DML rows in Apex ( 1 ) Date Conversion ( 1 ) Date/Time conversion ( 1 ) Deploy ( 1 ) Objects to Future Annotated Methods ( 1 ) SFDC limits ( 1 ) Sobject to Future Annotated Methods ( 1 ) Test Class ( 1 ) TimeZone Conversion ( 1 ) Too many dml rows ( 1 ) Too many future calls ( 1 ) annotations ( 1 ) apex code ( 1 ) closed opportunities ( 1 ) commit ( 1 ) convert ( 1 ) create records ( 1 ) csv create records ( 1 ) custom setting ( 1 ) deployment ( 1 ) deployment changeset ( 1 ) disable apex class ( 1 ) disable apex trigger ( 1 ) disable in production ( 1 ) document ( 1 ) download ( 1 ) field name ( 1 ) formula fields ( 1 ) iframe ( 1 ) inactive ( 1 ) intellisense ( 1 ) jsforce ( 1 ) limits ( 1 ) matrix report in vf page ( 1 ) multi select ( 1 ) multi select salesforce ( 1 ) multiselect ( 1 ) paypal ( 1 ) picklist ( 1 ) record type ( 1 ) rollback ( 1 ) salesforce limits ( 1 ) salesforce list ( 1 ) salesforce map ( 1 ) salesforce rest ( 1 ) salesforce set ( 1 ) salesforce1 ( 1 ) sandbox deployment ( 1 ) sfdc collection ( 1 ) sfdc list ( 1 ) sfdc map ( 1 ) sfdc rest ( 1 ) sfdc set ( 1 ) uncommitted ( 1 ) updated field ( 1 ) user ( 1 ) validation rule opportunity ( 1 ) validation rules opportunities ( 1 ) vf page ( 1 )

Ad