Wednesday, December 30, 2009

Override URL and Button through Apex And Visual Force

Hi Welcome back...
I have been soo busy but promise to put up some new and neat things in 2010.
So lets start:
As you may know S-Controls are going away in the year 2010. It was very simple to override an URL and button using S-Controls.
But I have figured out a neat and simple way to do it using Apex and VisualForce.

Scenario:
Override the New Button for Opportunity, from contact and pre-populating the field in the URL pushing it forward to Opportunity ContactName field.

Beginner's Steps:
  1. Get the field ID of the contact Lookup Field in Opportunity. Click on: Setup==>Customize==>Opportunities==>Fields.
  2. Look for the lookup Relationship field to Contact (basically in the


    Opportunity Custom Fields & Relationships Lookup for DataType which would state Lookup(Contact)).




  3. Click on it and get the ID from the URL. It would be something like this:https://tapp0.salesforce.com/00N70000002RFSE The last part of the URL is the salesforce ID that is needed for the Controller and URL we need.
  4. Also we need to know the prefixes for the New Opportunity URL and existing Contact URL. By default the New Opportunity will start with /006/e? and the existing or new Contact will start with /003/e?.
  5. Now we shall place all of this in the controller.
  6. Then the page in which we will call the controller
  7. Override the New Button in the Opportunity Button and Links section.
Lets Start with the Apex Controller:

// The Name of the class
public class OverrideOppButton{

// Create a variable to get the Contact and set the variable
Contact c {get; set;}

//Use a boolean to determine if there are contact records available and set it to false initially
boolean gotcontactrecords = false;

//Open up the constructor to get the contact records from the current URL
public OverrideOppButton(ApexPages.StandardController stdController){

// Create a variable to return the current Contact URL;
string ret;
ret = ApexPages.currentPage().getParameters().get('RetURL');
//This will pick up the URL on the current contact record
//For example: https://tapp0.salesforce.com/003T000000MFRcS
//We need to separate the 003 which is the contact record and the T000000MFRcS which is the ID of //the contact record

ret = ret.substring(1,ret.length());

if(ret.startswith('003')) {
//if the substring of the URL starts with '003' which it does '003T000000MFRcS'
//Then query the database for that record from the contact

    c = [Select name, lastname, firstname, id from Contact where id =: ret];

//if they are records then set the gotcontactrecords to true
    gotcontactrecords = true;
 }
} // end constructor


/*
Here we start the PageReference Class which will tell the URL of what to
place into it
*/
public PageReference init(){

/*
We need to specify where the URL will redirect after the New
Button is clicked
*/

//Define the variable first
string redirectURL = '';
/*
Place in if then logic if there is a contact record then place in the url parameters and
redirect the user to the new Opportunity Page
if not then redirect them to a new Opportunity Page
with no parameter in the URL
*/
if (gotcontactrecords ) {
    redirectURL = '/006/e?CF003T000000MFRcS =
     ' + EncodingUtil.urlEncode(c.name, 'UTF-8') + '
    &CF003T000000MFRcS_lkid=' + c.id + '
    &nooverride=1';
}
/*
Explanation of the RedirectURL:
/006/ <== Creating New Opportunity Record
e?      <== What parameters need to be inputed.
CFT000000MFRcS <== 'CF' is the custom field which is the lookup Contact field in
                                               the Opportunity Object. field id is T000000MFRcS.
EncodingUtil.urlEncode(c.name, 'UTF-8')<== Takes in symbols associated with the name
                                                                             For example: Haaris & Benny
nooverride=1 <== Need when one overrides the new button.
*/
else {
    redirectURL = '/006/e?nooverride=1';
}

/*
Set the Page Reference of what URL will it take if it passes the criteria mentioned above
*/
PageReference createnewOpp = new PageReference(redirectURL);
return createnewOpp;
}

} //end class
*************************************************************************
Create the VisualForce Page:
This page is very simple.
  • Give the page a new which will be used when you override the New Button on the Opportunity
  • Place the initiative in the first tag of Visual Force
  • standardController = "Opportunity" which takes the Look & feel of the Opportunity Page
  • extensions = "OverrideOppButton" which places in the class/controller we just created.
  • action = "{!init}" which calls the PageReference and tells what the URL should be for the user.

