fortnox-8.x-1.x-dev/src/Form/EmployeesForm.php

src/Form/EmployeesForm.php
<?php

namespace Drupal\fortnox\Form;

use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Locale\CountryManager;
use Drupal\fortnox\Plugin\ResourceTrait;

/**
 * Provides create and edit form for Employee resource.
 */
class EmployeesForm extends ResourceFormBase {

  use ResourceTrait;

  /**
   * {@inheritdoc}
   */
  protected $fields = [
    'select' => [
      'EmploymentForm' => FALSE,
      'SalaryForm' => FALSE,
      'PersonelType' => FALSE,
      'ScheduleId' => FALSE,
      'ForaType' => FALSE,
      'TaxAllowance' => FALSE,
    ],
    'datelist' => [
      'EmploymentDate' => FALSE,
    ],
    'number' => [
      'EmployeeId' => TRUE,
      'PersonalIdentityNumber' => FALSE,
      'TaxColumn' => FALSE,
    ],
    'textfield' => [
      'FirstName' => FALSE,
      'LastName' => FALSE,
      'JobTitle' => FALSE,
      'MonthlySalary' => FALSE,
      'HourlyPay' => FALSE,
      'TaxTable' => FALSE,
      'NonRecurringTax' => FALSE,
      'ClearingNo' => FALSE,
      'BankAccountNo' => FALSE,
      'AverageWeeklyHours' => FALSE,
      'AverageHourlyWage' => FALSE,
    ],
    'email' => [
      'Email' => FALSE,
    ],
    'tel' => [
      'Phone1' => FALSE,
      'Phone2' => FALSE,
    ],
    'radios' => [
      'Inactive' => TRUE,
    ],
    'fieldset' => [
      'Address' => FALSE,
    ],
  ];

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'employees_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 Employee');
      if (!empty($parameters['param1']) && !empty($parameters['param2'])) {
        $id .= '/' . $parameters['param1'] . '/' . $parameters['param2'];
      }
      $response = $parameters['resource']->getResponse($build, $id);
    }
    else {
      $submitButtonValue = $this->t('Create Employee');
    }
    $values = isset($response['Employee']) ? $response['Employee'] : [];
    $this->createFormFields($form, $values);
    $form['EmploymentForm']['#options'] = $this->getSelectListOptions('EmploymentForm');
    $form['ForaType']['#options'] = $this->getSelectListOptions('ForaType');
    $form['PersonelType']['#options'] = $this->getSelectListOptions('PersonelType');
    $form['SalaryForm']['#options'] = $this->getSelectListOptions('SalaryForm');
    $form['ScheduleId']['#options'] = $this->getSelectListOptions('ScheduleId');
    $form['TaxAllowance']['#options'] = $this->getSelectListOptions('TaxAllowance');
    if (!empty($values)) {
      $form['Inactive']['#default_value'] = $values['Inactive'] ? 1 : 0;
    }
    $form['Address']['Address'] = [
      '#type' => 'address',
      '#field_overrides' => [
        AddressField::GIVEN_NAME => FieldOverride::HIDDEN,
        AddressField::FAMILY_NAME => FieldOverride::HIDDEN,
        AddressField::ORGANIZATION => FieldOverride::HIDDEN,
        AddressField::ADMINISTRATIVE_AREA => FieldOverride::HIDDEN,
        AddressField::SORTING_CODE => FieldOverride::HIDDEN,
        AddressField::DEPENDENT_LOCALITY => FieldOverride::HIDDEN,
      ],
    ];
    if (!empty($values['Country'])) {
      $countries = CountryManager::getStandardList();
      $form['Address']['Address']['#default_value'] = [
        'country_code' => array_search($values['Country'], $countries),
        'locality' => $values['City'],
        'address_line1' => $values['Address1'],
        'address_line2' => $values['Address2'],
        'postal_code' => $values['PostCode'],
      ];
    }

    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $submitButtonValue,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    if ($values['EmploymentDate'] instanceof DrupalDateTime) {
      $form_state->setValue('EmploymentDate', $values['EmploymentDate']->format('Y-m-d'));
    }
    if (!empty($values['MonthlySalary']) && !$this->validateNumericField($values['MonthlySalary'])) {
      $form_state->setErrorByName('MonthlySalary', $this->t('MonthlySalary should be a float value.'));
    }
    if (!empty($values['HourlyPay']) && !$this->validateNumericField($values['HourlyPay'])) {
      $form_state->setErrorByName('HourlyPay', $this->t('HourlyPay should be a float value.'));
    }
    if (!empty($values['TaxTable']) && !$this->validateNumericField($values['TaxTable'])) {
      $form_state->setErrorByName('TaxTable', $this->t('TaxTable should be a float value.'));
    }
    if (!empty($values['NonRecurringTax']) && !$this->validateNumericField($values['NonRecurringTax'])) {
      $form_state->setErrorByName('NonRecurringTax', $this->t('NonRecurringTax should be a float value.'));
    }
    if (!empty($values['AverageHourlyWage']) && !$this->validateNumericField($values['AverageHourlyWage'])) {
      $form_state->setErrorByName('AverageHourlyWage', $this->t('AverageHourlyWage should be a float value.'));
    }
    if (!empty($values['AverageHourlyWage']) && !$this->validateNumericField($values['AverageHourlyWage'])) {
      $form_state->setErrorByName('AverageHourlyWage', $this->t('AverageHourlyWage should be a float value.'));
    }
    $id = $this->getRouteMatch()->getRawParameters()->get('id');
    if (!empty($values['EmployeeId']) && empty($id)) {
      $resource = $this->requestStack->getCurrentRequest()->get('resource');
      $build = [];
      $response = $resource->getResponse($build, $values['EmployeeId']);
      if (!empty($response)) {
        $form_state->setErrorByName('EmployeeId', $this->t('Employee ID already exists.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Remove form token and id from form state.
    $form_state->cleanValues();
    $resource = $this->requestStack->getCurrentRequest()->get('resource');
    $resourceIDSingular = $resource->resourceIDSingular;
    $values[$resourceIDSingular] = $form_state->getValues();
    if (!empty($values[$resourceIDSingular]['Address'])) {
      $countries = CountryManager::getStandardList();
      $values[$resourceIDSingular]['Address1'] = $values[$resourceIDSingular]['Address']['address_line1'];
      $values[$resourceIDSingular]['Address2'] = $values[$resourceIDSingular]['Address']['address_line2'];
      $values[$resourceIDSingular]['PostCode'] = $values[$resourceIDSingular]['Address']['postal_code'];
      $values[$resourceIDSingular]['City'] = $values[$resourceIDSingular]['Address']['locality'];
      if (!empty($values[$resourceIDSingular]['Address']['country_code'])) {
        $values[$resourceIDSingular]['Country'] = $countries[$values[$resourceIDSingular]['Address']['country_code']]->__toString();
      }
      unset($values[$resourceIDSingular]['Address']);
    }
    $parameters = $this->getRouteMatch()->getRawParameters()->all();
    if (!empty($parameters['id'])) {
      $id = $parameters['id'];
      if (!empty($parameters['param1']) && !empty($parameters['param2'])) {
        $id .= '/' . $parameters['param1'] . '/' . $parameters['param2'];
      }
      $resource->updateResource($id, $values);
    }
    else {
      $resource->createFortnoxResource($values);
    }
  }

  /**
   * Validate float values from textfields.
   *
   * @param string $value
   *   The value to validate.
   *
   * @return false|int
   *   The validation status.
   */
  protected function validateNumericField($value) {
    return preg_match('/^[\d]{1,}.{0,}[\d]{1,4}$/', $value);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc