Showing posts with label Visualforce. Show all posts
Showing posts with label Visualforce. Show all posts

Wednesday, May 16, 2012

Dynamic Visualforce Components Explained


Some or the other time you might have faced a challenge of dynamically generating input fields. Most of the time we sticked to dynamic HTML and embed that in our VF page to fulfil our needs.

But now, Salesforce has introduced the new Dynamic visualforce components which means you no longer will be dependent on dynamic HTML for most of your needs.

Here is a sample which shows you how to generate a dynamic input form for Account object.

Page
<apex:page standardController="Account" extensions="DynamicInputForm">
<!-- Create section header dynamically -->
<apex:dynamicComponent componentValue="{!SH}"/>
<apex:form >
<!-- Create dynamic input form for account object -->
<apex:dynamicComponent componentValue="{!ActForm}"/>
</apex:form>
</apex:page>

Class
public with sharing class DynamicInputForm
{
    public DynamicInputForm(Apexpages.standardController ctlr)
    {
        //constructor code goes here
    }

  
    //Create a page block dynamically
    public Component.Apex.PageBlock getActForm()
    {
        Component.Apex.PageBlock pb = new Component.Apex.PageBlock();
      
        //creating an input field dynamically
        Component.Apex.InputField name = new Component.Apex.InputField();
        name.expressions.value = '{!Account.Name}';
        name.id = 'name';
        Component.Apex.OutputLabel label = new Component.Apex.OutputLabel();
        label.value = 'Name';
        label.for = 'name';
        //Use the above block to create other input fields
      
        Component.Apex.CommandButton save = new Component.Apex.CommandButton();
        save.value = 'Save';
        save.expressions.action = '{!Save}';


        pb.childComponents.add(label);
        pb.childComponents.add(name);
        pb.childComponents.add(save);
        return pb;
    }

  
    //create section header dynamically
    public Component.Apex.SectionHeader getSH()
    {
        Component.Apex.SectionHeader sh = new Component.Apex.SectionHeader();
        sh.title = 'Create Account';
        return sh;
    }
}
Updated Visualforce developer guide covers this topic.

Sunday, August 7, 2011

How Force.com is revitalizing Application Development?

The other day I caught up with an old friend. We spent about 5 years together, working on Microsoft technologies and developing a slew of applications. Invariably, the topic veered towards technology and application development. I asked him what he was up to, and discovered that he was part of a team working on an application for a large enterprise. Some of the features read like this...

(No "ideas" were shared, these are pretty common features of all apps!)

--- Data model that supports related records
--- Large scale Business validations on forms
--- A Facebook clone for the social connect
--- Approval mechanisms, Notifications, Security, etc.

He was going on and on, so I stopped him to ask what his role in the entire exercise was and how they were planning for future versions. I learnt that he was a Lead Developer for one of the modules at one of the locations. Incidentally, the project was being worked on from four different geographies each of them sharing a significant Development piece. They were yet to come up with the first version and the project has been running for 15 months. As for the cost, your guess is better than his!

I said wow! This sounded familiar, but hang on, what are we building here? An aircraft carrier?

My heart goes out to the CIO and the end users of the application. By the time they get to realize any value out of the applications, their priorities in life would have changed. And it must have been one hell of a CFO to have approved the budget in the middle of uncertain and trying times.

