Monday, June 24, 2013

Salesforce - Pass parameter value from one page to another page

Here i have provided a sample to understand how to pass parameter value from one page to another and retrieve it. I have used two pages named Books and SelectedBooks. Books page has a PageBlockTable it dispalyes only book names from the Book_c custom object. The book names are displayed as links using <apex:CommandLink>. When a user click the link the first page Book is navigate to second page SelectedBook with the parameter value that is passed using <apex:param>. The Second page then retrieves the parameter value and displays the book details in a PageBlockTable
Design code for Books page:

By default the PageBlockTable displays its value as OutputLabel but we need to click the value for navigation purpose. So here i used <apex:commandLink> to convert it as Link. Book name is passed as parameter using <apex:param>

<apex:page controller="BooksController">  
   <apex:form >  
   <apex:sectionHeader subtitle="All Books" title="Books"/>  
      <apex:pageBlock >  
       <apex:pageBlockTable value="{!allbooks}" var="a">  
           <apex:column headervalue="Name">  
                 <apex:commandLink value="{!a.Name}" action="/apex/SelectedBook?id={!a.Name}">  
                 <apex:param name="id" value="{!a.Name}"/>  
                 </apex:commandLink>  
           </apex:column>  
             </apex:pageBlockTable>  
        </apex:pageBlock>  
   </apex:form>  
 </apex:page>  

Apex Code for Books page controller:

Here the getAllBooks fuction retrive the values from the Book__c custom objects and bind it to the PageBlockTable

 public class BooksController
 {  
      public List<Book__c> allbooks;   
      public List<Book__c> getAllBooks()  
      {  
           if(allbooks==null)  
           {  
                allbooks=[SELECT Name,Book_Author__c,Book_ISBN__c from Book__c];  
           }  
      return allbooks;  
      }  
 }  

Apex Code for SelectedBook page controller:

Here in the constructor the parameter value is retrieved using its name. Using that value the getSbook function gets the specific book details and bind it to the PageBlockTable.

 public class SelectedBookController 
 {  
      public String selectedName {get;set;}  
      public Book__c sbook;  
      public SelectedBookController()  
      {  
           sbook=new Book__c();  
           selectedName = ApexPages.currentPage().getParameters().get('id');  
      }  
       
      public Book__c getSbook()  
      {  
           sbook=[Select Name,Book_ISBN__c,Book_Author__c from Book__c where Name=:selectedName];  
           return sbook;  
      } 
 } 

Design code for SelectedBook page:

<apex:page controller="SelectedBookController">  
 <apex:form >  
      <apex:pageBlock >  
           <apex:pageBlockTable value="{!sbook}" var="b">  
                <apex:column value="{!b.Name}"/>  
                <apex:column value="{!b.Book_Author__c }"/>  
               <apex:column value="{!b.Book_ISBN__c}"/>  
             </apex:pageBlockTable>  
      </apex:pageBlock>  
 </apex:form>  
 </apex:page>  

Thursday, June 20, 2013

Salesforce - Insert data into Custom object using Apex

To insert data to Custom object using Apex just understand the below code. This is the basic for all other complex apex programming. Here in the Save() function the data you have enter in the text box will be saved. After inserting the data i am refreshing the page to clear the values in the text boxes. You han find the code in that function.
Apex Design Code:
 <apex:page controller="AddUserController">  
   <apex:form >  
     <apex:sectionHeader subtitle="All Books" title="Books" />  
     <apex:pageBlock >  
       <apex:PageBlockButtons >  
         <apex:commandButton action="{!Save}" value="Save"/>  
       </apex:PageBlockButtons>  
       <apex:pageBlockSection >  
         <apex:InputField value="{!users.Name}"/><br/>  
         <apex:InputField value="{!users.Age}" /><br/>  
         <apex:InputField value="{!users.Class}" /><br/>  
       </apex:pageBlockSection>  
   </apex:pageBlock>  
   </apex:form>  
 </apex:page>  

Apex Controller Code:
public class AddUserController  
 {  
   public User__c users;  
   public AddUserController()  
   {  
     users=new User__c();  
   }  
   public User__c getUsers()  
   {  
     return users;  
   }  
   public PageReference Save()  
   {  
     try  
     {  
       insert(users);  
       PageReference pagr= Page.UsersPage;  
       pagr.setRedirect(true);  
       return pagr;  
     }  
     catch(System.DMLException e)  
     {  
       return null;  
     }  
   }  
 }  

Salesforce - Display data from Custom object to PageBlockTable using Apex

Here i have provided code sample to understand, how to display data from custom objects to PageBlockTable. I have chosen pageBlocktable because it has predefined style. Don't want to use any css styles for that.
Apex Design Code:
 <apex:page controller="ViewUserController">  
   <apex:form >  
     <apex:sectionHeader subtitle="All Users" title="Users" />  
     <apex:pageBlock >  
       <apex:pageBlockTable value="{!allusers}" var="a">  
         <apex:column headervalue="Name" value="{!a.Name__c}" />  
         <apex:column headervalue="Age" value="{!a.Age__c}" />  
         <apex:column headervalue="Class" value="{!a.Class__c}" />  
       </apex:pageBlockTable>  
     </apex:pageBlock>  
   </apex:form>  
 </apex:page>  