apex:page standardController="Opportunity" extensions="OverrideOppButton" action="{!init}"
Do not forget the "<" and "/>" in this statement and your closing apex:page tag

*************************************************************************
Now go to Setup==> Customize ==> Opportunities ==> Button and Links
Click on Override next to the New Button
Click on the radio button which states Visualforce Page for Content Type selection
Drop down the Content Name and you should see the name of your Visualforce Page
which you just created.

That is it, your done.
Please leave your comments below.
Thanks



Friday, March 20, 2009

Embed VisualForce Page on Home Page

Scenario:
Create a Google Graph via VF and then embed it to the
Home Page. So when an user logs in they see the graph of there sales information Year over year.

Task at hand:
For this blog, I will walk through the steps of placing in any
component onto the Home Page.

Lets Get Started:
Go to Setup | Customize | Home | Home Page Components


Click New
Choose HTML Area and
Input the Name for your component.
Click Next

Here Choose either Wide (right) Column or Narrow (Left) Column.
Wide means some where on the Home page in the middle.

Narrow means somewhere on the Menu Column on the
Left where the search bar is.
Select show HTML on the right upper hand side and place in the following:
<iframe
src="/apex/yourpagename?core.apexpages.devmode.url=1"
width="100%" frameborder="0" height="100">
</iframe>

Then Click save.

Now go into Setup | Customize | Home |
Home Page Layouts |
Click Edit next to
the Layout you would like to conifgure
Select the component from there
Click Next and order it where you want it to show.
Click Save.
Now go to your Home Page and it should be there.
As you can see I have a Graph and Summary Side Bar as well.
Both are VisualForce Pages.

I hope this helped...

Great Materials:
Thanks
Check out my Other Salesforce.com Blogs
Salesforce Made Easy

