D8 Formularios Elementos - pierregermain/MyDrupal GitHub Wiki

Páginas relacionadas:

Índice:

Propiedades

Documentación oficial:

Características:

  • Las propiedades empiezan por #

Propiedades comunes

#type

Toma los valores textfield, select, email, submit, etc.

#title, #title_display

'#title_display' => 'before',
'#title_display' => 'after',
'#title_display' => 'invisible', // ocultar title por css
'#title_display' => 'attribute', // hover para radios y checkboxes

#description

#default_value

#disabled

'#disabled' => TRUE,
'#disabled' => FALSE,

#required

#access

Cuando es FALSE el elemento no se renderiza y se ignora totalmente a la hora de hacer el validate y el submit

#field_prefix, #field_suffix, #prefix, #suffix

El contenido de #prefix y #suffix es más exterior

$form['user_email'] = [
  '#type' => 'email',
  '#title' => $this->t('User email'),
  '#description' => $this->t('Your email.'),
  '#field_prefix' => '<div class="field_prefix">',
  '#field_suffix' => '</div>',
  '#prefix' => '<div class="prefix">',
  '#suffix' => '</div>',
];

#attributes

$form['user_email'] = [
  // ...
  '#attributes' => ['class' => ['highlighted', 'pierre']],
];

genera:

<input class="highlighted pierre ...>

#id

Genera un id manual del elemento. Sólo se usa si el generado no nos convence

#markup

Permite mostrar html en un #type de tipo 'item'

$form['comment'] = [
  '#type' => 'item',
  '#markup' => $this->t('Item element <strong>to add HTML</strong> into a Form.'),
];

Cuando un elemento no lleva #type se considera del tipo 'item'

$form['comment'] = [
'#markup' => $this->t('Item element <strong>to add HTML</strong> into a Form.'),
];

#plain_text

Es similar a #markup, pero todo el texto se convierte a texto plano. Cuando se definen las dos propiedades, sólo se mostrará el texto de #plain_text.

#weight

Elementos de agrupación

  • Agrupar elementos con un rectángulo
  • solo puede ser utilizado en formularios
$form['personal_data'] = [
  '#type' => 'fieldset',
  '#title' => $this->t('Personal Data'),
];
$form['personal_data']['first_name'] = [
  '#type' => 'textfield',
  //...
];
$form['personal_data']['last_name'] = [
  '#type' => 'textfield',
  //...
];
  • Parecido al fieldset pero plegable
  • Utiliza la etiqueta
    de HTML5.
  • Mediante la propiedad #open podemos indicar si el grupo estará abierto (TRUE) o cerrado (FALSE) por defecto.
$form['personal_data'] = [
  '#type' => 'details',
  '#title' => $this->t('Personal Data'),
  '#description' => $this->t('Lorem ipsum '),
  '#open' => TRUE,
];
$form['personal_data']['first_name'] = [
  '#type' => 'textfield',
  //...
];
$form['personal_data']['last_name'] = [
  '#type' => 'textfield',
  //...
];

container

  • Sirve para agrupar elementos en un
    $form['personal_data'] = [
      '#type' => 'container',
      '#title' => $this->t('Personal Data'),
    ];
    $form['personal_data']['first_name'] = [
      '#type' => 'textfield',
      //...
    ];
    $form['personal_data']['last_name'] = [
      '#type' => 'textfield',
      //...
    ];
    

    fieldgroup

    Igual que fieldset. Es mejor usar fieldset.

    vertical_tabs

    // Definición del contenedor de Tabs Verticales
    $form['information'] = array(
      '#type' => 'vertical_tabs',
    );
    // Definimos los elementos de cada Tab usando #group
    $form['personal_data'] = [
      '#type' => 'details',
      '#title' => $this->t('Personal Data'),
      '#description' => $this->t('Lorem ipsum. '),
      '#group' => 'information',
    ];
    // A cada grupo añadimos elementos cómo siempre
    $form['personal_data']['first_name'] = [
      '#type' => 'textfield',
      //...
    ];
    $form['personal_data']['last_name'] = [
      '#type' => 'textfield',
      //...
    ];
    // Definimos los elementos de cada Tab usando #group
    $form['access_data'] = [
      '#type' => 'details',
      '#title' => $this->t('Access Data'),
      '#description' => $this->t('Curabitur non.'),
      '#group' => 'information',
    ];
    // A cada grupo añadimos elementos cómo siempre
    $form['access_data']['user_email'] = [
      '#type' => 'email',
      '#title' => $this->t('User email'),
      '#required' => TRUE,
    ];
    $form['access_data']['password'] = [
      '#type' => 'password_confirm',
      '#title' => $this->t('Password'),
      '#required' => TRUE,
    ];
    

    table

    $form['members'] = array(
      '#type' => 'table',
      '#caption' => $this->t('Members'),
      '#header' => [
        $this->t('ID'), 
        $this->t('First name'),
        $this->t('Last name')
      ],
    );
    

    Otras propiedades:

    • #empty para texto a mostrar si tabla vacía.
    • #responsive por defecto es TRUE
    • #sticky por defecto es FALSE

    Añadir la información de las filas:

    Método 1: sin rows, con elementos hijos

    for ($i=1; $i<=5; $i++) {
      $form['members'][$i]['id'] = [
        '#type' => 'number',
        '#title' => $this->t('ID'),
        '#title_display' => 'invisible',
        '#size' => 3,
      ];
      $form['members'][$i]['first_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First name'),
        '#title_display' => 'invisible',
        '#size' => 30,
      ];
      $form['members'][$i]['last_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last name'),
        '#title_display' => 'invisible',
        '#size' => 30,
      ];
    }
    

    Método 2: Usando twig y la propiedad rows

    https://api.drupal.org/api/drupal/core!modules!system!templates!table.html.twig/8.2.x

      public function build() {
    
        $build['user_table'] = [
          '#type' => 'table',
          '#caption' => $this->t('Actual User'),
          '#header' => [
            $this->t('ID of user'),
            $this->t('Display Name'),
            $this->t('Roles),
          ],
          '#rows' => [
            [
              Markup::create($this->currentUser->id()),
              Markup::create($this->currentUser->getDisplayName()),
              Markup::create(implode(",",$this->currentUser->getRoles())),
            ],
          ],
        ];
    
        return [
          '#type' => 'markup',
          '#markup' => render($build['user_table']),
        ];
    
      }
    
    

    Elementos de texto

    textfield

    $form['first_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First name'),
      '#required' => TRUE,
      '#size' => 40,
      '#maxlength' => 80,
      '#default_value' => $this->t('Your first name'),
    ];
    

    textarea

    $form['description'] = [
      '#type' => 'textarea',
      '#title' => t('Description'),
      '#cols' => 60,
      '#rows' => 5,
    ];
    

    email

    $form['user_email'] = [
      '#type' => 'email',
      '#title' => $this->t('User email'),
      '#description' => $this->t('Your email.'),
      '#required' => TRUE,
      '#size' => 60,
      '#maxlength' => 128,
    ];
    

    number

    Ejemplo 1:

    $form['age'] = [
      '#type' => 'number',
      '#title' => $this->t('Age'),
    ];
    

    Ejemplo 2:

    $form['quantity'] = [
      '#type' => 'number',
      '#title' => $this->t('Quantity'),
      '#description' => $this->t('Must be a multiple of 5'),
      '#min' => 0,
      '#max' => 100,
      '#step' => 5,
    ];
    

    password

    password_confirm

    tel

    $form['tel_number'] = [
      '#type' => 'tel',
      '#title' => t('Telephone number'),
      '#maxlength' => 64,
      '#size' => 30,
    ];
    

    text_format

    hidden

    Permite añadir información oculta al formulario. Hay que tener en cuenta que este campo se renderiza y su valor sí está visible en el código HTML, aunque no se muestra en el formulario.

    El campo hidden puede usar las propiedades #default_value (Js la puede modificar) y #value (mas seguro).

    $form['entity_id'] = [
      '#type' => 'hidden',
      '#value' => $entity_id,
    ];
    

    value

    Campo que no se muestra en el html y permanece al 100% oculta.

    Ejemplo 1:

    $form['entity_id'] = [
      '#type' => 'value',
      '#value' => $entity_id,
    ];
    

    Ejemplo 2:

    $form['nid'] = [
      '#type' => 'value',
      '#value' => $nid,
    ];
    
    

    Elementos de lista y selección

    select

        $form['months'] = [
          '#type' => 'select',
          '#title' => $this->t('Month'),
          '#default_value' => date('n'),
          '#options' => [
            1 => $this->t('January'),
            2 => $this->t('February'),
            3 => $this->t('March'),
            4 => $this->t('April'),
            5 => $this->t('May'),
            6 => $this->t('June'),
            7 => $this->t('July'),
            8 => $this->t('August'),
            9 => $this->t('September'),
            10 => $this->t('October'),
            11 => $this->t('November'),
            12 => $this->t('December'),
          ],
          '#description' => t('Select month'),
        ];
    

    checkboxes

    Ejemplo 1

    $form['colors'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Colors'),
      '#default_value' => ['red','green'],
      '#options' => [
        'red' => $this->t('Red'),
        'green' => $this->t('Green'),
        'blue' => $this->t('Blue'),
        'yellow' => $this->t('Yellow'),
      ],
      '#description' => $this->t('Select your preferred colors.'),
    ];
    

    Ejemplo 2: Cargar Tipo de CT en Options

    $types = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->loadMultiple();
    
    $options = [];
    foreach ($types as $key => $value){
      $options[$key] = $key;
    }
    $form['my_module_content_types'] = [
     '#type' => 'checkboxes',
     '#title' => $this->t('My content types'),
     '#options' => $options,
    ];
    
    Carga de Options con array_combine
    $range = range(1, 3);
    $options = array_combine($range, $range),
    

    Para construir el array de opciones #options del elemento select, se puede usar las funciones range() y array_combine(). Con range() construimos un array del tipo [1, 2, 3], y con array_combine() construimos un array con formato clave => valor, que es el formato esperado por #options:

    Array
    (
    [1] => 1
    [2] => 2
    [3] => 3
    )
    

    radios

    $form['day'] = [
      '#type' => 'radios',
      '#title' => $this->t('Day of the week'),
      '#options' => [
        1 => $this->t('Monday'),
        2 => $this->t('Tuesday'),
        3 => $this->t('Wednesday'),
        4 => $this->t('Thursday'),
        5 => $this->t('Friday'),
        6 => $this->t('Saturday'),
        7 => $this->t('Sunday'),
      ],
      '#description' => $this->t('Choose the day of the week.'),
      '#default_value' => date('N'),
    ];
    

    checkbox

    $form['legal_notice'] = [
    '#type' => 'checkbox',
    '#title' => $this->t('Accept terms and conditions.'),
    ];
    

    radio

    range

    tableselect

    Elementos de fechas

    date

    $form['start_date'] = [
      '#type' => 'date',
      '#title' => $this->t('Start Date'),
      '#default_value' => '2021-01-13',
    ];
    

    datelist

    datetime

    Botones y Enlaces

    submit

    actions

    button

    image_button

    Otros Elementos de formulario

    color

    file y managedfile

    $form['file_upload'] = array(
      '#type' => 'file',
      '#title' => t('Upload a file'),
    );
    
    $form['foto'] = [
      '#title' => $this->t('Foto'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://managed',
      '#upload_validators' => [
        'file_validate_extensions' => ['jpg png'],
       ],
       '#required' => TRUE,
    ];
    

    weight

    path

    Sirve para añadir un nombre de sistema.

    Atributos adicionales que se pueden usar:

    • exists:Nombre del método que comprueba si el valor es único.
    • source: contiene el nombre del campo asociado al nombre de sistema. Si por ejemplo queremos usar cómo source el elemento $form['foo']['bar']['beer'] tendremos que usar 'source' => ['foo', 'bar', 'beer'];.
    • label. Texto a mostrar como etiqueta del campo. Por defecto el valor es "Machine name".
    • replace_pattern. Expresión regular que indica los caracteres no permitidos. Por defecto sólo se permiten letras en minúscula, números y guión bajo ('[^a-z0-9_]+').
    • replace. Carácter de reemplazo para los caracteres no permitidos. Por defecto '_'.
    • error. Mensaje de error para informar de que la cadena contiene caracteres no permitidos.
    • #maxlength
    • #disabled. Estableciendo el valor a TRUE el nombre de máquina no podrá ser editado tras la creación inicial (cuando se esté editando el formulario con un elemento creado previamente).
    $form['element_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Element name'),
    ];
    $form['element_machine_name'] = [
      '#type' => 'machine_name',
      '#description' => $this->t('A unique name for this item. It must
      only contain lowercase letters, numbers, and underscores.'),
      '#machine_name' => [
      'source' => ['element_name'],
      ],
    ];
    

    entity_autocomplete

    $form['author'] = [
    '#type' => 'entity_autocomplete',
    '#target_type' => 'user',
    '#title' => $this->t('Author'),
    '#description' => $this->t('Enter the username'),
    ];
    

    Más info: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Element!EntityAutocomplete.php/class/EntityAutocomplete/8

    language_select

    search

⚠️ **GitHub.com Fallback** ⚠️