Ads

Showing posts with label Apex. Show all posts
Showing posts with label Apex. Show all posts

Tuesday 17 September 2013

Using static resource Dynamically in Salesforce?

Let’s suppose we have an archive in static resource with name “Contact” and you want to use this static resource on a page that displays Contact Photos dynamically. Assumption is that the images are stored with same name as product codes.
Code:

//Declare an apex variable which gets the Contact code from an apex property
<apex:variable var="contact_photo" value="{!contactPhoto}.jpg"/>
<img src="{!URLFOR($Resource.Products,contact_photo)}')" alt="" />

Email Services in Salesforce?

Email services are automated processes that use the Apex classes to process the contents, headers, and attachments of inbound email.
For example, you can create an email service that automatically creates contact records based on contact information in messages. Each email service has one or more email service addresses that can receive messages for processing.
To use the email services, click Your Name ➤ Setup ➤ Develop ➤ Email Services.
Given below email service class inserts Contact which is declare in setting of Email Services.

Class for Email Services:
global class ProcessJobApplicantEmail implements Messaging.InboundEmailHandler {

  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

    Contact contact = new Contact();
    contact.FirstName = email.fromname.substring(0,email.fromname.indexOf(' '));
    contact.LastName = email.fromname.substring(email.fromname.indexOf(' '));
    contact.Email = envelope.fromAddress;
    insert contact;

    System.debug('====> Created contact '+contact.Id);

    if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = contact.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
      }
    }
     return result;
  }
}

Test Class for Email Service:
@isTest
private class EmailTest{
static testMethod void testMe() {

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

  // setup the data for the email
  email.subject = 'Test Job Applicant';
  email.fromname = 'FirstName1 LastName1';
  env.fromAddress = 'raees.sabir@accenture.com';

  // add an attachment
  Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
  attachment.body = blob.valueOf('my attachment text');
  attachment.fileName = 'textfile.txt';
  attachment.mimeTypeSubType = 'text/plain';

  email.binaryAttachments =
    new Messaging.inboundEmail.BinaryAttachment[] { attachment };

  // call the email service class and test it with the data in the testMethod
  ProcessJobApplicantEmail emailProcess = new ProcessJobApplicantEmail();
  emailProcess.handleInboundEmail(email, env);

  // query for the contact the email service created
  Contact contact = [select id, firstName, lastName, email from contact
    where firstName = 'FirstName1' and lastName = 'LastName1'];

  System.assertEquals(contact.firstName,'FirstName1');
  System.assertEquals(contact.lastName,'LastName1');
  System.assertEquals(contact.email,'raees.sabir@accenture.com');

  // find the attachment
  Attachment a = [select name from attachment where parentId = :contact.id];

  System.assertEquals(a.name,'textfile.txt');
 }
}

How to use apex variable for total records in Visualforce?

Scenario:

 I came across a issue where visualforce does not allow one to Count or Sum records in a page.
One solution would be to add more code to the controller to do a count of the records. Which is ok.
A simple solution is to use the apex variable function in Visualforce.

Solution:
Lets do it off Contacts
In your Apex Controller : Create a SOQL query as is:
public class countcontroller{
            public List<Contact> queryResult {get;private set;}
            public String qryString {get;set;}
            public PageReference query(){
            qryString =  'SELECT Name, Email, Phone from Contact';
            queryResult = Database.query(qryString);
             return null;
       }
}

Pretty Simple and Straight Forward.
Now for the VF Page and Magic:
You will see I use the apex variable function to do a couple of things:

create a variable run the query inside that variable counting all the records by 1 within a repeat tag calling the variable with the total Kind of like a for Loop but in Visualforce instead of controller.

<apex:page standardcontroller="Contact" extensions="countcontroller">
<table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr height="5">
    <td width="35%" class="outsideround_head" align="right">
        Total Contacts Returned:&nbsp;
    </td>
    <td width="8%" class="outside_round_head_value">
        <apex:variable var="call" value="{!0}" />
        <apex:repeat var="countitall" value="{!queryResult}" >
        <apex:variable var="call" value="{!call+1}"/>
        </apex:repeat>
        <apex:outputText value="{!call}"/>
    </td>
</tr>
</table>
</apex:page>

GROUP BY - Count Method in Apex Controller?

Scenario:

We Need to do Total of Opportunities  Based on Stages. 

