2011年9月26日 星期一

JDeveloper: ADF: Custom Converter

1. Create Converter: 

package com.pyramid.misc;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class PhoneConverter implements Converter  {
    public PhoneConverter() {
     
    }

    public Object getAsObject(FacesContext facesContext,
                              UIComponent uiComponent, String value) {
      if (value == null || (value.trim().length() == 0))
              {
                  return value;
              }
   
      // format phone numbers to display correctly
   
        String phone = value.trim();
        if (phone.length() == 10) {
            phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10);
        }
        else if (phone.matches("\\d{10}\\s*\\d+")) {
            phone = phone.replaceAll("\\s+", "");
            phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10) + " x" + phone.substring(10);
        }
 
      return phone;
    }

    public String getAsString(FacesContext facesContext,
                              UIComponent uiComponent, Object value) {
        String phoneNumber = (String)value;
         if (phoneNumber == null || (phoneNumber.trim().length() == 0))
          {
              return "";
          }
          String phone = phoneNumber.trim();


          if (phone.length() == 10) {
              phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10);
          }
          else if (phone.matches("\\d{10}\\s*\\d+")) {
              phone = phone.replaceAll("\\s+", "");
              phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10) + " x" + phone.substring(10);
          }
       
        return phone;
    }
}

2. Register on faces-config.xml file (or faces configuration file)
<faces-config
...

     <converter>
    <description>A Converter for phone number</description>
    <converter-id>PhoneConverter</converter-id>
    <converter-class>
        com.pyramid.misc.PhoneConverter
   
</converter>

...
</faces-config>

3. Use in field:


 <af:outputText value="#{row.Phone}" id="ot3">
                       <f:converter converterId="PhoneConverter"/>
                   </af:outputText>
                 

1 則留言: