Thursday, May 31, 2012

Create Multiple Accounts:

Create Multiple Accounts:
This is a  simple solution for create multiple accounts at a time.


public class multiAccountInsert{


    public List<Account> accts {get; set;}
   
    public multiAccountInsert(){
        accts = new List<Account>();
        accts.add(new Account());
    }
   
    public void addrow(){
        accts.add(new Account());
    }
   
    public PageReference save(){
        insert accts;
        PageReference home = new PageReference('/001/o');
        home.setRedirect(true);
        return home;
    }
}


<apex:page controller="multiAccountInsert">
    <apex:form >
        <apex:pageBlock >
       
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" rerender="error"/>
            </apex:pageBlockButtons>
       
            <apex:pageBlockTable value="{!accts}" var="a" id="table">
                <apex:facet name="footer">
                    <apex:commandLink value="Add Row" action="{!addRow}" rerender="table,error"/>
                </apex:facet>
                <apex:column headerValue="Name">
                    <apex:inputField value="{!a.Name}"/>
                </apex:column>
                <apex:column headerValue="Billing City">
                    <apex:inputField value="{!a.BillingCity}"/>
                </apex:column>                      
            </apex:pageBlockTable>
           
        </apex:pageBlock>
    </apex:form>
</apex:page>

System.runAs():

System.runAs():
This post resembles how you can use runas method of system class for testing your code by profile wise or user wise.


public class TestRunAs2 {
    public static testMethod void test2() {
        Profile p = [SELECT Id FROM profile WHERE name='Standard User'];
        User u2 = new User(alias = 'newUser', email='newuser@testorg.com',
        emailencodingkey='UTF-8', lastname='Testing', 
        languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,
        timezonesidkey='America/Los_Angeles', username='newuser@testorg.com');


        System.runAs(u2) {    
          // The following code runs as user u2.
          // all your test data, created here in
          // this block will not run in system mode. 
          // So access to org level data 
          // will be pretty limited


          // Create all your Test Data + Structures till here
          // use startTest() to give some extra buffer
          // to your real test code
          Test.startTest();
            // Do any extra DML and other stuff  
            // you have more bandwidth now.
          Test.stopTest();
        }
         
        // Any other validation and DML statements
        // if required to validate the results.
         
    }
}

Tuesday, May 29, 2012

Group BY IN SOQL:

Group BY IN SOQL:
This example shows how you can group records on a field.The following example is a straight and simple explains how to group records on closed date for opportunities list.
public class TestGroupBy
{
public list<AggregateResult> lstAR = new list<AggregateResult>();
/*
Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a read-only sObject and is only used for query results.
Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example, you could find the count of all opportunities for a CloseDate.


*/
public TestGroupBy()
{
lstAR = [SELECT CloseDate, COUNT(id) Total FROM Opportunity GROUP BY CloseDate];
}


public list<OppClass> getResults()
{
list<OppClass> lstResult = new list<OppClass>();
for (AggregateResult ar: lstAR)
{
oppClass objOppClass = new oppClass(ar);
lstResult.add(objOppClass);
}
return lstResult;
}


class oppClass
{
public Integer Total
{ get;set; }


public Date CloseDate
{ get;set; }


public oppClass(AggregateResult ar)
{
//Note that ar returns objects as results, so you need type conversion here
Total = (Integer)ar.get('Total');
CloseDate = (Date)ar.get('CloseDate');
}
}
}


<apex:page controller="TestGroupBy">
  <apex:pageBlock title="Test Group By">
      <apex:pageBlockTable value="{!Results}" var="ar">
          <apex:column headerValue="Number of Opportunities" value="{!ar.Total}"/>
           <apex:column headerValue="Close Date" value="{!ar.CloseDate}"/>
      </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

Sunday, May 27, 2012

తెలుగు జాతి గర్వించ దగ్గ నటులు

తెలుగు జాతి గర్వించ దగ్గ నటులు మన అన్న నందమూరి తారక రామారావు గారు.తెలుగు జాతికి పెద్ద పండగ రోజు అన్న గారి పుట్టిన రోజు .అలాంటి మహా మనిషి ప్రజల దైవం మళ్లీ పుట్టాలి అని ఆ భగవంతున్ని ప్రార్దిస్తూ అన్న గారికి జన్మదిన శుభాకాంక్షలు .......జోహార్ అన్న ఎన్టీర్



Saturday, May 26, 2012

RETURN URL FOR SEARCH:

RETURN URL FOR SEARCH:
This is a good example who is looking for url on search.The code looks like this




public class RetUrlSearchController
{
 public String nameQuery {get; set;}
 public List<Account> accounts {get; set;}

 public PageReference executeSearch()
 {
  String queryStr='%' + nameQuery + '%';
  accounts=[select id, Name, BillingStreet
            from Account
            where name like :queryStr];
           
  return null;
 }

 public RetUrlSearchController()
 {
  // if query appears in URL, execute it
  String urlQuery=ApexPages.currentPage().getParameters().get('query');
 
  if ( (null!=urlQuery) && (0!=urlQuery.length()) )
  {
   nameQuery=urlQuery;
   executeSearch();
  }
 }
}

<apex:page controller="RetUrlSearchController">
  <apex:form >
    <apex:pageBlock >
      <apex:pageBlockSection title="Criteria">
      <apex:outputLabel value="Enter Name Snippet"/>
      <apex:inputText value="{!nameQuery}"/>
      <apex:commandButton action="{!executeSearch}" value="Search"/>
   </apex:pageBlockSection>
    
   <apex:pageBlockTable value="{!accounts}" var="acc">
      <apex:column headerValue="Name">
         <apex:outputLink value="/{!acc.id}/e?retURL={!URLENCODE('/apex/RetUrlSearchPage?query='+nameQuery)}">{!acc.Name}</apex:outputLink>
      </apex:column>
      <apex:column value="{!acc.BillingStreet}"/>
   </apex:pageBlockTable>
 </apex:pageBlock>
  </apex:form>
</apex:page>


Friday, May 25, 2012

Chatter Follow Multiple Items:

Chatter Follow Multiple Items:
This post related to chatter follow on multiple records at a time .The visualforce looks like this 






<apex:page standardcontroller="Position__c" recordsetvar="positions" >
  <apex:sectionHeader title="Chatter" subtitle="Follow Positions"/>
  <apex:form >
  <apex:pageBlock >    
      <apex:pageBlockButtons >
          <apex:commandButton value="Previous" action="{!previous}"/>
          <apex:commandButton value="Next" action="{!next}"/>
          <apex:commandButton value="Cancel" action="{!cancel}"/>
      </apex:pageBlockButtons>
      <apex:pageBlockSection columns="1">
          <apex:pageBlockTable value="{!positions}" var="p">
              <!-- TODO: Add a column with the header "Follow / Unfollow" that allows the user to follow the position -->
              <apex:column headerValue="Follow / Unfollow">
                  <chatter:follow entityId="{!p.id}"/>
              </apex:column>
              <apex:column headerValue="{!$ObjectType.Position__c.fields.name.label}">
                  <apex:outputLink value="/{!p.id}">
                      {!p.name}
                  </apex:outputLink>
              </apex:column>
              <apex:column value="{!p.Department__c}"/>
              <apex:column value="{!p.Hiring_Manager__c}"/>
              <apex:column value="{!p.Status__c}"/>
              <apex:column value="{!p.Sub_Status__c}"/>
          </apex:pageBlockTable>
      </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>
</apex:page>

Thursday, May 24, 2012

Dynamic View On Visualforce:

Dynamic View On Visualforce:
How to limit page view by sending select option values in controller .In this example you can find a drop down list contains one of the standard field on account object (Type).If you would like to control your page display as of selected drop down list code looks like this




public class myPageController {
private Account acc = new Account();
private List<Account> accs;
private string selectedAccount;
public Account getAccount()
{
return acc;
}
public void setAccount(Account a)
{
acc = a;
}
public List<Account> getAccounts()
{
return accs;
}
public string getSelectedAccount()
{
return selectedAccount;
}
public void setSelectedAccount(string value)
{
selectedAccount = value;
}
public PageReference ViewAccounts()
{
if (acc.Type == null)
{
//view a message because validation has failed.
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Validation Failed: Select an item fron the dropdown list.'));
return null;
}
string AccountType = acc.Type;
accs = [Select id, name, type from Account where type= :AccountType limit 20];
if (accs == null || accs.size() == 0)
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'No data found to be shown.'));
}
return null;
}
public PageReference ShowSelected()
{
if (selectedAccount != null && selectedAccount != '')
{
for(Account a: accs)
{
if (a.Id == selectedAccount)
{
string Msg = a.Name + ' Account is selected.';
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,Msg ));
}
}
}
return null;
}
}