Thought Process:
What are the columns involved? Answer: StageName and Count or Total
What methods will we utilize to achieve these results? Answer: Group By SOQL Statement with Count.
What UI to built this neat logic? Answer: Apex Controller and VisualForce Page
Need to achieve this type of reporting for the user:


Solution:
Use Eclipse IDE or SOQL Explorer to create your SOQL Statement.
SELECT StageName, Count(Name) ce FROM Opportunity GROUP BY StageName
Second create  Apex Controller name what you like I named it TTL_Lesson, with your logic
public class TTL_Lesson{
public class OppStageHolder {
    public String OPP {get; set;}
    public Integer TTL_Opp {get; set;}
public OppStageHolder (){}
}
//Results will be placed within this List
public List queryResults{ get; set; }

//Your Page
public PageReference TTL() {

AggregateResult[] groupedResults = [SELECT StageName,
     Count(Name) ce FROM Opportunity
     GROUP BY StageName];
System.Debug('zzavg ' + groupedResults.size());
//Define your List
queryResults = new List();

for (AggregateResult ard : groupedResults)  {  
    OppStageHolder myObject = new OppStageHolder();  
    myObject.OPP = String.valueOf(ard.get('StageName'));  
    myObject.TTL_Opp = (Integer) ard.get('ce');      
    queryResults.add(myObject);  
}
return Page.TTL;
}

}

Now create your VF Page to call this and display it whenever the user clicks on this page:

<apex:page controller="TTL_Lesson" action="{!TTL}" showHeader="false" sidebar="false">
    <apex:dataTable value="{!queryResults}" var="a" id="theTable" border="2" cellpadding="1" cellspacing="1" bgcolor="#A9D0F5" >
                <apex:column >
                        <apex:facet name="header">Stage</apex:facet>
                        <apex:outputText value="{!a.OPP}"/>
                </apex:column>              
                <apex:column >
                        <apex:facet name="header">&nbsp;&nbsp;&nbsp;Count</apex:facet>
                        <apex:outputText value="{!a.TTL_Opp}"/>
                </apex:column>
    </apex:dataTable>
</apex:page>

Thursday 22 August 2013

How to undelete records in Salesforce?

Salesforce keep record you delete to Recycle Bin for 15 days with maximum record of 25 times the Megabytes (MBs) in your storage. For example, if your organization has 1 GB of storage then your limit is 25 times 1000 MB or 25,000 records. If your organization reaches its Recycle Bin limit, Salesforce automatically removes the oldest records if they have been in the Recycle Bin for at least two hours.

You can manually undelete records by click Recycle Bin icon in bottom left menu. Undelete account will include contact, case, opportunity tagged to that Account. But, if you have many records or you have specific record Id or you want to undelete records with some conditions, manually delete is not an option, use Apex code for it.

You not really need to be good developer to utilize Apex code. Here we go:

1. Open Developer Console
From your name in top right, look for Developer Console











2.From Developer Console
Go to Debug menu and select Open Execute Anonymous Window











3. Enter SOQL 
Example:
Account[] a = [SELECT Id FROM Account WHERE name = 'singtel' ALL ROWS];
undelete a;
Important to add ALL ROWS, otherwise deleted records will be not return on query.






4. Monitor Apex Debug Log
Go to Monitor - Logs - Debug Logs (in Salesforce menu, not Developer console)
Add user to monitor, default it will capture 20 log request for the users

5. Execute 
Click Execute button in Enter Apex Code window

6. Back to Debug Log
Select latest debug log and click View to monitor

Thursday 1 August 2013

Using Rerender to Render — One Solution for Headaches?

It's a regular occurrence to have an <apex:outputPanel> or similar element in a Visualforce page, where you want to toggle visibility of said element according to some variable. Something that's caught both myself and fellow teammates out on a few such occasions is finding that it just won't appear again after being removed from the screen, when the page code looks analogous like the following.

<apex:outputPanel id="thePanel" rendered="{!bRenderThePanel}">
    <!-- Content -->
</apex:outputPanel>

<apex:commandButton action="{!DoSomeCalcs}" rerender="thePanel" value="FIRE!"/>

In this example, the action DoSomeCalcs is implemented such that it will toggle the value of the variable bRenderThePanel and so the result should be that the panel is alternately displayed and hidden with each click of the button. Woe is the developer, as this is not the case. Chances are you'll find yourself confused as to why it just won't reappear (or appear in the first place).

