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

src/Form/SupplierInvoicesForm.php
<?php

namespace Drupal\fortnox\Form;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;
use Drupal\fortnox\Plugin\ResourceTrait;

/**
 * Class SupplierInvoicesForm.
 */
class SupplierInvoicesForm extends ResourceFormBase {

  use ResourceTrait;

  /**
   * {@inheritdoc}
   */
  protected $fields = [
    'textfield' => [
      'Currency' => FALSE,
      'ExternalInvoiceNumber' => FALSE,
      'ExternalInvoiceSeries' => FALSE,
      'InvoiceNumber' => FALSE,
      'OurReference' => FALSE,
      'YourReference' => FALSE,
      'OCR' => FALSE,
      'CurrencyRate' => FALSE,
      'CurrencyUnit' => FALSE,
      'Freight' => FALSE,
      'RoundOffValue' => FALSE,
      'Total' => FALSE,
      'VAT' => FALSE,
    ],
    'checkbox' => [
      'DisablePaymentFile' => FALSE,
      'PaymentPending' => FALSE,
    ],
    'datelist' => [
      'InvoiceDate' => FALSE,
      'DueDate' => FALSE,
    ],
    'textarea' => [
      'Comments' => FALSE,
    ],
    'fieldset' => [
      'SupplierInvoiceRows' => FALSE,
    ],
    'select' => [
      'SupplierNumber' => TRUE,
      'SalesType' => TRUE,
      'CostCenter' => FALSE,
      'Project' => FALSE,
    ],
  ];

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'supplier_invoice_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 Supplier Invoice');
      if (!empty($parameters['param1']) && !empty($parameters['param2'])) {
        $id .= '/' . $parameters['param1'] . '/' . $parameters['param2'];
      }
      if (empty($form_state->get('response'))) {
        $response = $parameters['resource']->getResponse($build, $id);
        $form_state->set('response', $response);
      }
      else {
        $response = $form_state->get('response');
      }
    }
    else {
      $submitButtonValue = $this->t('Create Supplier Invoice');
    }
    $values = isset($response['SupplierInvoice']) ? $response['SupplierInvoice'] : [];
    $this->createFormFields($form, $values);
    $this->createCurrencyFields($form);
    $form['SalesType']['#options'] = $this->getSalesTypesOptions();
    $form['SupplierNumber']['#options'] = !$form_state->isRebuilding() ? $this->getDynamicResourceOptions('suppliers', 'Name') : $form_state->getCompleteForm()['SupplierNumber']['#options'];
    $form['CostCenter']['#options'] = !$form_state->isRebuilding() ? $this->getDynamicResourceOptions('cost-centers', 'Description', ['Active' => TRUE]) : $form_state->getCompleteForm()['CostCenter']['#options'];
    $form['Project']['#options'] = !$form_state->isRebuilding() ? $this->getDynamicResourceOptions('projects', 'Description') : $form_state->getCompleteForm()['Project']['Options'];

    $form['#tree'] = TRUE;
    $supplierInvoiceValues = !empty($values) ? $values['SupplierInvoiceRows'] : [];
    $form['SupplierInvoiceRows'] = [
      '#type' => 'dynamic_add_more',
      '#title' => $this->t('Supplier Invoice Rows'),
      '#fields' => [
        [
          'field_name' => 'Account',
          'field_label' => $this->t('Account'),
          'field_type' => 'select',
          'options' => !$form_state->isRebuilding() ? $this->getDynamicResourceOptions('accounts', 'Description') : $form_state->getCompleteForm()['SupplierInvoiceRows'][0]['Account']['#options'],
        ],
        [
          'field_name' => 'ArticleNumber',
          'field_label' => $this->t('ArticleNumber'),
          'field_type' => 'select',
          'options' => !$form_state->isRebuilding() ? $this->getDynamicResourceOptions('articles', 'Description') : $form_state->getCompleteForm()['SupplierInvoiceRows'][0]['ArticleNumber']['#options'],
        ],
        [
          'field_name' => 'CostCenter',
          'field_label' => $this->t('CostCenter'),
          'field_type' => 'select',
          'options' => !$form_state->isRebuilding() ? $form['CostCenter']['#options'] : $form_state->getCompleteForm()['CostCenter']['#options'],
        ],
        [
          'field_name' => 'Project',
          'field_label' => $this->t('Project'),
          'field_type' => 'select',
          'options' => !$form_state->isRebuilding() ? $form['Project']['#options'] : $form_state->getCompleteForm()['Project']['#options'],
        ],
        [
          'field_name' => 'Debit',
          'field_label' => $this->t('Debit'),
          'field_type' => 'textfield',
        ],
        [
          'field_name' => 'Credit',
          'field_label' => $this->t('Credit'),
          'field_type' => 'textfield',
        ],
      ],
      '#fieldset_machine_name' => 'SupplierInvoiceRows',
      '#default_value' => $supplierInvoiceValues,
    ];

    // Disable the unit field.
    $form['CurrencyUnit']['#disabled'] = TRUE;
    // Disable the CurrencyRate field when the currency is SEK.
    $form['CurrencyRate']['#states'] = [
      'disabled' => [
        'select[name="Currency"]' => ['value' => 'SEK'],
      ],
    ];

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $invoiceDate = $form_state->getValue('InvoiceDate');
    if ($invoiceDate instanceof DrupalDateTime) {
      $form_state->setValue('InvoiceDate', $invoiceDate->format('Y-m-d'));
    }
    $dueDate = $form_state->getValue('DueDate');
    if ($dueDate instanceof DrupalDateTime) {
      $form_state->setValue('DueDate', $dueDate->format('Y-m-d'));
    }
    $floatFields = [
      'OCR',
      'AdministrationFee',
      'CurrencyRate',
      'CurrencyUnit',
      'Freight',
      'RoundOffValue',
      'Total',
      'VAT',
      ['SupplierInvoiceRows', 0, 'Debit'],
      ['SupplierInvoiceRows', 0, 'Credit'],
    ];
    // Verify the float fields to be valid.
    foreach ($floatFields as $field) {
      $fieldValue = $form_state->getValue($field);
      if (!empty($fieldValue) && !is_numeric($fieldValue)) {
        if (is_array($field)) {
          // For the fields inside a fieldset we set the error differently.
          $field = implode('][', $field);
        }
        $form_state->setErrorByName($field, $this->t('The field value must be numeric.'));
      }
    }
  }

  /**
   * Callback for both ajax-enabled buttons.
   *
   * Selects and returns the fieldset with the names in it.
   */
  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    return $form['SupplierInvoiceRows'];
  }

  /**
   * Submit handler for the "add-one-more" button.
   *
   * Increments the max counter and causes a rebuild.
   */
  public function addOne(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    $add_button = $name_field + 1;
    $form_state->set('num_names', $add_button);
    // Since our buildForm() method relies on the value of 'num_names' to
    // generate 'name' form elements, we have to tell the form to rebuild. If we
    // don't do this, the form builder will not call buildForm().
    $form_state->setRebuild();
  }

  /**
   * Submit handler for the "remove one" button.
   *
   * Decrements the max counter and causes a form rebuild.
   */
  public function removeCallback(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    if ($name_field > 1) {
      $remove_button = $name_field - 1;
      $form_state->set('num_names', $remove_button);
    }
    // Since our buildForm() method relies on the value of 'num_names' to
    // generate 'name' form elements, we have to tell the form to rebuild. If we
    // don't do this, the form builder will not call buildForm().
    $form_state->setRebuild();
  }

}

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

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