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

# Custom Field

Custom Field è un componente per racchiudere più componenti come un singolo campo. Fornisce funzionalità standard dei campi di input come etichetta, helper, validazione, e data binding. Lo usi per creare componenti di input personalizzati.

**Lit** — `custom-field-basic.ts`

```html
<vaadin-custom-field
  label="Enrollment period"
  helper-text="Cannot be longer than 30 days"
  required
  ${field(this.binder.model.enrollmentPeriod)}
>
  <vaadin-date-picker
    accessible-name="Start date"
    placeholder="Start date"
  ></vaadin-date-picker>
  &ndash;
  <vaadin-date-picker accessible-name="End date" placeholder="End date"></vaadin-date-picker>
</vaadin-custom-field>
```

**Flow** — `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");
        // Sets title for screen readers
        start.setAriaLabel("Start date");

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

        // Enable manual validation on both date pickers to
        // be able to override their invalid state
        start.setManualValidation(true);
        end.setManualValidation(true);

        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());
    }

    @Override
    public void setInvalid(boolean invalid) {
        super.setInvalid(invalid);
        // Propagate invalid state to both date pickers so
        // that they show a red background
        start.setInvalid(invalid);
        end.setInvalid(invalid);
    }
}
```

**Flow** — `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());
                });
```

**Flow** — `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;
    }
}
```

**Flow** — `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;
    }
}
```

**React** — `custom-field-basic.tsx`

```tsx
<CustomField
  label="Enrollment period"
  helperText="Cannot be longer than 30 days"
  required
  {...field(model.enrollmentPeriod)}
>
  <DatePicker accessibleName="Start date" placeholder="Start date" />
  &ndash;
  <DatePicker accessibleName="End date" placeholder="End date" />
</CustomField>
```

## <a id="utilizzo-di-base"></a>Utilizzo di Base

Custom Field è ottimizzato per racchiudere i seguenti componenti:

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

- [Number Field](https://vaadin.com/docs/latest/it/components/number-field.md)

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

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

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

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

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

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

Può anche essere usato per fornire un’etichetta, un helper, e altre funzionalità di campo a componenti che non le hanno integrate, come [List Box](https://vaadin.com/docs/latest/it/components/list-box.md).

## <a id="tipo-formato-del-valore"></a>Tipo & Formato del Valore

Il tipo, il formato, e l’ulteriore propagazione del valore di Custom Field sono gestiti in modo diverso in Java, e in Lit e React. Le due sezioni seguenti spiegano come potrebbe configurare questi aspetti a seconda del linguaggio di programmazione o dell’approccio che preferisce.

### <a id="java"></a>Java

Custom Field è una classe generica che accetta un tipo di valore. Il tipo di valore può essere qualsiasi cosa: String, List, un bean, o qualcos’altro.

Quando il tipo è specificato, deve stabilire come il valore di Custom Field dovrebbe propagarsi ai componenti figli e viceversa. La propagazione del valore dipende fortemente dalla struttura di Custom Field, dai componenti contenuti, e dai loro tipi. Per questo motivo, non viene fornita alcuna implementazione predefinita. Invece, Custom Field fornisce due metodi che dovrebbero essere implementati manualmente: `generateModelValue`; e `setPresentationValue`.

Il metodo `generateModelValue` definisce come generare un valore di Custom Field dai valori dei componenti figli. Custom Field attiva questo metodo per aggiornare il proprio valore quando un componente figlio emette un evento DOM di modifica sul lato client. In questo metodo, tipicamente deve raccogliere i valori da tutti i componenti figli e restituire un singolo valore del tipo di Custom Field basato su tali valori.

Il metodo `setPresentationValue` riceve un valore di Custom Field e definisce come distribuirlo ai componenti figli. Custom Field attiva questo metodo per aggiornare i valori dei componenti figli quando il suo valore cambia programmaticamente sul lato server. In questo metodo, tipicamente deve suddividere il valore dato in parti e applicarle rispettivamente a ciascun componente figlio individuale.

L’esempio seguente mostra come impostare la propagazione del valore, usando un bean come tipo di valore:

`Phone.java`

```java
Unresolved directive in <stdin> - include::../../../src/main/java/com/vaadin/demo/component/customfield/Phone.java[tags=snippet, indent=0]
```

`PhoneField.java`

```java
Unresolved directive in <stdin> - include::../../../src/main/java/com/vaadin/demo/component/customfield/PhoneField.java[tags=snippet, indent=0]
```

### <a id="lit-react"></a>Lit & React

Custom Field supporta solo valori stringa. Tuttavia, fornisce controllo sul formato del valore con un parser e un formatter. Il parser e il formatter definiscono come il valore di Custom Field dovrebbe essere suddiviso nei valori dei componenti figli e viceversa. Quando un componente figlio emette un evento di modifica o il valore di Custom Field cambia programmaticamente, Custom Field propaga i valori in base al risultato del parser o del formatter.

#### <a id="parser"></a>Parser

Quando il valore di Custom Field cambia programmaticamente, Custom Field passa questo valore al parser. Il parser dovrebbe convertire questo valore in un array di valori figli, disposti nell’ordine in cui i loro componenti appaiono nel DOM. Custom Field assegna quindi questi valori ai componenti figli usando la loro proprietà value.

Il parser predefinito restituisce un array di valori dei componenti figli, suddividendo il valore tramite il carattere `\t`.

#### <a id="formatter"></a>Formatter

Quando Custom Field rileva un evento di modifica da un componente figlio, raccoglie le proprietà value da tutti i componenti figli e le passa come un array al formatter. L’array contiene i valori figli nell’ordine in cui i loro componenti appaiono nel DOM. Il formatter dovrebbe trasformare questo array in un singolo valore stringa. Custom Field aggiorna quindi il proprio valore in base alla stringa restituita dal formatter.

Il formatter predefinito restituisce una concatenazione dei valori dei componenti figli, separati dal carattere `\t`.

Può personalizzare il formato del valore definendo il Suo formatter e parser dei valori, come mostrato nell’esempio seguente:

**Lit**

```ts
render() {
  return html`
    <!-- Phone Custom Field -->
    <vaadin-custom-field
      .formatValue="${([code, number]: unknown[]) => {
        return code && number ? [code, number].join('|') : '';
      }}"
      .parseValue="${(value: string) => {
        return value ? value.split('|') : ['', ''];
      }}"
    >
      <!-- Country code -->
      <vaadin-select></vaadin-select>

      <!-- Phone number -->
      <vaadin-text-field></vaadin-text-field>
    </vaadin-custom-field>
  `
}
```