OK, let's get pragmatic to understand the reason for my frustration.
(Disclaimer: I've been a fan of the Force.com platform since it's inception, and have partnered in building a Company around it, but that's after working on Microsoft technologies for many years before that, and I am still a keen follower)

Traditional Application Development follows an approach similar to this:
Code, Test, Assemble, Bundle, Deploy, Resolve, Release, Fix
This is characteristic of any technology that forces Developers to interact with libraries and have them worry about making the code work after writing it. But, as Application Development evolved in general and the way Force.com has adapted in particular, this approach has become redundant. And, here's why.

We hear it all the time - Application Developers must focus on Innovation. But, Force.com is the front runner,  if not the only technology that lets Application Developers do that. Everything else is what's called as plumbing code. So, when you do any of the following (and more), you are essentially plumbing your code.

--- Write code (or use Design mode in IDEs) for Data validations, and even common Business validations
--- Importing libraries and fretting over getting all the files in one folder to ward of the "Assembly not found" error
--- Use multiple frameworks to imitate a 3-tier architecture, making your code bulky
--- Write classes for Notifications, Messaging, Role hierarchy, etc.
--- Move from one Remote m/c to another to deploy your code before seeing your page go bust with an Invalid reference error

Sample this - how can you expect your Developer to be innovative if he is plumbing for 75% of his time?
This is exactly where Force.com wins - with Visualforce, Apex and the Force.com platform, it helps Application Developers ideate. They get a Zen like feeling. It's the holy grail of Application Development platforms.

How does Force.com achieve this? I'll cover that in detail over the next few posts, but for starters, the crux lies in how the platform provides for a combination of common feature sets bundled with an exciting user experience, and how Developers are able to leverage a Business data model with easy to build validations and formulae through clicks. As a Developer, that's making it available on a platter for me! My interest to ideate is enhanced when I look at what I already have on Force.com. There can't be a better motivation to build great apps.

I can't but mention about the social connection, and how Business and Enterprise apps have the social toolbox ready to go on Chatter.

It is not all about the plumbing though, its how you have a wonderful user experience that makes it graceful that adds all the value. There are umpteen stories of how CEOs have built up the entire environment on Force.com leaving only the code for the Developers, which is essentially about 20-25% of the entire effort.

The technology industry has been known to fade out geographical barriers, but are the IT behemoths doing it in the most efficient way for their Clients? No. 3-year, 5-year budget cycles spread over millions of dollars cannot be a sustainable approach for a technological implementation. Bordering uncertain times, CIOs must demand the best approach, the best technology and the best ROI and must leave behind the baggage of legacy brands.
In the next post, I'll write about how Force.com dilutes geographical barriers in the best possible way, thereby letting in more of the innovation in to your apps.








Thursday, December 2, 2010

Update Namespace Prefix in Your Apex Code

As a developer, it is sometimes very tedious when we have to make all of our code as a Managed Package. Have to go to each custom field/Object in the code and change it manually with the Namespace Prefix.

I have developed a tool which takes input as your Class/VF Page/Trigger etc.. for that matter any of the file type mxml, aspx, php etc... and gives the updated output like in the screen shots below.




 'Hope this helps

You can use the tool from here.

Thanks,
Srinivas.

Wednesday, May 5, 2010

Visualforce Email Template with Attachment

Visualforce Email Templates with Component as Attachment

Now Email templates can be created through a visualforce. That is you can send emails to people with salesforce features.

I will explain a Visualforce email template basic/as well as with component as attachement here.

<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="opportunity report for Account : {!relatedTo.name}">
<messaging:htmlEmailBody >
<html>
<body>
<table >
    <tr>
        <th> Name </th>
        <th> CloseDate </th>
        <th> Stage Name </th>
    </tr>
    <apex:repeat var="o" value="{!relatedTo.Opportunities}">
        <tr>
           <td>{!o.Name}</td>
           <td>{!o.CloseDate}</td>
           <td>{!o.StageName}</td>
        </tr>
    </apex:repeat>    
</table>
   
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
The above Visualforce Template sends out all the opportunities that are related to the Contact's Account.

The one more powerful usage of Visualforce Email Template is We can introduce Custom Components in the body.

I would like to attach a PDF document which shows the number of Opporutnities for that account grouping by their close date. This I can do in a component and include that component inside my email template like this after htmlEmailBody tag.
<messaging:attachment renderAs="PDF">
    <c:opportunityGrouping accountId="{!relatedTo.Id}"/>
</messaging:attachment>
component:
<apex:component controller="opportunityGroupingController" access="global">
    <apex:attribute name="accountId" assignTo="{!accId}" type="String" description="Id of the account"/>
    <table >
            <tr>
                <th> Total </th>
                <th> CloseDate </th>
            </tr>
        <apex:repeat var="opp" value="{!GroupedOpportunites}">
            <tr>
                <td>{!opp.Total}</td>
                <td>{!opp.CloseDate}</td>
            </tr>
        </apex:repeat>    
    </table>
</apex:component>
opportunityGroupingController Class:
public class opportunityGroupingController 
{
    public String accId
    {   get;set;    }
   
    public list<AggregateResult> lstAR = new list<AggregateResult>();
   
    public list<subClass> lstSC = new list<subClass>(); 

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

        public date closeDate
        {   get;set;    }
       
        public subClass(AggregateResult ar)
        {
            Total = (Integer)ar.get('Total');
            closeDate = (date)ar.get('CloseDate');              
        }
    }

    public list<subClass> getGroupedOpportunites()
    {  
        lstAR = [select count(Id) Total, CloseDate from Opportunity where AccountId =:accId Group By CloseDate];
        for(Integer i = 0; i < lstAR.size(); i++)
        {
            subClass objSubClass = new subClass(lstAR[i]);
            lstSC.add(objSubClass);
        }
        return lstSC;  
    }
}

Hope this is useful.

Thanks
Srinivas
Technology Evangelist
Trekbin Technologies

Thursday, April 29, 2010

Visualforce File Upload - for Any SObject


How to Upload Attachment to any SObject using Visualforce

This article explains how you can upload file attachments to any SOobject using Visualforce.


Page:



<apex:page standardController="YourSObjectName" extensions="VFFileUpload">
  <apex:form>
      <apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
       </apex:pageBlock>
  </apex:form>