Salesforce Data Migration Made Easy
eTechCareers.com Coming Soon
    
    

    How to add and delete row in a datatable through visualforce

    Scenario:
    Through a VisualForce custom Page the user must have the
    ability to add and delete row.

    BrainStorming:
    For each record display the record should have a link for deletion.
    So that it will delete that row only.

    For all the records, it will have a button call Add to add an
    additional line to the records.

    Tools needed:
    1. An Force.com Account, if you do not have one
    2. get a free developer account Here
    3. Apex Controller
    4. VisualForce Page
    Lets Get Started:
    1. Create your Apex Controller.
    This will have the PageRefernce to:
    • Add()
    • Delete()
    • Save()
    2. Create your Visual Force Page.

    First thing:
    I will create a simple Apex Controller.
    Go to Setup | Develop | Apex Classes
    Click New

    The Apex Class I created is off the Account Object and
    Case Object.

    It will show, all the Cases for the Account
    associated with it.

    Here the User can Add or Delete the case
    one by one or even close it.

    Below if the code for it:
    /*Start off by placing a name for the controller,
    When I build a controller I always place
    controller at the end of the name*/
    public class AccountsController {
    
    /* I set the Account and Case Objects
    here for use through out the code*/
    public Account acct { get; private set;}
    public Case[] caseItems { get; private set; }
    private ApexPages.StandardController controller;
    
    // constructor, loads the Account and
    // any cases associated with it
    
    void caseItems(id id) {
    acct = [SELECT Id, Name, Type, AccountNumber, Site,
          (SELECT Id, CaseNumber, Status, Reason,Origin,
          Subject FROM Cases) FROM Account
          where id = :id limit 1];
    //Hook caseItems to the query above
     caseItems = acct.Cases;
    }
    
    //Define the id
    id accountid;
    
    /* A List Method to delete the Cases assigned*/
    public list todelete = new list();
    
    public AccountsController (ApexPages.StandardController c)
    {
    /* this will kickoff you main page */
    controller = c;
    /* to get this current Account Id*/
    accountid = c.getRecord().id;
    /*kick off the init() function*/
    init();
    }
    public AccountsController () {
    accountid =
    ApexPages.CurrentPage().getParameters().get('id');
    
    init();
    
    }
    
    void init() {
    /* load up Cases
    basically we defined caseitems up on top, so
    when the page loads then caseItems(accountId)
    will go through the query and list out the
    Items assoicated with it */
    caseItems(accountid);  
    }
    
    public PageReference save() {
    try {
    upsert caseItems;
    if ( todelete.size() > 0 ) {           
    delete todelete;   
    }
    caseItems(acct.id);
    }
    catch ( DmlException exc) {
          ApexPages.addMessages(exc);
          return null;
    }
    return null;
    }
    
    
    /* your Delete functionality*/
    public PageReference del() {
    
    string delnumber =
    ApexPages.CurrentPage().getParameters().get('delnumber');
    
    system.assert( delnumber != null );
    integer gone = -1;
    integer i = 0;
      
    for ( i=0; i< casenumber ="="" gone =" i;">= 0) {
    todelete.add(caseItems.remove(gone) );
    }
    return null;
    }
    public PageReference add() {
    // insert a new line, after user clicks Add
    Case cs =  new Case(
    AccountId = acct.id,
    Subject = 'hello', Status = 'Low',
    Reason = 'Other',Origin='Low'
    );
    caseItems.add ( cs );
    return null;
     }
    }
    
    Second, Now for the Visual Force Page:
    Setup | Develop | Pages
    Click New
    Name it editCases
    Paste this in:
    
    <apex:page standardController="Account"
    extensions="AccountsController"
    sidebar="false" tabStyle="Account" >
    
    <style>
    .dataCell input {
    width:100px;
    }
    </style>
    
    <apex:form >
    
    <apex:actionFunction status="outStatus"
    name="yacks" rerender="table" />
    
    <apex:pageBlock title="Edit Cases"
    mode="edit" id="table">
    
    <apex:pageBlockButtons >
    
    
    
    <apex:commandButton action="{!save}"
    value=" Save " />
    <apex:commandButton action="{!add}" value="Add" rerender="table" /> </apex:pageBlockButtons> <apex:pageMessages /> <apex:pageBlockSection title="Account Name : {!Account.name} " columns="1"> <apex:pageBlockTable value="{!caseItems}" var="item" > <apex:column headerValue="Action"> <apex:commandLink value="Del" action="{!del}" rerender="table" > <apex:param name="delname" value="{!item.CaseNumber}" /> </apex:commandLink> </apex:column> <apex:column headerValue="Case Number"> <a href="/{!item.CaseNumber}"> {!item.CaseNumber}</a> <apex:outputPanel rendered="{!isnull(item.CaseNumber)}" > <apex:inputField required="true" value="{!item.CaseNumber}" onchange="yacks();" /> </apex:outputPanel> </apex:column> <apex:column headerValue="Subject"> <apex:inputField required="true" value="{!item.Subject}" onchange="yacks();"/> </apex:column> <apex:column headerValue="Reason" > <apex:inputField required="true" value="{!item.Reason}" onchange="yacks();" /> </apex:column> <apex:column headerValue="Origin" > <apex:inputField value="{!item.Origin}" onchange="yacks();"/> </apex:column> </apex:pageBlockTable> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> Some Definitions for the Apex Controller and VF Page: 1. Public Reference whtever() : These are used for action methods for the controller. Like Save, Add, Reset, Delete,Cancel 2. return Method : This contains the value from either a query or action. Within the save(), I return null; at the end to stay on that same page. If I wanted to redirect back to the account page I would return functionredirect(); And functionredirect() would be a custom function to go back to the account page. 3. <apex:pageBlockButtons > : Creates a button, that have the same style as regular Salesforce.com buttons. The Attributes for the pageBlockButtons Tag are: Note** This came from the VisualForce Online Guide. Great Materials for VisualForce Tutorials:
    Thanks
    Check out my Other Salesforce.com Blogs
    Salesforce Made Easy

    Salesforce Data Migration Made Easy
    eTechCareers.com Coming Soon

      Wednesday, March 18, 2009

      Blend a table within the environment using VisualForce

      Scenario:
      Within a PDF create a table that would blend into the environment off the data QuoteLineItem. The borders and colors should be the same style as the Quote Tab.

      What is needed for this assignment:
      1. Developer Account if you do not already have one.
      2. Apex Controller write a simple one that gets all account or just one account.
      3. Login into your org, go to Setup | Develop | Pages
      4. Click New, Enter in Label and Name. Note** the Name column may not have a space in between and will not prefill after the label column. You will get an error such as:

      Error: The page name can only contain alphanumeric characters, must begin with a letter,
      and must be unique.


      Understand Tags and Build out:

      TabStyle

      Using this tag will get you the colors of the Quote Tab. Plus it
      will open up the VisualForce Page in the Quote Tab.
      Now if the tabstyle was set to Account then it will inherit the
      colors and open up under the Account tab.

      Facts about TabStyle:
      1. "the tabStyle attribute of an tag allows you to mimic
      the look and feel of the associated Salesforce page"..
      From Force.com Online tutorial guide

      2. The tabstyle is always equal to the object API Name.

      3. It is a String within the <apex:page> tag.


      We will add to the first tag, the tabstyle reference.

      Within the <apex:Page> tag place in tabStyle="ObjectName"

      **Note: Object Name can be a Standard Object or a Custom Object
      Make sure if a Custom Object to use the API Object Name
      "XXXX__c".

      <apex:page tabStyle="SFDC_520_Quote__c">
      and click save.
      To view this page go to the URL and at the of the last
      slash after your
      instance URL. type in /apex/tabtest




      RenderAs="PDF"
      Since the Scenario asked for PDF Page. Then within the
      <apex:Page tag place in renderAs="PDF"

      This would convert the page as a PDF.
      So tag should look like so:

      <apex:page tabStyle="
      SFDC_520_Quote__c" renderAs="PDF">

      Remeber to always close your Tags
      So to close the <apex:page> tag, at the end of the code place in
      </apex:page>

      PageBlock and PageBlockSection
      These two tags go hand in hand. The main tag(PageBlock)
      is the one that encompasses many tags within it. The
      PageBlock tag gives it that border with the same color
      as your tabstyle. Now PageBlockSection gives it the
      header shaded in the same color as the style.

      So lets do it:
      the second line should read as follows:

      Use pageBlock Tag Line #2
      <apex:pageblock></apex:pageblock>

      This will get you the upper border, right side border
      and bottom border.

      As you can see the green borders
      are created from the pageblock tag.
      Now to add the PageBlockSection. This would give as our
      Header or Title.Underneath the pageBlock line and within
      the closing pageblock tag place in the following:

      <
      apex:pageBlockSection title="Congrats">

      </apex:pageblockSection>
      See Below:

      As you can see the header now in green.

      Your code should look like this now:

      <apex:page tabStyle="SFDC_520_Quote__c">

      <apex:pageBlock>
      <apex:pageBlockSection title="Congrats Header"
      collapsible="false" columns="1">


      </apex:pageBlockSection>

      </apex:pageBlock>

      </apex:page>

      Notice:
      ***collapsible within the tag is used to open or close the
      header information below it. I set it to false because
      I would like the user to see the information at all
      times and never have to hide it.


      Create The Table:

      We will utilize pageblockTable ... This blends into
      the environment.
      Let me post the code up and then explain the tags:

      <apex:page
      tabStyle="SFDC_520_Quote__c">

      <apex:pageBlock>

      <apex:pageBlockSection
      title="Congrats Header"
      collapsible="false"
      columns="1">

      <apex:pageBlockTable
      value="{!SFDC_520_Quote__c.quote_lines__r}"
      var="item" border="1"
      cellspacing="0"
      cellpadding="0">

      <apex:column headerValue="Item #">
      {!item.name}
      </apex:column>

      <apex:column headerValue="SKU">
      {!item.Product2__r.ProductCode}
      </apex:column>

      <apex:column headerValue="Description">
      {!item.Product2__r.Name}
      </apex:column>

      <apex:column headerValue="Qty">
      <apex:outputField value="{!item.Qty_Ordered__c}"/>
      </apex:column>

      </apex:pageBlockTable>

      </apex:pageBlockSection>

      </apex:pageBlock>


      </apex:page>
      Alright, now for an explanation:

      • We using the child object QuoteLineItems related to Quotes.

      • Utilizing the child object for information on line items.

      • We set the variable to be item.

      • We gave the table a border = 1, higher you go the
        thicker the border.

      • We now need an Apex Controller to place in the items we need.
      Good Reference Materials:



      Monday, March 2, 2009

      Google Graphs using VisualForce...

      Hi:
      Welcome back,
      Scenario:
      • Had to created a real time graph(TimeLine) on salesforce.com, year over year to show sales data for the account.
      • Place this on the Account page layout when viewing the record.
      • Had to use Google graph.
      Not so easy, but with my help and visual aid I'll walk you through it step by step.

      What you will need:
      • As always developer force.com edition
      • data in the account record
      • sales data table
      • internet :)
      So Stay tuned...
      Thanks
      Check out my Other Salesforce.com Blogs
      Salesforce Made Easy

      Salesforce Data Migration Made Easy
      eTechCareers.com Coming Soon

      Wednesday, February 25, 2009

      Insufficient Privileges??? Users can not see VisualForce Page??

      Hi.. Welcome back:
      I ran into a scenario where there was a VisualForce page created with a controller and added onto the Page Layout.
      Now I as an admin I can view the VF page on the page layout I placed in on...
      But when I logged into as an User I could not view the page...
      The Answer to this
      page level security access on their profile to this VFpage

      To accomplish this do the following:
      1. Go to the Setup | Develop | Pages

      You will see The Following:

      Notice you have a Link that states Security... Click on it.. It will take you to the Page Level Security Page.

      Select the Profile from the Left side and click the Add button and click save.
      Now you have given Page Level Security to The Profile Added.
      ***Note: This gives the Access to this VF Page only, each VF Page is independent.. So if you like to give access to more VF Pages then you must repeat the steps for that Page.. ***
      Hope this helps
      Thanks
      Check out my Other Salesforce.com Blogs
      Salesforce Made Easy

      Salesforce Data Migration Made Easy
      eTechCareers.com Coming Soon

      Tuesday, February 24, 2009

      How do I add VF Page to Account Page Layout??

      Hi:
      Welcome back...
      Let say you created a Visual Force Page and Apex Controller... Now you want to add the VF page to the Page Layout on for example Account. So when an user goes into an Account; he/she will see the Visual Force Page created.
      But, there is no option there on the account Page Layout to add VF pages...
      Now what?
      Well very easy, The solution is:
      VF pages will show up in the Page Layout editor if there is at least one VF Page using the standard controller for Account (in your scenario).
      The VF page you want to add to the Account page layout must use the Account standard controller.
      For example in your Visual Force Page First line should have the standard Controller connected to the object:


      Make sure you create the apex method in your Apex class....
      Thanks
      Check out my Other Salesforce.com Blogs
      Salesforce Made Easy

      Salesforce Data Migration Made Easy
      eTechCareers.com Coming Soon