> Markdown version of [Custom Field](https://vaadin.com/docs/v14/ds/components/custom-field). Section index: [llms.txt](https://vaadin.com/docs/v14/ds/llms.txt)

# Custom Field

Custom Field is a component for wrapping multiple components as a single field. It has the same features as [Input Fields](https://vaadin.com/docs/v14/ds/components/input-fields.md), such as its own label, helper, validation, and data binding. Use it to create custom input components.

`DateRangePicker.java`

```java
public class DateRangePicker extends CustomField<LocalDateRange> {

  private DatePicker start;
  private DatePicker end;

  public DateRangePicker(String label) {
    this();
    setLabel(label);
  }

  public DateRangePicker() {
    start = new DatePicker();
    start.setPlaceholder("Start date");

    end = new DatePicker();
    end.setPlaceholder("End date");

    // aria-label for screen readers
    start.getElement()
      .executeJs("const start = this.shadowRoot.querySelector('[part=\"text-field\"]').shadowRoot.querySelector('[part=\"value\"]');" +
        "start.setAttribute('aria-label', 'Start date');" +
        "start.removeAttribute('aria-labelledby');"
      );
    end.getElement()
      .executeJs("const end = this.shadowRoot.querySelector('[part=\"text-field\"]').shadowRoot.querySelector('[part=\"value\"]');" +
        "end.setAttribute('aria-label', 'End date');" +
        "end.removeAttribute('aria-labelledby');"
      );

    add(start, new Text(" – "), end);
  }

  @Override
  protected LocalDateRange generateModelValue() {
    return new LocalDateRange(start.getValue(), end.getValue());
  }

  @Override
  protected void setPresentationValue(LocalDateRange dateRange) {
    start.setValue(dateRange.getStartDate());
    end.setValue(dateRange.getEndDate());
  }
}
```

`CustomFieldBasic.java`

```java
DateRangePicker dateRangePicker = new DateRangePicker();
dateRangePicker.setLabel("Enrollment period");
dateRangePicker.setHelperText("Cannot be longer than 30 days");
add(dateRangePicker);

Binder<Appointment> binder = new Binder();
binder.forField(dateRangePicker)
  .asRequired("Enter a start and end date")
  .withValidator(localDateRange ->
    localDateRange.getStartDate() == null ||
    localDateRange.getEndDate() == null ||
    ChronoUnit.DAYS.between(localDateRange.getStartDate(), localDateRange.getEndDate()) <= 30,
    "Dates cannot be more than 30 days apart"
  )
  .withValidator(localDateRange ->
    localDateRange.getStartDate() == null ||
    localDateRange.getEndDate() == null ||
    localDateRange.getStartDate().isBefore(localDateRange.getEndDate()),
    "Start date must be earlier than end date"
  )
  .bind(
    appointment ->
      new LocalDateRange(appointment.getStartDate(), appointment.getEndDate()),
    (appointment, localDateRange) -> {
      appointment.setStartDate(localDateRange.getStartDate());
      appointment.setEndDate(localDateRange.getEndDate());
    }
  );
```

`LocalDateRange.java`

```java
public class LocalDateRange {

  private LocalDate startDate;
  private LocalDate endDate;

  public LocalDateRange(LocalDate startDate, LocalDate endDate) {
    this.startDate = startDate;
    this.endDate = endDate;
  }

  public LocalDate getStartDate() {
    return startDate;
  }

  public void setStartDate(LocalDate startDate) {
    this.startDate = startDate;
  }

  public LocalDate getEndDate() {
    return endDate;
  }

  public void setEndDate(LocalDate endDate) {
    this.endDate = endDate;
  }
}
```

`Appointment.java`

```java
public class Appointment {

  private LocalTime startTime;

  private LocalDateTime startDateTime;

  private LocalDate startDate;

  private LocalTime endTime;

  private LocalDateTime endDateTime;

  private LocalDate endDate;

  private String enrollmentPeriod;

  private Integer id;

  public LocalTime getStartTime() {
    return startTime;
  }

  public void setStartTime(LocalTime startTime) {
    this.startTime = startTime;
  }

  public LocalDateTime getStartDateTime() {
    return startDateTime;
  }

  public void setStartDateTime(LocalDateTime startDateTime) {
    this.startDateTime = startDateTime;
  }

  public LocalDate getStartDate() {
    return startDate;
  }

  public void setStartDate(LocalDate startDate) {
    this.startDate = startDate;
  }

  public LocalTime getEndTime() {
    return endTime;
  }

  public void setEndTime(LocalTime endTime) {
    this.endTime = endTime;
  }

  public LocalDateTime getEndDateTime() {
    return endDateTime;
  }

  public void setEndDateTime(LocalDateTime endDateTime) {
    this.endDateTime = endDateTime;
  }

  public LocalDate getEndDate() {
    return endDate;
  }

  public void setEndDate(LocalDate endDate) {
    this.endDate = endDate;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  @Override
  public int hashCode() {
    return id;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof Appointment)) {
      return false;
    }
    Appointment other = (Appointment) obj;
    return id == other.id;
  }

  public String getEnrollmentPeriod() {
    return enrollmentPeriod;
  }

  public void setEnrollmentPeriod(String enrollmentPeriod) {
    this.enrollmentPeriod = enrollmentPeriod;
  }
}
```

## <a id="basic-usage"></a>Basic Usage

Custom Field is optimised for wrapping the following components:

- [Text Field](https://vaadin.com/docs/v14/ds/components/text-field.md)

- [Number Filed](https://vaadin.com/docs/v14/ds/components/number-field.md)

- [Password Field](https://vaadin.com/docs/v14/ds/components/password-field.md)

- [Text Area](https://vaadin.com/docs/v14/ds/components/text-area.md)

- [Select](https://vaadin.com/docs/v14/ds/components/select.md)

- [Combo Box](https://vaadin.com/docs/v14/ds/components/combo-box.md)

- [Date Picker](https://vaadin.com/docs/v14/ds/components/date-picker.md)

- [Time Picker](https://vaadin.com/docs/v14/ds/components/time-picker.md)

It can also be used to provide a label, helper, and the other field features, for components that don’t have them built-in, such as [List Box](https://vaadin.com/docs/v14/ds/components/list-box.md).

## <a id="native-input-fields"></a>Native Input Fields

Custom Field works with native HTML elements.

`PaymentInformationField.java`

```java
public class PaymentInformationField extends CustomField<PaymentInformation> {

  private Input cardholderName;
  private Input cardNumber;
  private Input securityCode;

  public PaymentInformationField(String label) {
    this();
    setLabel(label);
  }

  public PaymentInformationField() {
    cardholderName = createInput("Cardholder name", "[\\p{L} \\-]+");
    cardNumber = createInput("Card number", "[\\d ]{12,23}");
    securityCode = createInput("Security code", "[0-9]{3,4}");

    HorizontalLayout layout = new HorizontalLayout(cardholderName, cardNumber, securityCode);
    // Removes default spacing
    layout.setSpacing(false);
    // Adds small amount of space between the components
    layout.getThemeList().add("spacing-s");

    add(layout);
  }

  private Input createInput(String label, String pattern) {
    Input input = new Input();
    input.getElement().setAttribute("aria-label", label);
    input.getElement().setAttribute("pattern", pattern);
    input.getElement().setAttribute("required", true);
    input.setPlaceholder(label);
    input.setType("text");
    return input;
  }

  @Override
  protected PaymentInformation generateModelValue() {
    return new PaymentInformation(
      cardholderName.getValue(),
      cardNumber.getValue(),
      securityCode.getValue()
    );
  }

  @Override
  protected void setPresentationValue(PaymentInformation paymentInformation) {
    cardholderName.setValue(paymentInformation.getCardholderName());
    cardNumber.setValue(paymentInformation.getCardNumber());
    securityCode.setValue(paymentInformation.getSecurityCode());
  }
}
```

`CustomFieldNativeInput.java`

```java
PaymentInformationField paymentInformationField = new PaymentInformationField("Payment information");
paymentInformationField.addValueChangeListener(event -> {
  value.setText(
    event.getValue().getCardholderName() + " " +
    event.getValue().getCardNumber() + " " +
    event.getValue().getSecurityCode()
  );
});

value = new Span();
Paragraph paragraph = new Paragraph(
  new Html("<span><b>Payment information:</b> </span>"),
  value
);

add(paymentInformationField, paragraph);
```

`PaymentInformation.java`

```java
public class PaymentInformation {

  private String cardholderName;
  private String cardNumber;
  private String securityCode;

  public PaymentInformation(String cardholderName, String cardNumber, String securityCode) {
    this.cardholderName = cardholderName;
    this.cardNumber = cardNumber;
    this.securityCode = securityCode;
  }

  public String getCardholderName() {
    return cardholderName;
  }

  public void setCardholderName(String cardholderName) {
    this.cardholderName = cardholderName;
  }

  public String getCardNumber() {
    return cardNumber;
  }

  public void setCardNumber(String cardNumber) {
    this.cardNumber = cardNumber;
  }

  public String getSecurityCode() {
    return securityCode;
  }

  public void setSecurityCode(String securityCode) {
    this.securityCode = securityCode;
  }
}
```

## <a id="supported-features"></a>Supported Features

- [Label](https://vaadin.com/docs/v14/ds/components/input-fields.md#label)

- [Helper](https://vaadin.com/docs/v14/ds/components/input-fields.md#helper)

- [Required](https://vaadin.com/docs/v14/ds/components/input-fields.md#required)

## <a id="required-field-indicator-visibility"></a>Required Field Indicator Visibility

The visibility of the required field indicator is controlled by the `has-value` attribute on the Custom Field component. In Flow (Java), a class extending `CustomField` should take care of toggling the `has-value` attribute based on what values are considered empty.

## <a id="size-variants"></a>Size Variants

The small theme variant can be used to make Custom Field’s label, helper, and error message smaller. Custom Field does not propagate its theme variant to its internal components, meaning each internal component’s theme variant must be set individually.

`MoneyField.java`

```java
public class MoneyField extends CustomField<Money> {

  private TextField amount;
  private Select<String> currency;

  public MoneyField(String label) {
    this();
    setLabel(label);
  }

  public MoneyField() {
    amount = new TextField();

    currency = new Select();
    currency.setItems("AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "USD");
    currency.setWidth("6em");

    // aria-label for screen readers
    amount.getElement()
      .executeJs("const amount = this.shadowRoot.querySelector('[part=\"value\"]');" +
        "amount.setAttribute('aria-label', 'Amount');" +
        "amount.removeAttribute('aria-labelledby');");
    currency.getElement()
      .executeJs("const currency = this.shadowRoot.querySelector('vaadin-select-text-field').shadowRoot.querySelector('[part=\"input-field\"]');" +
        "currency.setAttribute('aria-label', 'Currency');" +
        "currency.removeAttribute('aria-labelledby');");

    HorizontalLayout layout = new HorizontalLayout(amount, currency);
    // Removes default spacing
    layout.setSpacing(false);
    // Adds small amount of space between the components
    layout.getThemeList().add("spacing-s");

    add(layout);
  }

  public void addThemeVariant(String theme) {
    getElement().getThemeList().add(theme);
    amount.addThemeName(theme);
    currency.getElement().getThemeList().add(theme);
  }

  @Override
  protected Money generateModelValue() {
    return new Money(amount.getValue(), currency.getValue());
  }

  @Override
  protected void setPresentationValue(Money money) {
    amount.setValue(money.getAmount());
    currency.setValue(money.getCurrency());
  }
}
```

`CustomFieldSizeVariants.java`

```java
MoneyField moneyField = new MoneyField("Price");
moneyField.addThemeVariant("small");
```

`Money.java`

```java
public class Money {

  private String amount;
  private String currency;

  public Money(String amount, String currency) {
    this.amount = amount;
    this.currency = currency;
  }

  public String getAmount() {
    return amount;
  }

  public void setAmount(String amount) {
    this.amount = amount;
  }

  public String getCurrency() {
    return currency;
  }

  public void setCurrency(String currency) {
    this.currency = currency;
  }
}
```

`CDC76788-C339-411B-89BF-510C3603EF59`
