fortnox-8.x-1.x-dev/src/Form/AbsenceTransactionsForm.php
src/Form/AbsenceTransactionsForm.php
<?php
namespace Drupal\fortnox\Form;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;
use Drupal\fortnox\Plugin\ResourceTrait;
/**
* Provides create form for Absence Transactions resource.
*/
class AbsenceTransactionsForm extends ResourceFormBase {
use ResourceTrait;
/**
* {@inheritdoc}
*/
protected $fields = [
'select' => [
'EmployeeId' => FALSE,
'CauseCode' => FALSE,
'Project' => FALSE,
'CostCenter' => FALSE,
],
'datelist' => [
'Date' => FALSE,
],
'number' => [
'Hours' => FALSE,
'Extent' => FALSE,
],
];
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'absence_transactions_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$parameters = $this->getRouteMatch()->getParameters()->all();
$response = [];
if (!empty($parameters['id'])) {
$build = [];
$id = $parameters['id'];
$submitButtonValue = $this->t('Edit Absence Transaction');
if (!empty($parameters['param1']) && !empty($parameters['param2'])) {
$id .= '/' . $parameters['param1'] . '/' . $parameters['param2'];
}
$response = $parameters['resource']->getResponse($build, $id);
}
else {
$submitButtonValue = $this->t('Create Absence Transaction');
}
$values = isset($response['AbsenceTransaction']) ? $response['AbsenceTransaction'] : [];
$this->createFormFields($form, $values);
$form['CauseCode']['#options'] = $this->getCauseCodesList();
$form['EmployeeId']['#options'] = $this->getDynamicResourceOptions('employees', 'FullName');
$form['Project']['#options'] = $this->getDynamicResourceOptions('projects', 'Description');
$form['CostCenter']['#options'] = $this->getDynamicResourceOptions('cost-centers', 'Description');
$form['CauseCode']['#disabled'] = $form['EmployeeId']['#disabled'] = $form['Date']['#disabled'] = !empty($values) ? TRUE : FALSE;
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $submitButtonValue,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$date = $form_state->getValue('Date');
if ($date instanceof DrupalDateTime) {
$form_state->setValue('Date', $date->format('Y-m-d'));
}
}
}