Essentially re-rendering a specified panel (or other component) that is not currently displayed will fail, and the solution is to wrap it with a component that is always present, using that as the target for the re-render. Thus our example becomes:

<apex:outputPanel id="thePanelWrapper">
    <apex:outputPanel rendered="{!bRenderThePanel}">
        <!-- Content -->
    </apex:outputPanel>
</apex:outputPanel>

<apex:commandButton action="{!DoSomeCalcs}" rerender="thePanelWrapper" value="FIRE!"/>

What does seem strange to me is that Salesforce have specifically ensured that you can access DOM elements within an <apex:outputPanel> when it's not displayed, as indicated by the documentation for the layout attribute, it seems odd that this functionality does not carry over for the element itself when it's being used as a re-render target.

The layout style for the panel. Possible values include "block" (which generates an HTML div tag), "inline" (which generates an HTML span tag), and "none" (which does not generate an HTML tag). If not specified, this value defaults to "none". However, if layout is set to "none", for each child element with the rendered attribute set to "false", the outputPanel generates a span tag, with the ID of each child, and a style attribute set to "display:none". Thus, while the content is not visible, JavaScript can still access the elements through the DOM ID.

Happy coding!

Tuesday 30 July 2013

AggregateResult in Salesforce?

AggregateResult in Salesforce is used to find Sum, Min, Max and Avg. It is similar to Aggregate function in SQL.

Using Aggregate Result, we cannot fetch data. It is mainly used to find Sum, Min, Max and Avg.

Sample Code:

Visualforce page:

<apex:page controller="Sample" sidebar="false" action="{!show}">
<apex:pagemessages />
<apex:form >
    <apex:pageBlock >
        <apex:pageblockTable value="{!SummaryList}" var="r">          
            <apex:column headerValue="Account Name" value="{!r.AcctName}"/>
            <apex:column headerValue="Number of Contacts" value="{!r.Total}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Controller:

public with sharing class Sample {
    public List<AggregateResult> Result {get;set;}  
    public List<Summary> SummaryList {get;set;}
    public List<Account> AcctList;
    public Map<Id, Account> IdAccount;
    List<Id> Ids;
   
    public void show() {
        SummaryList = new List<Summary>();
        Result = new List<AggregateResult>();
        Ids = new List<Id>();
        AcctList = new List<Account>();
        IdAccount = new Map<Id, Account>();
       
        Result = [SELECT Count(Id) Total , AccountId FROM Contact GROUP BY AccountId];              
       
        for(AggregateResult a : Result) {  
            Ids.add((Id)a.get('AccountId'));
        }
       
        AcctList = [SELECT Name FROM Account WHERE Id IN : Ids];
       
        System.debug('Account List' + AcctList);
       
        for(Account a : AcctList) {
            IdAccount.put(a.Id, a);          
        }
       
        System.debug('Ids and Accounts are ' + IdAccount);
               
        for(AggregateResult a : Result) {
            Account TempAcct = new Account();          
            TempAcct = IdAccount.get((Id)(a.get('AccountId')));
            system.debug('Account Name is ' + TempAcct.Name);
            SummaryList.add(new Summary(a, TempAcct.Name));              
        }  
    }
   
    public class Summary {
        public Integer Total {get;set;}
        public String AcctName {get;set;}
       
        public Summary(AggregateResult a, String AccountName) {
            Total =  (Integer)a.get('Total');
            AcctName = AccountName;
        }
    }
}
 output:


Tuesday 16 July 2013

insufficient_access_on_cross_reference_entity APEX / Salesforce

Even though i understood what this means and have dealt with it earlier, this time this error message sucked my brain for one week. Finally, i got it sorted out and i hope this post helps someone understand and solve as well.

When does this error happen?
This error normally happens when a DML operation is performed. Meaning that, whenever an Insert or Update is performed. You won't see this error when you save your APEX class or TRIGGER, because this error happens at RUNTIME.

What does this error mean?
This error means that you are trying to do an operation which is not supposed to be done, or the operation you are about to perform is not permitted according to the Sharing and Security settings defined. This error message does NOT always mean that you lack access to do the operation, even though it might be the case sometimes. So, even if you are an ADMINISTRATOR you may get this message.