Apex Controller Code:
 
 public class ViewUserController  
 {  
     public List<User__c> allusers;    
     public List<User__c> getAllUsers()  
     {  
         if(allusers==null)  
         {  
             allusers=[SELECT Name__c,Age__c,Class__c from User__c];  
         }  

         return allusers;  
     }  
 }  

Gridview Edit, Update, Delete sample in ASP.NET

Here is a simple and complete source code to get an idea about how to Edit, Delete, Update data in Gridview using Gridview events like RowEditing, RowDeleting, RowUpdating. To run this application you need to create a table like shown below in SQL Table section. Updating data is just a straight forward method but to delete a record you need to set the DataKeyNames properties to the column name you using as a key in table. So that in the c# code you can retrieve the Id value when you click the Delete link in Gridview. You cannot use the method like i used in the RowUpdating event to the RowDeleting event to retrieve the Id value. It will only return null. Also don't forget to use IsPostBack in the Page_Load event.
SQL Table

Id               int                      
Name         nvarchar(MAX)
Address     nvarchar(MAX)

C# Code
string constr = @"Data Source=VENKAT;Initial Catalog=Test;Integrated Security=true";  
 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     bindGridView();  
   }  
 }  

 protected void bindGridView()  
 {  
   try  
   {  
     string query = "SELECT * FROM Grid ";  
     SqlConnection con = new SqlConnection(constr);  
     con.Open();  
     SqlDataAdapter da = new SqlDataAdapter(query, con);  
     DataSet ds = new DataSet();  
     da.Fill(ds);  
     GridView1.DataSource = ds;  
     GridView1.DataBind();  
   }  
   catch (Exception ex)  
   {  
   }  
 }  

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
 {  
   GridView1.EditIndex = e.NewEditIndex;  
   HiddenField1.Value = e.NewEditIndex.ToString();  
   bindGridView();  
 }  

 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
 {  
   GridView1.EditIndex = -1;  
   bindGridView();  
 }  

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
 {  
   GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];  
   int index = Convert.ToInt32(row.RowIndex);  
   TextBox tId = (TextBox)row.FindControl("txtId");  
   TextBox tName = (TextBox)row.FindControl("txtName");  
   TextBox tAddress = (TextBox)row.FindControl("txtAddress");  
   GridView1.EditIndex = -1;  
   SqlConnection conn = new SqlConnection(constr);  
   conn.Open();  
   SqlCommand cmd = new SqlCommand("UPDATE Grid set Name='" + tName.Text + "',Address='" + tAddress.Text + "' WHERE Id=" + tId.Text + "", conn);  
   cmd.ExecuteNonQuery();  
   bindGridView();  
   conn.Close();  
 }  

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
 {  
   string id = GridView1.DataKeys[e.RowIndex].Value.ToString();  
   SqlConnection conn = new SqlConnection(constr);  
   conn.Open();  
   SqlCommand cmd = new SqlCommand("delete from Grid where Id=" + id + "", conn);  
   cmd.ExecuteNonQuery();  
   conn.Close();  
   bindGridView();  
 }  

Design Code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id"  
       onrowcancelingedit="GridView1_RowCancelingEdit"  
       onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"  
       onrowupdating="GridView1_RowUpdating" RowStyle-VerticalAlign="Top"  
       AutoGenerateColumns="False">  
       <RowStyle VerticalAlign="Top" />  
       <Columns>  
         <asp:TemplateField ShowHeader="False">  
           <EditItemTemplate>  
             <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"  
               CommandName="Update" Text="Update"></asp:LinkButton>  
             &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"  
               CommandName="Cancel" Text="Cancel"></asp:LinkButton>  
           </EditItemTemplate>  
           <ItemTemplate>  
             <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"  
               CommandName="Edit" Text="Edit"></asp:LinkButton>  
           </ItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField ShowHeader="False">  
           <ItemTemplate>  
             <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"  
               CommandName="Delete" Text="Delete"></asp:LinkButton>  
           </ItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Id">  
             <ItemTemplate>  
               <%# Eval("Id")%>  
             </ItemTemplate>  
             <EditItemTemplate>  
               <asp:TextBox ID="txtId" runat="Server" Text='<%# Eval("Id") %>' Columns="30"></asp:TextBox>  
             </EditItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Name">  
             <ItemTemplate>  
               <%# Eval("Name")%>  
             </ItemTemplate>  
             <EditItemTemplate>  
               <asp:TextBox ID="txtName" runat="Server" Text='<%# Eval("Name") %>' Columns="30"></asp:TextBox>  
             </EditItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Address">  
             <ItemTemplate>  
               <%# Eval("Address")%>  
             </ItemTemplate>  
             <EditItemTemplate>  
               <asp:TextBox ID="txtAddress" runat="Server" Text='<%# Eval("Address") %>' Columns="30"></asp:TextBox>  
             </EditItemTemplate>  
         </asp:TemplateField>  
       </Columns>  
</asp:GridView>