Sunday, 4 August 2013

Chatter for VF Page


 Display Chatter Feeds on a Visual force Page:-

  Vf page:- 


   <apex:page controller="test12">
   <apex:form id="main">
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:inputTextarea value="{!comment}" style="width:500px;height:50px;"/>
            <apex:commandButton action="{!post}" value="Post" reRender="main,reff"/>
        </apex:pageBlockSection>
        <apex:pageBlockTable value="{!feditm}" var="f"> 
            <apex:column value="{!f.CreatedBy.Name}"/> &nbsp;&nbsp;&nbsp;&nbsp;
            <apex:column value="{!f.Body}" /> <br/>
        </apex:pageBlockTable>
    </apex:pageBlock>
   </apex:form> 
</apex:page>

class:-


public class test12 {

   
    public String comment { get; set; }
    public List<FeedItem> feditm{get;set;}
  
    public test12(){
        feed(); 
    }
   
    public void post() {
        
        FeedItem post = new FeedItem();
        post.ParentId = Userinfo.getUserId(); //eg. Opportunity id, custom object id..
        post.Body = comment;
        post.CreatedById = Userinfo.getUserId();
        insert post;
        feed();
    }
    public void feed(){
        feditm = [select Body,InsertedById,CreatedBy.Name from FeedItem ORDER BY CreatedDate desc];
        comment='';
    }
}



In above example displaying the chatter feeds on Visual force page for User.

Tuesday, 30 July 2013

Dynamic Date Picker :-


        Today i am going to explain about Dynamic Date Picker in vf page.  
   
   If we want to display a date field in Vf page using custom functionality. (But not Standard field using Standard controller). follow the code ...


   In Vf page:
---------

<script>
function DynamicDatePicker(d_id)
{        
DatePicker.pickDate(true,d_id.id,false);
</script>
Date:: <apex:inputText value="{!var_date}" id="time" onfocus="DynamicDatePicker(this);"/>


In apex class:-
-----------

public Date var_date{get;set;}




Here the var_date is text field in Vf page, So i am using java script functionality to get the date Dynamically.

Monday, 18 March 2013

onChange of Pick list value Another Page block section should be Rendered

Hi,
 Create VF page , i.e onChange of pick list value Stage to 'closed lost' Another page block section should visible, if you select another stage value it should be hide.

See the code below,

  <apex:page standardController="Opportunity" sidebar="false">
    <apex:sectionHeader title="Edit Opportunity" subtitle="{!opportunity.name}"/>
    <apex:form >
        <apex:pageBlock title="Edit Opportunity" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>                
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Basic Information" columns="1">
                    <apex:inputField value="{!opportunity.name}"/>
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Stage"/>
                        <apex:outputPanel >
                            <apex:inputField value="{!opportunity.stageName}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                    <apex:inputField value="{!opportunity.amount}"/>
                    
                </apex:pageBlockSection>
            </apex:actionRegion>

 <!-- This is another page block section , it visible when stage is 'closed lost' --> 
            <apex:pageBlockSection title="Closed Lost Information" columns="1"
                                   rendered="{!opportunity.stageName == 'Closed Lost'}">
                <apex:inputField value="{!opportunity.closedate}"/>
                <apex:inputField value="{!opportunity.amount}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Display Duplicate Records count

Here We have a scenario.

In Account object we have lot of records. If we need to know , how many  records with the same name present in your object.

Record Name and that record count..

Please look at this code.

Vf Page:-
----------

<apex:page controller="test4">
 <apex:pageblock title="Map Usage On VF">
     <apex:pageBlockTable value="{!data}" var="d">
         <apex:column headerValue="Account Name">
             {!d}
         </apex:column>
         <apex:column headerValue="Duplicate Count">
             {!data[d]}
         </apex:column>
     </apex:pageBlockTable>
 </apex:pageblock>
</apex:page>


Controller
------------

public class test4{
 
    public map<string,integer> data {get;set;}
    public test4(){
        data = new map<string,integer>();
        for(Account acc: [Select Id, Name, (Select Id, Name, Email from Contacts), Phone from Account]){
            integer count = data.get(acc.name);
            if(count != null)
                count++;
            else
                count = 1;
            data.put(acc.name, count);
        }
    }
}

Monday, 4 February 2013

How to change the Date format in Visual force:-




Hi Guys ,Now i am going to tell, Changing the date format in VF page.


Example:- Here i need Today Date in this format " February 15th, 2013"


Here we go like,

<apex:outputText value="{0,date,MMMMMMMM d'th', yyyy}">
                    <apex:param value="{!Today()}" />
 </apex:outputText>


 If Date/Datetime field taking from Apex . if you want to display above format.


<apex:outputText value="{0,date,MMMMMMMM d'th', yyyy}">
                    <apex:param value="{!variablename}" />
 </apex:outputText>

Thursday, 31 January 2013

Working on Java script.


Hi guys, Here i did some Java script stuff , i am sharing with you guys,


Hi Guys Here we have a scenario, Create a VF page with two buttons. Those are
"Open in PDF" and "Open in Word" ,
When we click on any button the vf page should open in Pdf/Word format Based on Button click.
Here we go..



<apex:page controller="some class" showHeader="false" renderAs="{!ispdf}" contentType="{!isword}">

.........
......
.........


<center><br/>
    <apex:form rendered="{!isvf}" id="frm1">

        <apex:commandButton reRender="frm1" action="{!donothing}" value="Open in PDF" onclick="window.open('/apex/vf page name?id={!$CurrentPage.parameters.id}&type=pdf','_blank')"/>

        <apex:commandButton reRender="frm1" action="{!donothing}" value="Open in Word"  onclick="window.open('/apex/vf page name?id={!$CurrentPage.parameters.id}&type=word','_blank')"/>

   </apex:form>
  </center>

</apex:page>



How to get user id in Java script Buttons.
alert('{!$user.Id}');

How to get profile id in Java script Buttons.
alert('{!$Profile.Id}');


How to open a Vf page in a new Window using java script button.

{!REQUIRESCRIPT("/soap/ajax/8.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}

var url="/apex/vf page name ?id={!Opportunity.Id}";

if('{!$Profile.Id}'=='some id' ||'{!$Profile.Id}'=='some id') // it should work for two profiles only
{
      newWin=window.open(url, 'Popup','height=800,width=1100,left=100,top=100,Right=100');
}


How to write code for save & close operation done in one button click.


<apex:commandButton action="{!save}" value="Save" rerender="AJAXTest" status="AJAXStatus"/> 
<apex:actionStatus startText="(Saving...)" stopText="" onStop="window.top.close();" ID="AJAXStatus"/>

=========================================









Wednesday, 23 January 2013

Counting The Duplicate Records


Hi all, the scenario is just count the duplicate records. How many times that record is arrived. 
we are displaying in VF page..

<apex:page controller="test4">
 <apex:pageblock title="Map Usage On VF">
     <apex:pageBlockTable value="{!data}" var="d">
         <apex:column headerValue="Account Name">
             {!d}
         </apex:column>
         <apex:column headerValue="Duplicate Count">
             {!data[d]}
         </apex:column>
     </apex:pageBlockTable>
 </apex:pageblock>
</apex:page>



public class test4{
   
    public map<string,integer> data {get;set;}
    public test4(){
        data = new map<string,integer>();
        for(Account acc: [Select Id, Name, (Select Id, Name, Email from Contacts), Phone from Account]){
            integer count = data.get(acc.name);
            if(count != null)
                count++;
            else
                count = 1;
            data.put(acc.name, count);
        }
    }
}



reRender Functionality Using Action poller:- 


Here we have a scenario.. Increment the counter automatically based on interval time..

<apex:page Controller="Actionpollar1">
    <apex:form >
        <apex:pageBlock >
            <apex:outputText value="{!Increment}" id="Test"/>
            <apex:actionPoller action="{!IncrementValue}" interval="5" reRender="Test"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>


public class Actionpollar1
{
    public String getIncrement() {
        return null;
    }
    public Integer Increment { get; set; }
     public Actionpollar1()
        {
            Increment =0;
        }
    public void IncrementValue() {
       
       Increment=Increment+1;
    }
}

Tuesday, 8 January 2013

Select/Deselect all Check boxces:- (08/01/12)


Hi guys we have a scenario, When we select/deselect the header check box the other all
 check boxes Should be select/deselect. And display the selected check boxes .


<apex:page controller="test7">
    <apex:form >
        <apex:pageBlock Title="Accounts with CheckBoxes">
            <apex:pageBlockSection Title="List of Available Accounts">
                <apex:pageBlockTable value="{!accounts}" var="a" columnswidth="50px,50px" cellpadding="4" border="1">
                    <apex:column >
                        <apex:facet name="header"> <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!GetSelected1}" onsubmit="checkAll(this)" rerender="Selected_PBS"/>
                            </apex:inputCheckbox>
                        </apex:facet>
                        <apex:inputCheckbox value="{!a.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected1}" rerender="Selected_PBS"/></apex:inputCheckbox>
                    </apex:column>
                    <apex:column headervalue="Account Name" value="{!a.acc.Name}" />
                    <apex:column headervalue="Account Number" value="{!a.acc.AccountNumber}" />
                    <apex:column headervalue="Phone" value="{!a.acc.Phone}" />
                </apex:pageBlockTable>
            </apex:pageBlockSection>

            <apex:pageBlockSection Title="Selected Accounts" id="Selected_PBS">
                <apex:dataTable value="{!SelectedAccounts}" var="s" columnswidth="50px,50px" cellpadding="4" border="1">
                    <apex:column headervalue="Account Name" value="{!s.Name}" />
                    <apex:column headervalue="Account Number" value="{!s.AccountNumber}" />
                    <apex:column headervalue="Phone" value="{!s.Phone}" />
                </apex:dataTable>
            </apex:pageBlockSection>

        </apex:pageBlock>
    </apex:form>
    <script>
        function checkAll(cb)
        {
            var inputElem = document.getElementsByTagName("input");
            for(var i=0; i<inputElem.length; i++)
            {
                if(inputElem[i].id.indexOf("checkedone")!=-1)
                inputElem[i].checked = cb.checked;
            }
        }
    </script>
</apex:page>



public class test7 {
 
    List<accountwrapper> accountList = new List<accountwrapper>();
    List<Account> selectedAccounts = new List<Account>();

    public List<accountwrapper> getAccounts()
    {
        for(Account a : [select Id, Name, AccountNumber, Phone from Account limit 5])
        accountList.add(new accountwrapper(a));
        return accountList;
    }

    public PageReference getSelected1()
    {
        selectedAccounts.clear();
        for(accountwrapper accwrapper : accountList)
        if(accwrapper.selected == true)
        selectedAccounts.add(accwrapper.acc);
        return null;
    }

    public List<Account> GetSelectedAccounts()
    {
        if(selectedAccounts.size()>0)
        return selectedAccounts;
        else
        return null;
    }   

    public class accountwrapper
    {
        public Account acc{get; set;}
        public Boolean selected {get; set;}
        public accountwrapper(Account a)
        {
            acc = a;
            selected = false;
        }
    }
}



-----------------

Here we have a scenario, Search the records by giving it's Name.


<apex:page standardController="Account" Extensions="secondinterview" standardStylesheets="true">
 
  <apex:form >
    <apex:pageBlock id="id" title="Interview Two">
   
        <apex:pageBlockSection title="Search">
            Search:<apex:inputtext value="{!str1 }"/>
           &nbsp; <apex:commandButton action="{!Search}" value="search" reRender="id"/>
        </apex:pageBlockSection>
       
        <apex:pageBlockButtons >
            
        </apex:pageBlockButtons>
    
     <apex:pageBlockSection title="Result" columns="1">
    <apex:pageBlockTable value="{!Search}" var="Test">            
                   <apex:column headerValue="Account Name">
                       <apex:outputField Value="{!Test.Name}"/>
                   </apex:column>
                   <apex:column headerValue="Billing State/Province">
                         <apex:outputField value="{!Test.BillingState}"/>
                   </apex:column>
                    <apex:column headerValue="Phone">
                           <apex:outputField value="{!Test.Phone}"/>
                    </apex:column>
                    <apex:column headerValue="Website">
                        <apex:outputField value="{!Test.Website}"/>
                    </apex:column>
    </apex:pageBlockTable>
   
    </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>


public class secondinterview {

public String str1 {get;set;}
String str2;
public Account Account{get;set;}
    public secondinterview(ApexPages.StandardController controller) {
        Account=new Account();
    }
public void search1(String s1)
    {
    str1=s1;
   
    }
    Public String search1()
    {
    return str1;
    }
    List<Account> conobj;
     public void Search()
     {
         System.Debug('********************'+Account.Name);
        conobj=[select id,name,BillingState,Phone,Website from Account where Name=:str1];

     }
  
  Public List<Account> getSearch()
  {
    return conobj;
 
  }
}

Monday, 7 January 2013

Check Boxes for Selecting Records:-(01/07/13)


Hi Guys, Today i am going to explain, How the check boxes to use in Vf page, How to call in apex.

Here we have scenario, The user will select one (or more) accounts on the left, click “Show Selected Accounts” and the results will show in the right.


 VF page:-


<apex:page controller="thirdinterview">
  <apex:form >
        <apex:pageBlock title="Interview Three">
       
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="out"/>
            </apex:pageBlockButtons>
           <apex:pageBlockSection columns="2">
            <apex:pageBlockTable value="{!Accounts}" var="Acc" columnsWidth="150px,150px" align="left">
                <apex:column >
                  
                    <apex:inputCheckbox value="{!Acc.selected}"/>
                </apex:column>
               
                <apex:column value="{!Acc.con.Name}" />
                <apex:column value="{!Acc.con.Phone}" />
            </apex:pageBlockTable>
        
               <apex:pageBlockTable value="{!selectedAccounts}" var="Rec" id="out" align="right" title="Selected Accounts">
                    <apex:column headerValue="Account Name">
                        <apex:outputField value="{!Rec.name}"/>
                    </apex:column>  
                    <apex:column headerValue="Phone">
                        <apex:outputField value="{!Rec.Phone}"/>
                    </apex:column>            
                </apex:pageBlockTable>  
          </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
   
</apex:page>

Class:-

public class thirdinterview
{
  public List<cAccount> accList {get; set;}
  public List<Account> selectedAccounts{get; set;}
//Adding the Records to inner class and to get the values for page block table.
  public List<cAccount> getAccounts(){
        if(accList == null){
            accList = new List<cAccount>();
            for(Account acc : [select Id, Name, Phone from Account limit 25]){
                  accList.add(new cAccount(acc));
            }
         }
       return accList;
   }  
//on button click it will show the list of records what we have selected.
  public PageReference processSelected(){    
        selectedAccounts= new List<Account>();
        for(cAccount cCon : getAccounts()) {
            if(cCon.selected == true){
                selectedAccounts.add(cCon.con);
            }
        }           
        return null;
   }
  //  Inner class for capture the records
  public class cAccount {
        public Account con {get; set;}
        public Boolean selected {get; set;}
        public cAccount(Account c) {
            con = c;
            selected = false;
        }
   }
    
}

Friday, 4 January 2013

Roll-up summary Using Trigger:-


Here 
ChildExample2__c  is child object and Amount__c is custom field in this object.
Example2__c  is parent object and Total_Amount__c is custom field in this object.

Roll-up summary means add all Amount fields in Child records , then update total amount with
the parent record.

Here we go

 
    trigger Testduplicate7 on ChildExample2__c (after delete, after insert, after update) {
    set<Id> Ids = new set<Id>();
    if(trigger.isInsert || trigger.isUpdate){
        for(ChildExample2__c p : trigger.new){
            Ids.add(p.Example2__c);
        }
    }
    if(trigger.isDelete){
        for(ChildExample2__c p : trigger.old){
            Ids.add(p.Example2__c);
        }
    }
    map<Id,Double> smap = new map <Id,Double>();
    for(AggregateResult q : [select Example2__c,sum(Amount__c)from ChildExample2__c where Example2__c IN :Ids group by Example2__c]){
        smap.put((Id)q.get('Example2__c'),(Double)q.get('expr0'));
    }
    List<Example2__c> ls = new List<Example2__c>();
    for(Example2__c a : [Select Id, Total_Amount__c from Example2__c where Id IN :Ids]){
        Double PipelineSum = smap.get(a.Id);
        a.Total_Amount__c = PipelineSum;
        ls.add(a);
    }
    update ls;
}


(OR) Another method here we go

/*Rollup summary on any field*/
trigger Test7 on ChildExample2__c (after insert,after update,after delete){
    if(Trigger.isinsert){
        Map<id,decimal> total = new Map<id,decimal>();
        for(ChildExample2__c ch :trigger.new){
            if(ch.amount__c!=null){
                if(total.get(ch.Example2__c)==null){
                    total.put(ch.Example2__c,ch.amount__c);
                }
                else
                {
                    decimal amt = 0;
                    amt = total.get(ch.Example2__c)+ch.amount__c;
                    total.put(ch.Example2__c,amt);
               
                }
            }
        }
        list<Example2__c> elist= new list<Example2__c>();
        list<Example2__c> exList = [select total_amount__c from Example2__c where id in:total.keyset()];
        for(Example2__c a:exList){
            if(a.total_amount__c==null){
                a.total_amount__c=0;
            }
            a.total_amount__c+=total.get(a.id);
            elist.add(a);
        }
        update elist;
    }
    if(Trigger.isUpdate){
        Map<id,decimal> total = new Map<id,decimal>();
        List<ChildExample2__c> chOld = Trigger.old;
        for(ChildExample2__c ch :trigger.New){
            if(ch.amount__c!=null){
                total.put(ch.Example2__c,ch.amount__c);
            }
            else{
                total.put(ch.Example2__c,0);
            }
        }
        Map<id,decimal> acc = new Map<id,decimal>();
        for(ChildExample2__c chod :trigger.old){
            if(chod.amount__c!=null){
                acc.put(chod.Example2__c,chod.amount__c);
            }
            else{
                acc.put(chod.Example2__c,0);
            }
        }
        list<Example2__c> elist= new list<Example2__c>();
        list<Example2__c> exList = [select total_amount__c from Example2__c where id in:total.keyset()];
        for(Example2__c a:exList){
            if(a.total_amount__c==null){
                a.total_amount__c=0;
            }
            System.Debug('==============sizw='+acc.get(a.id));
            a.total_amount__c+=total.get(a.id)-acc.get(a.id);
            elist.add(a);
        }
        update elist;
    }
    if(Trigger.isDelete){
        List<ChildExample2__c> chOld = Trigger.old;
        Map<id,decimal> acc = new Map<id,decimal>();
        for(ChildExample2__c chod :trigger.old){
            if(chod.amount__c!=null){
                acc.put(chod.Example2__c,chod.amount__c);
            }
        }
        list<Example2__c> elist= new list<Example2__c>();
        list<Example2__c> exList = [select total_amount__c from Example2__c where id in:acc.keyset()];
        for(Example2__c a:exList){
            if(a.total_amount__c==null){
                a.total_amount__c=0;
            }
            a.total_amount__c-=acc.get(a.id);
            elist.add(a);
        }
        update elist;
    }
}



Thursday, 3 January 2013

Working With Triggers:-


How to create a Trigger:-

Setup--> App setup--> Any object -->Triggers

Use of Trigger:- Triggers will do automate the Process.

When the Trigger will fire:- When we did DML operations in Records , on that time based on Event 
                                         Triggers will fire.

Here we have Some Events:-

Before Insert
Before Update
Before Delete
After Insert
After Update
After Delete

Example:-

Here we Have a scenario , In contact object we have a Email field, create one field 
domain__c in contact, When we create/update a record in Contact object ,
The Domain Name of Email field should update with domain__c field in same record.

trigger DomainName on Contact (before insert,before update)
{
   if(Trigger.isinsert){
       List<String> allEmailStrings=new List<String>();
       if(Trigger.isbefore){
           for(Contact allconnew:Trigger.new){
               if(allconnew.Email!=null){
                   //List<Contact> conEmailCompare=[select id,name,email from Contact where email=:allconnew.email];  
                   String strEmail = allconnew.email;
                   String strSubEmail = strEmail.substring(strEmail.indexOf('@'),strEmail.length());
                   System.debug('Final String:========> '+ strSubEmail);
                   String strActString = strSubEmail.substring(1,strSubEmail.indexOf('.'));
                   System.debug('Final String:========> '+ strActString);
                   allconnew.domain__c=strActString;
               }
            }
        }
   }
   if(Trigger.isupdate){
        List<String> allEmailStrings=new List<String>();
        if(Trigger.isbefore){
              for(Contact allconnew:Trigger.new){
                  if(allconnew.Email!=null){
                       String strEmail = allconnew.email;
                       String strSubEmail = strEmail.substring(strEmail.indexOf('@'),strEmail.length());
                       String strActString = strSubEmail.substring(1,strSubEmail.indexOf('.'));
                       System.debug('Final String:========> '+ strActString);
                       allconnew.domain__c=strActString;
                       System.debug('transfered=========>'+allconnew.domain__c);
                   }
               }
          }
    }
     
  }


Example2:-

 We take another scnario , In contact there is a lookup field called spouse on to contact.(self lookup).
When we click on look-up field in child record, the parent record spouse field should be child record name.

Here if a contact record name='Daniel'.
And spouse in the record of daniel is 'Mary'.
if i click mary lookup feild the daniel should be the spouse in the mary record.
it means the lookup value should change vice versa.


trigger MatchSpouse on Contact (after insert, before update) {
    List<Contact> spouses = new List<Contact>();
    Contact spouse;
    for (Contact c : Trigger.new){
        if (c.Spouse__c != null){
            spouse = [select id,Spouse__c from Contact where Id=: c.Spouse__c ];
            if(spouse.Spouse__c != c.id){
                spouse.Spouse__c = c.id;
                spouses.add(spouse);
            }
        }
    }
    if(spouses.size()>0 && staticFlag.a ){
        staticFlag.a = false;
        update spouses;
    }
}