Possible Causes:
Let's take some scenario's and analyze.

 Scenario 1:  Creating a new record (Account/Contact/...) and setting the Owner. Applies to updating records as well.

So, in your code you create some records. By Default the creator of the record is the Owner. You want to change this and you modify the OwnerId column of the newly created records. You make "User X" as the Owner. Now when you run the code, you get the Error below:
System.DmlException: Insert failed. First exception on row 2; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

Things to check:
  *Check that the running user (in this case you) has access to the object being operated. Check that he has CREATE privileges on the object. This is optional, but is always better to start from here.
  *Check that the Owner ie User X has CREATE permission on the object. Check that his profile has the CREATE permission on the particular object. He might not be having it, grant him permission and the issue is resolved.

 Scenario 2:
Creating or Updating an Opportunity (just for an example,  might be any object). Setting the related Account of the Opportunity.

So, let's say that you create 5 Opportunities and you set the Owner to "User X". You set the Account to "Account X". When your code tries to insert these 5 opportunities, it fails and you get the same error message.
System.DmlException: Insert failed. First exception on row 2; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []
Reason:
This is because "User X" does not have access to "Account X". When you try to create an Opportunity for "Account X" that he does not have access to the code fails. Either grant access to "User X" for "Account X" manually or through code and then do the Insert.

Scenario 3:
The Sharing Object.

This is a bit complex to get at. atleast for me. You might be aware that every object has its own Share object. So, Account has AccountShare and Customobj__c has Customobj__Share
When you insert or update records in this object you might receive the same error message. There are a number of reasons for this to happen.

    *If you are trying to share "Record X" with "User Y" and you yourself do not have access to "Record x", this error happens.
    *If you are trying to share "Record X" with "User Y" and "User Y" does not have access to the object (the profile level permission, create read edit delete), this error happens.
    *If you are trying to share "Record X" with "User Y" and "User Y" already has access to "Record X" this error happens.

Read and Insert records from a CSV file - Using Visualforce?

The Apex Data Loader is always there when you want to insert records into Salesforce from a CSV file. But, just in case if you don't want your users to install the Apex Data Loader and learn how to use it, then here is a simple example which tells you how to do the same using Visualforce.

Click here to view the demo.


Step 1:

Download the template from the DEMO URL above. Save the file in your desktop. Upload the file into Static Resources with the name "AccountUploadTemplate".

Step 2:

Create an Apex Class named "FileUploader". Paste the code below and save it.



public class FileUploader
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Account> accstoupload;
 
    public Pagereference ReadFile()
    {
        nameFile=contentFile.toString();
        filelines = nameFile.split('\n');
        accstoupload = new List<Account>();
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
         
            Account a = new Account();
            a.Name = inputvalues[0];
            a.ShippingStreet = inputvalues[1];    
            a.ShippingCity = inputvalues[2];
            a.ShippingState = inputvalues[3];
            a.ShippingPostalCode = inputvalues[4];
            a.ShippingCountry = inputvalues[5];

            accstoupload.add(a);
        }
        try{
        insert accstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }  
        return null;
    }
 
    public List<Account> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
            else
                return null;                  
        else
            return null;
    }          
}

Step 3:

Create a Visualforce Page named "UploadAccounts". Paste the code below and save it.



<apex:page sidebar="false" controller="FileUploader">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Accounts. <a href="{!URLFOR($Resource.AccountUploadTemplate)}" target="_blank"> Click here </a> to download the template. </b> </font>
             </center>
   
   
      <apex:pageblocktable value="{!uploadedAccounts}" var="acc" rendered="{!NOT(ISNULL(uploadedAccounts))}">
          <apex:column headerValue="Account Name">
              <apex:outputField value="{!acc.Name}"/>
          </apex:column>
          <apex:column headerValue="Shipping Street">
              <apex:outputField value="{!acc.ShippingStreet}"/>
          </apex:column>
          <apex:column headerValue="Shipping City">
              <apex:outputField value="{!acc.ShippingCity}"/>
          </apex:column>
          <apex:column headerValue="Shipping State">
              <apex:outputField value="{!acc.ShippingState}"/>
          </apex:column>
          <apex:column headerValue="Shipping Postal Code">
              <apex:outputField value="{!acc.ShippingPostalCode}"/>
          </apex:column>
          <apex:column headerValue="Shipping Country">
              <apex:outputField value="{!acc.ShippingCountry}"/>
          </apex:column>
      </apex:pageblocktable>
   
      </apex:pageBlock>    
   </apex:form>
</apex:page>



Screenshot:


Some pointers:
You can use only the standard template. Because, that's how we have done the mapping to the columns in excel and the fields in Salesforce. You can modify the mapping and use your own template.
Allowing the user to choose his own mapping is possible i believe, but may be a bit complex.
Also, we use a CSV file. So, you may have to use additional criteria if your data values itself have a comma in them (For ex: Billing Street = 'Mumbai, India ') . This would cause problems because Mumbai and India would be considered as seperate values because of the comma in between them.

Getter and setter methods - What are they?

Well, once you start using a controller or an extension you will get used to these words...

So, it is good that we understand what these methods really do..

Getter and setter methods are used to pass data from your visualforce page to your controller and vice versa..

Let's take a very simple scenario... Let's assume you want to display a textbox in your visualforce page.. When the user enters some value in this textbox and clicks on a button you want the value entered by the user in your Apex class (ie. basically your controller or extension)

So go ahead and create a simple visualforce page.. the code for this would be
<apex:page controller="simplegetset">
  <apex:form>
    <apex:outputlabel value="Enter your name here"/>
       <apex:inputtext value="{!userinput}"/>        
  </apex:form>  
</apex:page>


The Apex code for this page would be...

public class simplegetset
{
    public String userinput{get; set;}
}


Now, the variable "userinput" in your Apex class will store the value entered by the user....

Let's analyze the methods now...

Get

The "get" method is used to pass data from your Apex code to your Visualforce page.. In our example we are not passing any value.. hence, when your page loads initially the textbox will have a empty value...

So, lets modify our code and pass a default value to the textbox.. Change the Apex code as follows..

public class simplegetset
{
    public String userinput;
    public String getuserinput(){return 'John';}
 
    public void setuserinput(String userinput)
    {
        this.userinput = userinput;
    }  
}


You can now see that your page loads with a value 'John'...

Set

The "set" method is used to pass values from your visualforce page to the controller... In our example the variable "userinput" will be storing the value entered in the textbox..

Now modify your VF page as below..

<apex:page controller="simplegetset">
  <apex:form>
    <apex:outputlabel value="Enter your name here"/>
       <apex:inputtext value="{!userinput}">
           <apex:actionsupport event="onclick" rerender="display" />
       </apex:inputtext>                  
    <apex:outputpanel id="display">
        <apex:outputtext value="The name entered is {!userinput}"/>
    </apex:outputpanel>                  
  </apex:form>  
</apex:page>


The Apex code would be...

public class simplegetset
{
    public String userinput{get; set;}
}


In this example what happens is.. the variable "userinput" stores the value entered in visualforce page and passes it to the Apex code.. hence you are able to see the entered value in the visualforce page..

I guess you might understand what i am saying.. to make things simple now use the same visualforce page.. but modify the Apex code as below..

public class simplegetset
{
    public String userinput;
    public String getuserinput(){return 'John';}
 
    public void setuserinput(String userinput)
    {
        this.userinput = userinput;
    }  
}


Now, whatever value you enter the page always displays "The name entered is John".... This is because your get method always returns 'John'... but still your set method will store the value you entered in the variable "userinput"....

Sunday 14 July 2013

How to undelete records Using Apex?

Salesforce keep record you delete to Recycle Bin for 15 days with maximum record of 25 times the Megabytes (MBs) in your storage. For example, if your organization has 1 GB of storage then your limit is 25 times 1000 MB or 25,000 records. If your organization reaches its Recycle Bin limit, Salesforce automatically removes the oldest records if they have been in the Recycle Bin for at least two hours.

You can manually undelete records by click Recycle Bin icon in bottom left menu. Undelete account will include contact, case, opportunity tagged to that Account. But, if you have many records or you have specific record Id or you want to undelete records with some conditions, manually delete is not an option, use Apex code for it.

You not really need to be good developer to utilize Apex code. Here we go:

1. Open Developer Console
From your name in top right, look for Developer Console











2.From Developer Console
Go to Debug menu and select Open Execute Anonymous Window











