> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/powershell-universal/es/aplicaciones/components/inputs/form.md).

# Formulario

{% embed url="<https://youtu.be/o8Bl1NsCc2Y>" %}

Los formularios proporcionan una forma de recopilar datos de los usuarios.

Los formularios pueden incluir cualquier tipo de control que desee. Esto le permite personalizar el aspecto y utilizar cualquier control de entrada.

Los datos introducidos mediante los controles de entrada se enviarán de vuelta al bloque de script `OnSubmit` cuando se envíe el formulario. Dentro del controlador de eventos `OnSubmit`, tendrá acceso a la variable `$EventData`, que contendrá propiedades para cada uno de los campos del formulario.

Por ejemplo, si tiene dos campos, tendrá dos propiedades en `$EventData`.

```powershell
New-UDForm -Content {
    New-UDTextbox -Id 'txtTextField'
    New-UDCheckbox -Id 'chkCheckbox'
} -OnSubmit {
    Show-UDToast -Message $EventData.txtTextField
    Show-UDToast -Message $EventData.chkCheckbox
}
```

## Controles compatibles

Los siguientes controles de entrada se integran automáticamente con un formulario. Los valores establecidos en estos controles se enviarán durante la validación y en el controlador de eventos `OnSubmit`.

* [Autocomplete](/powershell-universal/es/aplicaciones/components/inputs/automcomplete.md)
* [Checkbox](/powershell-universal/es/aplicaciones/components/inputs/checkbox.md)
* [Date Picker](/powershell-universal/es/aplicaciones/components/inputs/date-picker.md)
* [Radio](/powershell-universal/es/aplicaciones/components/inputs/radio.md)
* [Select](/powershell-universal/es/aplicaciones/components/inputs/select.md)
* [Slider](/powershell-universal/es/aplicaciones/components/inputs/slider.md)
* [Switch](/powershell-universal/es/aplicaciones/components/inputs/switch.md)
* [Textbox](/powershell-universal/es/aplicaciones/components/inputs/textbox.md)
* [Time Picker](/powershell-universal/es/aplicaciones/components/inputs/time-picker.md)
* [Transfer List](/powershell-universal/es/aplicaciones/components/inputs/transfer-list.md)
* [Upload](/powershell-universal/es/aplicaciones/components/inputs/upload.md)

## Formulario simple

![](/files/eWFPBD0uwJIkTMXanEBd)

Los formularios simples pueden usar entradas como cuadros de texto y casillas de verificación.

```powershell
New-UDForm -Content {
    New-UDTextbox -Id 'txtTextfield'
    New-UDCheckbox -Id 'chkCheckbox'
} -OnSubmit {
    Show-UDToast -Message $EventData.txtTextfield
    Show-UDToast -Message $EventData.chkCheckbox
}
```

## Dar formato a un formulario

![](/files/Wwb71Pw3K4gAoiMSLWlp)

Dado que los formularios pueden utilizar cualquier componente, puede usar componentes de formato estándar dentro del formulario.

```powershell
New-UDForm -Content {

    New-UDRow -Columns {
        New-UDColumn -SmallSize 6 -LargeSize 6 -Content {
            New-UDTextbox -Id 'txtFirstName' -Label 'First Name' 
        }
        New-UDColumn -SmallSize 6 -LargeSize 6 -Content {
            New-UDTextbox -Id 'txtLastName' -Label 'Last Name'
        }
    }

    New-UDTextbox -Id 'txtAddress' -Label 'Address'

    New-UDRow -Columns {
        New-UDColumn -SmallSize 6 -LargeSize 6  -Content {
            New-UDTextbox -Id 'txtState' -Label 'State'
        }
        New-UDColumn -SmallSize 6 -LargeSize 6  -Content {
            New-UDTextbox -Id 'txtZipCode' -Label 'ZIP Code'
        }
    }

} -OnSubmit {
    Show-UDToast -Message $EventData.txtFirstName
    Show-UDToast -Message $EventData.txtLastName
}
```

## Devolver componentes

Cuando se envía un formulario, puede devolver opcionalmente otro componente para reemplazar el formulario en la página. Puede devolver cualquier componente de Universal Dashboard. Todo lo que necesita hacer es asegurarse de que el componente se escriba en la canalización dentro del controlador de eventos `OnSubmit`.

```powershell
New-UDForm -Content {
    New-UDTextbox -Id 'txtTextfield'
} -OnSubmit {
    New-UDTypography -Text $EventData.txtTextfield
}
```

## Validar un formulario

La validación de formularios se puede lograr utilizando el parámetro de bloque de script OnValidate.

```powershell
New-UDForm -Content {
    New-UDTextbox -Id 'txtValidateForm'
} -OnValidate {
    $FormContent = $EventData

    if ($FormContent.txtValidateForm -eq $null -or $FormContent.txtValidateForm -eq '') {
        New-UDFormValidationResult -ValidationError "txtValidateForm is required"
    } else {
        New-UDFormValidationResult -Valid
    }
} -OnSubmit {
    Show-UDToast -Message $Body
}
```

