D8 Formularios Creación - pierregermain/MyDrupal GitHub Wiki
Páginas relacionadas:
Índice:
- Links Importantes:
- Formulario básico
- Cómo Inyectar servicios en un formulario
- Propiedades de elementos de formularios
- Agregar Validaciones
- Agregar Submit
- Creación de formularios con la consola
Links Importantes:
Formulario básico
Pasos para realizar un formulario básico
1. Crear el fichero routing
my_module.simple:
path: '/my-route/forms/simple'
defaults:
_form: '\Drupal\my_module\Form\Simple'
_title: 'Simple Form'
requirements:
_permission: 'access content'
2. Creación de la clase
OJO: el nombre de la clase debe coincidir con el nombre del Form definido en el routing
/src/Form/Simple.php
Extendemos de FormBase
Consideraciones:
- $form contiene la estructura por defecto del formulario.
- $form_state de tipo FormStateInterface contiene los valores de los campos enviados por el usuario o almacenados.
- getFormId() sirve para dar un ID único a nuestro formulario para poder modificarlo desde otros módulos con hook_form_alter().
- finalmente definimos validateForm() y submitForm().
<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements the Simple form controller.
*
* @see \Drupal\Core\Form\FormBase
*/
class Simple extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
//.. Definir estructura
return $form;
}
public function getFormId() {
return 'my_module_simple';
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
3. Definimos la estructura del formulario desde el buildForm()
$form['title'] = [
'#type' => 'textfield',
'#title' => $this->t('Title'),
'#description' => $this->t('The title must be at least 5 characters long.'),
'#required' => TRUE,
];
4. Definimos el botón de Envío
Lo metemos dentro del contenedor de "actions".
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
Finalmente nos encargaríamos de crear el validate y submit.
Cómo Inyectar servicios en un formulario
Añadimos a la clase un contstructor y create con los servicios a ser inyectados.
//..
class Simple extends FormBase {
protected $database;
protected $currentUser;
protected $emailValidator;
public function __construct(Connection $database,
AccountInterface $current_user,
EmailValidator $email_validator) {
$this->database = $database;
$this->currentUser = $current_user;
$this->emailValidator = $email_validator;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('database'),
$container->get('current_user'),
$container->get('email.validator')
);
}
public function buildForm(array $form, FormStateInterface $form_state) {
//..
Propiedades de elementos de formularios
Type textfield
$form['title'] = [
'#type' => 'textfield',
'#title' => $this->t('Title'),
'#description' => $this->t('The title must be at least 5 characters long.'),
'#required' => TRUE,
];
Type Select
$form['color'] = [
'#type' => 'select',
'#title' => $this->t('Color'),
'#options' => [
0 => $this->t('Black'),
1 => $this->t('Red'),
2 => $this->t('Blue'),
3 => $this->t('Green'),
4 => $this->t('Orange'),
5 => $this->t('White'),
],
'#default_value' => 2,
'#description' => $this->t('Choose a color.'),
];
Type Email
$form['email'] = [
'#type' => 'email',
'#title' => $this->t('Email'),
'#description' => $this->t('Your email.'),
'#default_value' => $this->currentUser->getEmail(),
'#required' => FALSE,
];
Agregar Validaciones
public function validateForm(array &$form, FormStateInterface $form_state) {
$title = $form_state->getValue('title');
if (strlen($title) < 5) {
// Set an error for the form element with a key of "title".
$form_state->setErrorByName('title', $this->t('The title must
be at least 5 characters long.'));
}
if(!$this->emailValidator->isValid($email)) {
$form_state->setErrorByName('email', $this->t('%email is
not a valid email address.', ['%email' => $email]));
}
}
Agregar Submit
public function submitForm(array &$form, FormStateInterface $form_state) {
// Obtener datos del formulario
dpm($form_state->getValue('nid'));
dpm($form_state->getValue('field_name'));
// Escribir un mensaje
\Drupal::messenger()->addStatus(t('tu mensaje'));
// Escribir a watchdog
\Drupal::logger('my_module')->notice('New entry
from uid %uid, name %name, title %title inserted.',
[
'%uid' => $uid,
'%name' => $username,
'%title' => $title,
]);
// rederigir
$form_state->setRedirect('nombre-de-la-ruta');
}
Creación de formularios con la consola
drupal gf