</apex:page>

Class:



public class VFFileUpload
{
    public Id recId
    {    get;set;    }
    
    public VFFileUpload(ApexPages.StandardController ctlr)
    {
       recId = ctlr.getRecord().Id;     
    }
    
    public string fileName 
    {    get;set;    }
    
    public Blob fileBody 
    {    get;set;    }
  
    public PageReference UploadFile()
    {
        PageReference pr;
        if(fileBody != null && fileName != null)
        {
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
           pr = new PageReference('/' + myAttachment.Id);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }    
}


You can use the above code for any object whether it is standard or custom. Happy coding!

Thanks,
Srinivas,
Technology Evangelist,
Trekbin Technologies,
www.trekbin.com

Friday, April 23, 2010

Call External Web Service from Salesforce Apex

Call External Web Service from Salesforce Apex

Some times, you may need to call an extenal web service which might have written on a serverside language like .net, php or java.
Once you made your web service on the serverside or you can use a third party web service api.

I will explain you this using Authorize.net payment gateway.
There are several types of payment criterias available for Authorize.net. For an example I will go with CIM (Customer Information Manager)
You will find all the details in Authoirze.net developer documentation.

To do payments on authorize using CIM we need to create customer profile first.

Here is the apex code that calls an external web service.

//Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the call will fail. The platform, by default, prevents calls to unauthorized network addresses.
//You can do this like this: got Setup->Administration setup->Security controls->Remote site settings->New and add your endpoint URL there.
//In our case the ende point is https://api.authorize.net/soap/v1/Service.asmx.

Public class callExternalWS
{
    public void invokeExternalWs()
    {
        HttpRequest req = new HttpRequest();
        //Set HTTPRequest Method
        req.setMethod('POST');
        req.setEndpoint('https://api.authorize.net/soap/v1/Service.asmx');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'text/xml; charset=utf-8');
        req.setHeader('SOAPAction', 'https://api.authorize.net/soap/v1/CreateCustomerProfile');//
        string b =   '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
                      '<soap:Body><CreateCustomerProfile xmlns="https://api.authorize.net/soap/v1/">'+
                      '<merchantAuthentication><name>Merchant name here</name>'+
                      '<transactionKey>Transaction Key here</transactionKey></merchantAuthentication>'+
'<profile><description>description</description>'+
                      '<email>sforce2009@gmail.com</email>'+
                      '<paymentProfiles>'+
                      '<CustomerPaymentProfileType><customerType>individual</customerType>'+
'<payment><creditCard><cardNumber>6011000000000012</cardNumber>'+
                      '<expirationDate>2009-12</expirationDate></creditCard>'+
                      '</payment></CustomerPaymentProfileType></paymentProfiles></profile>'+
                      '</CreateCustomerProfile></soap:Body></soap:Envelope>';
        req.setBody(b);
        Http http = new Http();
        try {
          //Execute web service call here       
          HTTPResponse res = http.send(req);   
          //Helpful debug messages
          System.debug(res.toString());
          System.debug('STATUS:'+res.getStatus());
          System.debug('STATUS_CODE:'+res.getStatusCode());
        //YOU CAN ALWAYS PARSE THE RESPONSE XML USING XmlStreamReader  CLASS
       } catch(System.CalloutException e) {
            //Exception handling goes here....
     }       
}
}

Hope this is useful

Wednesday, April 14, 2010

Set Id for Apex insert Tag

How to set Id parameter for Apex insert Tag


I came to an interesting question on community. the above. you might want to check (reply from sforce2009, its me :) ).


Thanks,
Srinivas

Friday, April 2, 2010

Visualforce

Visualforce is a powerful tool for designing your forms with similar look and feel of Salesforce default layouts. Let’s say you want to build a search page for Account Object. That is you wish to list all the existing accounts in a list and search functionality by using which you want to view the filtered accounts.
To do the same functionality before Visualforce era, it was very cumbersome and demand more knowledge on javascript (which may not be reliable on all browsers). Visual force is the markup language introduced by Salesforce, It provides a similar look and feel of a Salesforce standard object by just introducing some tags whose namespace is prefixed by apex.
We can use the standard object properties and styles by just setting the attribute StandardController to the desired object like below
<apex:page standardController=”Account”></apex:page>

An example which uses Account as StandardController and renders Account style is below.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Edit Account for{!$User.FirstName}">
<apex:pageBlockSection>
<apex:inputField value="{!account.name}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

The above code inherits a pageblock which is similar to Account standard layout page section with the Name field editable. If you observe the Pageblock’s title, we can still use the Formula Merge Fields just like in S-Controls.
In my next Article on Visualforce, I will be posting the code for the functionality described at top (Search functionality on Account listing). This will involve more abilities of Visualforce.