3. Enter SOQL 
Example:
Account[] a = [SELECT Id FROM Account WHERE name = 'singtel' ALL ROWS];
undelete a;
Important to add ALL ROWS, otherwise deleted records will be not return on query.






4. Monitor Apex Debug Log
Go to Monitor - Logs - Debug Logs (in Salesforce menu, not Developer console)
Add user to monitor, default it will capture 20 log request for the users

5. Execute 
Click Execute button in Enter Apex Code window

6. Back to Debug Log
Select latest debug log and click View to monitor

Tuesday 9 July 2013

How to fetch Contact details from Opportunity using SOQL in Salesforce?

Query:

SELECT Id, Opportunity.Name, Opportunity.OrderNumber__c, Opportunity.Approval_Status__c, Contact.Email, Contact.Name FROM OpportunityContactRole

Output:


"SYSTEM.QUERYEXCEPTION: LIST HAS NO ROWS FOR ASSIGNMENT TO SOBJECT"

So I was quering Account a = [Select name from account where id=: strld];
and an exception was thrown: System.QueryExceptoin: List has no rows for assignment to SObject.

Here is the mistake I made and how to fix it:

List<Account>lst = [Select name from account where id=: strld];



Thursday 20 June 2013

Adding Rows Dynamically to Page block Table ?

Apex:

public class MemberPopup
{
    public List<Account> memberList {get;set;}
    public List<Account> memberAddList {get;set;}
    public String memberName {get;set;}      
    public MemberPopup()
    {
        String sql = 'SELECT Name,Company__c FROM Account';
        memberList = Database.Query(sql);
        memberAddList = new List<Account>();
        memberAddList.add(new Account());
    }  
    public void AddRow()
    {
        memberAddList.add(new Account());
    }
}



VF Page:

<apex:page controller="MemberPopup" >
<apex:form >
    <apex:pageBlock id="membAdd" >                
        <apex:pageblockSection >
            <apex:pageBlockTable value="{!memberAddList}" var="m" >
                <apex:column headerValue="Member Name">
                    <apex:inputField value="{!m.Name}"/>
                </apex:column>
                <apex:column headerValue="Mobile Number">
                    <apex:inputField value="{!m.Company__c}"/>
                </apex:column>
                <apex:column headerValue="eMail Id">
                    <apex:inputField value="{!m.Account_Status__c}"/>
                </apex:column>
            </apex:pageBlockTable>
            <br/><apex:commandLink value="Add Row" action="{!addRow}" reRender="membAdd"/>      
        </apex:pageblockSection>      
        <apex:pageblockSection columns="1" >
            <apex:pageblockSectionItem >
                <apex:commandButton value="Save" />
                <apex:commandButton value="Cancel" />
            </apex:pageblockSectionItem>       
        </apex:pageblockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>



how to get a picklist values in apex controller?

Apex:
public class PicklistController{

    public Lead lead{get;set;}
    public List<SelectOption> statusOptions {get;set;}
   
    // Constructor called when page is accessed.
    public PicklistController() {   
        lead = new Lead();       
        statusOptions = new List<SelectOption>();

        // Use DescribeFieldResult object to retrieve status field.
        Schema.DescribeFieldResult statusFieldDescription =  Lead. Status.getDescribe();
        // For each picklist value, create a new select option
        for (Schema.Picklistentry  picklistEntry: statusFieldDescription.getPicklistValues())
{
            statusOptions.add(new SelectOption( pickListEntry.getValue(),pickListEntry.getLabel()));
            // obtain and assign default value
         
        }    
    }
}

VF Page:
<apex:page controller="PicklistController">
    Please selectValue:
    <apex:form >
        <apex:selectList size="1" value="{!led.Status}">
            <apex:selectOptions value="{!statusOptions}"/>
        </apex:selectList>
    </apex:form>  
</apex:page>

Screen Shot:





Sunday 26 May 2013

how to lock a record?

To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement

To display all the fields of sObject using Apex & VF?

<apex:page showHeader="false" Controller="FieldsClass">
        <apex:DataTable value="{!data}" var="d">
             <apex:column headerValue="Field Name">
                 {!d}
             </apex:column>         
         </apex:DataTable>
</apex:page>
*******************************
public class  FieldsClass {

     public map<string,Schema.SObjectField> data {get;set;}
  
     public  FieldsClass (){
         data = Schema.SObjectType.Book__c.fields.getMap();
        }
    }