## Cancelar un formulario

Puede definir un controlador de eventos `-OnCancel` para invocarlo cuando se pulse el botón de cancelar. Esto puede utilizarse para realizar acciones como cerrar un modal.

```powershell
New-UDButton -Text 'On Form' -OnClick {
    Show-UDModal -Content {
        New-UDForm -Content {
            New-UDTextbox -Label 'Hello'
        } -OnSubmit {
            Show-UDToast -Message 'Submitted!'
            Hide-UDModal
        } -OnCancel {
            Hide-UDModal
        }
    }
}
```

## Mostrar la salida sin reemplazar el formulario

Aunque puede devolver componentes directamente desde un formulario, es posible que desee conservar el formulario para que los usuarios puedan introducir datos de nuevo. Para ello, puede usar `Set-UDElement` y un elemento de marcador de posición al que pueda establecer el contenido.

En este ejemplo, tenemos un formulario vacío que, al enviarse, actualizará el elemento `results` con un UDCard.

```powershell
New-UDForm -Content {

} -OnSubmit {
   Set-UDElement -Id 'results' -Content {
      New-UDCard -Content { "Hello " + (Get-Date) }
   }
}

New-UDElement -Id 'results' -Tag 'div'
```

## Formularios de esquema

En lugar de definir todo el diseño y la lógica de los formularios mediante cmdlets, también puede definir un formulario basado en una tabla hash de esquema. Esta versión de formularios se basa en [react-jsonschema-form](https://rjsf-team.github.io/react-jsonschema-form/docs/).

### Campos

Puede definir campos que acepten tipos string, number, integer, enum y boolean. Esto cambia el tipo de entrada que se muestra.

```powershell
New-UDForm -Schema @{
   title = "Test Form"
   type = "object"
   properties = @{
       name = @{
           type = "string"
       }
       age = @{
           type = "number"
       }
   }
} -OnSubmit {
   # $EventData.name
   # $EventData.age
}
```

### Propiedades obligatorias

Puede usar la propiedad `required` para establecer una lista de propiedades obligatorias.

```powershell
New-UDForm -Schema @{
   title = "Test Form"
   type = "object"
   properties = @{
       name = @{
           type = "string"
       }
       age = @{
           type = "number"
       }
   }
   required = @('name')
} -OnSubmit {
   # $EventData.name
   # $EventData.age
}
```

{% hint style="warning" %}
Tenga en cuenta que las propiedades deben estar en minúsculas. Por ejemplo, debe asegurarse de que las claves de su tabla hash de propiedades estén en minúsculas y que la lista de propiedades obligatorias también esté en minúsculas.
{% endhint %}

### Ordenación

Puede usar la propiedad `schemaUI` para modificar la ordenación de los campos.

```powershell
New-UDForm -Schema @{
        title = "Test"
        type = "object"
        properties = @{
            hostname = @{
                title = "Hostname"
                type = "string"
                }
            ipaddress= @{
                title = "IP Address"
                type = "string"
                format = "ipv4"
                }
            description = @{
                title = "Server Description"
                type = "string"
                }
            servertype = @{
                title = "Server Type"
                type = "string"                            
                enum = "App","DB"
                }
            environment = @{
                title = "Environment"
                type = "string"
                enum = "Prod", "Dev" , "QA"
                }
            }
		required = @('hostname','ipaddress','description','servertype','environment')                    
	} -uiSchema @{
		"ui:order" = @('environment','hostname','ipaddress','description')
	} -OnSubmit {
		Show-UDModal -Content {                        
			New-UDTypography -Text $EventData
		} -Footer {
			New-UDButton -Text "Close" -OnClick {Hide-UDModal}
		} -Persistent
	}
```

### Matrices

Puede crear formularios que acepten de 0 a muchos objetos. El usuario podrá añadir y eliminar objetos del formulario.

```powershell
New-UDForm -Schema @{
   title = "Test Form"
   type = "array"
   items = @{
      type = "object" 
       properties = @{
           name = @{
               type = "string"
           }
           age = @{
               type = "number"
           }
       }
   }
} -OnSubmit {
   # $EventData[0].name
   # $EventData[0].age
}
```

## Formularios de script

Puede generar formularios automáticamente basados en scripts de su entorno de PowerShell Universal. Los formularios de script generarán componentes de entrada basados en el bloque `param`. Los formularios de script admiten automáticamente el progreso y la retroalimentación.

Los formularios de script también admiten mostrar la salida como texto o como tabla.

```powershell
New-UDForm -Script "Script.ps1" -OutputType 'text'
```

## API

* [New-UDForm](/powershell-universal/es/comandos-de-powershell/new-udform.md)
* [New-UDFormValidationResult](/powershell-universal/es/comandos-de-powershell/new-udvalidationresult.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.devolutions.net/powershell-universal/es/aplicaciones/components/inputs/form.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