**React**

```tsx
function Example() {
  return (
    // Phone Custom Field
    <CustomField
      formatValue={([code, number]: unknown[]) => (code && number ? [code, number].join('|') : '')}
      parseValue={(value: string) => (value ? value.split('|') : ['', ''])}
    >
      {/* Country code */}
      <Select />

      {/* Phone number */}
      <TextField />
    </CustomField>
  );
}
```

## <a id="campi-di-input-nativi"></a>Campi di Input Nativi

Custom Field funziona con elementi HTML nativi.

**Lit** — `custom-field-native-input.ts`

```html
<vaadin-custom-field
  label="Payment information"
  @change="${(event: CustomFieldChangeEvent) => {
    this.customFieldValue = event.target.value ?? '';
  }}"
>
  <vaadin-horizontal-layout style="gap: 0.5rem; padding-top: 0.25rem;">
    <input
      aria-label="Cardholder name"
      pattern="[\\p{L} \\-]+"
      placeholder="Cardholder name"
      required
      type="text"
    />
    <input
      aria-label="Card number"
      pattern="[\\d ]{12,23}"
      placeholder="Card number"
      required
      type="text"
    />
    <input
      aria-label="Security code"
      pattern="[0-9]{3,4}"
      placeholder="Security code"
      required
      type="text"
    />
  </vaadin-horizontal-layout>
</vaadin-custom-field>
<p><b>Payment information:</b> ${this.customFieldValue}</p>
```

**Flow** — `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);
        layout.setSpacing(false);
        layout.getStyle().set("gap", "0.5rem");
        layout.getStyle().set("padding-top", "0.25rem");

        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());
    }
}
```

**Flow** — `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);
```

**Flow** — `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;
    }
}
```

**React** — `custom-field-native-input.tsx`

```tsx
<CustomField
  label="Payment information"
  onValueChanged={(event) => {
    customFieldValue.value = event.detail.value ?? '';
  }}
>
  <HorizontalLayout style={{ gap: '0.5rem', paddingTop: '0.25rem' }}>
    <input
      aria-label="Cardholder name"
      pattern="[\p{L} \-]+"
      placeholder="Cardholder name"
      required
      type="text"
    />
    <input
      aria-label="Card number"
      pattern="[\d ]{12,23}"
      placeholder="Card number"
      required
      type="text"
    />
    <input
      aria-label="Security code"
      pattern="[0-9]{3,4}"
      placeholder="Security code"
      required
      type="text"
    />
  </HorizontalLayout>
</CustomField>
<p>
  <b>Payment information:</b> {customFieldValue}
</p>
```

`CB7FDF39-7653-4DF0-A0C0-9C2A2EE7EDBA`