<apex:page controller="myPageController" tabStyle="Account">
<apex:form >
<apex:sectionHeader title="My Page" />
<apex:pageBlock title="" id="pageBlock">
<apex:pageBlockButtons location="top">
<apex:inputField id="accountType" value="{!Account.Type}" />
<apex:commandButton value="View" action="{!ViewAccounts}" id="theButton" rerender="pageBlock"></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageMessages ></apex:pageMessages>
<!-- defines a javascript function which calls a Controller's method -->
<apex:actionFunction action="{!ShowSelected}" name="RowMethodCall" rerender="pageBlock" status="status">
<apex:param name="selectedAccount" assignTo="{!selectedAccount}" value=""/>
</apex:actionFunction>
<!-- define a start facet within the actionStatus that has a div with defined id visible to the whole HTML document -->
<apex:actionStatus id="status">
<apex:facet name="start">
<div id="statusTemplate">Working...</div>
</apex:facet>
</apex:actionStatus>


<apex:pageBlockTable value="{!accounts}" var="a" rendered="{!NOT(ISNULL(accounts))}">
<apex:column >
<apex:facet name="header">Account Name</apex:facet>
<apex:outputLink value="/{!a.Id}" target="_blank">{!a.Name}</apex:outputLink>
</apex:column>
<apex:column value="{!a.type}"></apex:column>
<apex:column >
<apex:facet name="header">Action</apex:facet>
<a href="javascript:DoTask('{!a.Id}');">Execute</a>
<div style="display:none" id="{!a.Id}">
Processing {!a.Name} ...
</div>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
<script type="text/javascript">
function DoTask(accountId)
{


var accountStatus = document.getElementById(accountId);
if (accountStatus && accountStatus.innerHTML)
{
document.getElementById('statusTemplate').innerHTML = accountStatus.innerHTML;
}


RowMethodCall(accountId);
}
</script>
</apex:form>
</apex:page>



Wednesday, May 23, 2012

Integrating Google Maps :

Integrating Google Maps :
User Interface is a part of Cloud Architecture ,You can see google map on a page for a billing address or any other information on a google map using visualforce page.It is simple and also can deploy to production since you don't worry about code coverage since it doesn't have any custom controller.This simple example for account object billing address shows on detail page of account (section created on page layout drag the visualforce page into that section).The code looks like this



<apex:page standardController="Account">

<script src="http://maps.google.com/maps?file=api">
</script>

<script type="text/javascript">

var map = null;
var geocoder = null;

var address = "{!Account.BillingStreet}, {!Account.BillingPostalCode} {!Account.BillingCity}, {!Account.BillingState}, {!Account.BillingCountry}";

function initialize() {
if(GBrowserIsCompatible())
{
  map = new GMap2(document.getElementById("MyMap"));
  map.addControl(new GMapTypeControl());
  map.addControl(new GLargeMapControl3D());

  geocoder = new GClientGeocoder();
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        document.getElementById("MyMap").innerHTML = address + " not found";
      } else {
        map.setCenter(point, 13);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.bindInfoWindowHtml("Account Name : <b><i> {!Account.Name} </i></b>
 Address : "+address);
      }
    }
  );
}
}
</script>


<div id="MyMap" style="width:100%;height:300px"></div>
<script>
    initialize() ;
</script>

</apex:page>



Tuesday, May 22, 2012

Searching & Pagination:

Searching & Pagination:
In this example you can search records using text as you are observing like global search also you can control Number of rows per page using pagination concept in controller .


First part of this requirement design controller ,Consider Searching on Standard Contact Object and the controller looks like this



public class pagingControllerForUser
{
    public List<Contact> AllSearchUsers
    {
        get
        {
            if(con != null)
                return (List<Contact>)con.getRecords();
            else
                return null ;
        }
        set;}
    
    public Contact usr {get; set;}
    
    //Controller
    public pagingControllerForUser()
    {
        AllSearchUsers = new List<Contact>() ;
        usr = new Contact() ;
    }
    
     public PageReference Search()
    {   
        if(usr.Name != null)
        {
            con = new ApexPages.StandardSetController(Database.getQueryLocator([select Id , name ,FirstName,LastName, email , phone from Contact where name = :usr.Name or firstname=:usr.Name or lastname=:usr.name]));


            // sets the number of records in each page set
            con.setPageSize(5);
        }
        else
        {
            con = null;
        }
        return null ;
    }
    
    //Instantiate the StandardSetController
    public ApexPages.StandardSetController con{get; set;}
    
    //Boolean to check if there are more records after the present displaying records
    public Boolean hasNext
    {
        get
        {
            return con.getHasNext();
        }
        set;
    }


    //Boolean to check if there are more records before the present displaying records
    public Boolean hasPrevious
    {
        get
        {
            return con.getHasPrevious();
        }
        set;
    }


    //Page number of the current displaying records
    public Integer pageNumber
    {
        get
        {
            return con.getPageNumber();
        }
        set;
    }


    //Returns the previous page of records
    public void previous()
    {
        con.previous();
    }


    //Returns the next page of records
    public void next()
    {
        con.next();
    }
}


and the contact pagination looks like this




<apex:page controller="pagingControllerForUser">
    <apex:form >
        <apex:pageBlock >
            
            <apex:pageMessages id="pgm"/>
            
            <apex:pageBlockButtons >
                <apex:commandButton value="Search" action="{!Search}"/>
            </apex:pageBlockButtons>
            
            <apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="User Name"/>
                    <apex:inputText value="{!usr.Name}"/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>


        </apex:pageBlock>


        <apex:pageBlock rendered="{!IF(AllSearchUsers.size > 0 , true , false)}">


            <apex:outputPanel layout="block" styleClass="pSearchShowMore" id="otpNav2">
              Total Records Found: <apex:outputText rendered="{!IF(Con.resultSize==10000,true,false)}">10000 +</apex:outputText><apex:outputText rendered="{!IF(Con.resultSize < 10000,true,false)}">{!Con.resultSize}</apex:outputText>
                  <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>
                  <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>
                  <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!Con.HasPrevious}"/>
                  <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasPrevious)}">Previous Page</apex:outputPanel>         
                  &nbsp;({!IF(Con.PageNumber == 1,1,((Con.PageNumber -1) * Con.PageSize)+1)}-{!IF(Con.resultSize < Con.PageSize,Con.resultSize,Con.PageNumber * Con.pageSize)})&nbsp;
                  <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasNext)}">Next Page</apex:outputPanel>         
                  <apex:commandLink title="Next Page" value="Next Page" rendered="{!Con.HasNext}" action="{!Next}"/>&nbsp;
                  <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>
                  <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/>          
              </apex:outputPanel>
            
            <apex:pageBlockSection columns="1">
                <apex:pageBlockTable value="{!AllSearchUsers}" var="UR">
                    <apex:column headerValue="Name" value="{!UR.Name}"/>
                    <apex:column headerValue="Email" value="{!UR.Email}"/>
                    <apex:column headerValue="Phone" value="{!UR.Phone}"/>
                  
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            
            <apex:outputPanel layout="block" styleClass="pSearchShowMore" id="otpNav">
              Total Records Found: <apex:outputText rendered="{!IF(Con.resultSize==10000,true,false)}">10000 +</apex:outputText><apex:outputText rendered="{!IF(Con.resultSize < 10000,true,false)}">{!Con.resultSize}</apex:outputText>
                  <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>
                  <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>
                  <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!Con.HasPrevious}"/>
                  <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasPrevious)}">Previous Page</apex:outputPanel>         
                  &nbsp;({!IF(Con.PageNumber == 1,1,((Con.PageNumber -1) * Con.PageSize)+1)}-{!IF(Con.resultSize < Con.PageSize,Con.resultSize,Con.PageNumber * Con.pageSize)})&nbsp;
                  <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasNext)}">Next Page</apex:outputPanel>         
                  <apex:commandLink title="Next Page" value="Next Page" rendered="{!Con.HasNext}" action="{!Next}"/>&nbsp;
                  <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>
                  <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/>          
              </apex:outputPanel>


        </apex:pageBlock>


    </apex:form>
</apex:page>



Sunday, May 20, 2012

DataTableSort

DataTableSort
This is a common requirement for any salesforce developer sorting data table .It is good to practice by uploading script in static resource as a zip format and access using visualforce page as follows
Custom controller is always a best practice for a developer




public class DataTableExampleController {
  // ApexPages.StandardSetController must be instantiated
 
  // for standard list controllers
 
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [select name,phone,email,account.name,title from contact]));
            }
            return setCon;
        }
        set;
    }


    // Initialize setCon and return a list of records
 
    public List<Contact> getcontacts() {
         return (List<contact>) setCon.getRecords();
    }
}


and the Visualforce page as


<apex:page Controller="DataTableExampleController" docType="html-5.0">
    <head>
        <apex:includescript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"/>


        <style type="text/css" title="currentStyle">
                @import "{!URLFOR($Resource.DataTables, 'media/css/demo_page.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/css/demo_table.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/css/ColReorder.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/css/ColVis.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/css/TableTools.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/css/ColumnFilterWidgets.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/css/demo_table_jui.css')}";
                @import "{!URLFOR($Resource.DataTables, 'media/examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css')}";
        </style>


        <script src="{!URLFOR($Resource.DataTables, 'media/js/jquery.dataTables.min.js')}"></script>
        <script src="{!URLFOR($Resource.DataTables, 'media/js/jquery.dataTables.js')}"></script>
        <script src="{!URLFOR($Resource.DataTables, 'media/js/ColVis.js')}"></script>
        <script src="{!URLFOR($Resource.DataTables, 'media/js/ZeroClipboard.js')}"></script>
        <script src="{!URLFOR($Resource.DataTables, 'media/js/TableTools.js')}"></script>
        <script src="{!URLFOR($Resource.DataTables, 'media/js/ColumnFilterWidgets.js')}"></script>


        <script type="text/javascript" charset="UTF-8">


            $(document).ready( function () {
              var oTable = $('#contacttable').dataTable( {
                  "sDom": 'WRC<"clear">lftip',
                  "bJQueryUI": true,
                  "sPaginationType": "full_numbers",
                  "aoColumnDefs": [ { "bVisible": false, "aTargets": [ ] }],
                  "oColumnFilterWidgets": { "aiExclude": [ 0, 3, 4 ] }
             });
          });


        </script>


    </head>


    <body>


     
     


        <table cellpadding="10" cellspacing="0" border="5" class="display" id="contacttable" style="margin-top:25px;">


            <thead>
             <tr>
                 <th>Name</th>
                 <th>Account</th>
                 <th>Title</th>
                 <th>Phone</th>
                 <th>Email</th>
             </tr>
            </thead>


            <tfoot>
             <tr>
                 <th>Name</th>
                 <th>Account</th>
                 <th>Title</th>
                 <th>Phone</th>
                 <th>Email</th>
             </tr>
            </tfoot>


            <tbody>


                <apex:repeat value="{!Contacts}" var="c">
                    <tr>
                      <td>{!c.Name}</td>
                      <td>{!c.Account.Name}</td>
                      <td>{!c.Title}</td>
                      <td>{!c.Phone}</td>
                      <td>{!c.Email}</td>
                  </tr>
                 </apex:repeat>


            </tbody>


        </table>


    </body>


</apex:page>


Download Your Static Resource at
DataTables


Here is some screen shots



Saturday, May 19, 2012

Google Chrome USEFUL SALESFORCE EXTENSIONS

Google Chrome USEFUL SALESFORCE EXTENSIONS
Install on your Chrome ..Enjoy Awesome Salesforce Features


1.Force.com LOGINS 1.1.0
https://chrome.google.com/webstore/detail/ldjbglicecgnpkpdhpbogkednmmbebec#
2.Force.com Utility Belt
https://chrome.google.com/webstore/detail/bchgkjmjnmekbampjoenadmoekocpbhp
3.Salesforce Custom Object Admin Link 
http://userscripts.org/scripts/versions/100708
4.Salesforce Fields List Enhancements
http://userscripts.org/scripts/versions/100292
5.Salesforce User Menu Enhancement - Administrators 1.0
http://userscripts.org/scripts/show/100798
6.Salesforce User Menu Enhancement - Developer Version1.0
http://userscripts.org/scripts/show/127856
7.Salesforce.com Quick Login As
https://chrome.google.com/webstore/detail/dccccilgophpadpomgajjlkkioipoojh

Share Tasks Multiple Contacts,Cool Features in Summer'12

Share Tasks Multiple Contacts,Cool Features in Summer'12 


You can get More Info follow the link 
http://www.salesforce.com/customer-resources/releases/

This is my first blog


This is my first blog

This is my first blog.

You will read Salesforce Concepts(My Profession) and Articles About Telugu(My Mother Tongue).Especially MY Favorite Actors in reel life and Good Human being  in Real Life none other than  NTR & NBK.....