MeasurementTestForm.php in Physical Fields 8
File
tests/modules/physical_test/src/Form/MeasurementTestForm.php
View source
<?php
namespace Drupal\physical_test\Form;
use Drupal\physical\Length;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\physical\LengthUnit;
class MeasurementTestForm extends FormBase {
public function getFormId() {
return 'physical_measurement_test_form';
}
public function buildForm(array $form, FormStateInterface $form_state, $restrict_unit = FALSE) {
$form['height'] = [
'#type' => 'physical_measurement',
'#measurement_type' => 'length',
'#title' => $this
->t('Height'),
'#default_value' => [
'number' => '1.92',
'unit' => LengthUnit::METER,
],
'#required' => TRUE,
];
if ($restrict_unit) {
$form['height']['#available_units'] = [
LengthUnit::METER,
];
}
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$value = $form_state
->getValue('height');
$height = new Length($value['number'], $value['unit']);
$this
->messenger()
->addStatus($this
->t('The number is "@number" and the unit is "@unit".', [
'@number' => $height
->getNumber(),
'@unit' => $height
->getUnit(),
]));
}
}