[SalesForce] Use a custom datepicker to get the value of date of birth in contact

The standard datepicker for "Date of Birth" field in Contact has a limited range of years available.It is unsuitable for capturing a contact's date of birth. I have used apex:input but how can I save the value provided by the user in the Date of Birth field in Contact?

Visualforce page:

<apex:page standardController="Contact" docType="html-5.0" extensions="DatePicker">
 <apex:pageMessages />
  <apex:sectionHeader title="Custom Date Picker" subtitle="Create Contact" />
  <apex:form id="frm">  
    <apex:pageblock title="Opportunity" id="pb">
      <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!save}" />
        <apex:commandButton value="Cancel" action="{!Cancel}" />
      </apex:pageBlockButtons>
      <apex:pageBlockSection id="pbs">
        <apex:inputField value="{!Contact.Salutation}" />
        <apex:inputField value="{!Contact.FirstName}" />
        <apex:inputField value="{!Contact.LastName}" />
         <apex:pageBlockSectionItem >
         <apex:outputLabel value="Date of Birth" for="birthdate" />
         <apex:input type="date" value="{!dat}"/>
         </apex:pageBlockSectionItem>



        </apex:pageBlockSection>
        </apex:pageBlock>
        </apex:form>


</apex:page>

Apex Class:

public class DatePicker 
{

    public DatePicker(ApexPages.StandardController controller) {

    }

    public String datename {get; set;}
     public Date dat {get;set;}
    public DatePicker() {

    }
}

I have checked https://developer.salesforce.com/forums?id=906F00000008kzBIAQ but this doesn't seem to work.

Best Answer

Here is code taking the same approach as your link of modifying the date pickers that Visualforce generates. This will only work if Salesforce continue to leave the specific HTML they generate unchanged in this area.

Working example page:

<apex:page standardController="Contact">
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection>
                <apex:inputField value="{!Contact.Birthdate}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"/>
<script>
(function($) {
    function addYearsToDatePickers() {
        var currentYear = $('select#calYearPicker > option:first-child').val();
        for (var year = currentYear - 1; year > 1900; year--) {
            $('<option value="' + year + '">' + year + '</option>').prependTo('select#calYearPicker');
        }
     }
     $(document).ready(addYearsToDatePickers);
})(jQuery.noConflict());
</script>

</apex:page>

When adding JavaScript, always check in your browser's JavaScript console for errors.

Related Topic