xero-8.x-2.x-dev/src/Form/DefaultSettingsForm.php

src/Form/DefaultSettingsForm.php
<?php

namespace Drupal\xero\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\xero\XeroQuery;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\Serializer;

/**
 * Provides configuration form to integrate with a Xero private application.
 */
class DefaultSettingsForm extends ConfigFormBase implements ContainerInjectionInterface {

  /**
   * The serializer service.
   *
   * @var \Symfony\Component\Serializer\Serializer
   */
  protected $serializer;

  /**
   * The xero logger channel.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * The xero.query service.
   *
   * @var bool|\Drupal\xero\XeroQuery
   */
  protected $query = FALSE;

  /**
   * Initialization method.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Configuration factory interface.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The `config.typed` service.
   * @param \Drupal\xero\XeroQuery $query
   *   An instance of XeroClient or NULL if it fails, which is most likely the
   *   case on first load.
   * @param \Symfony\Component\Serializer\Serializer $serializer
   *   Serializer object.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   The logger factory.
   */
  public function __construct(ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typedConfigManager, XeroQuery $query, Serializer $serializer, LoggerChannelFactoryInterface $logger_factory) {
    parent::__construct($config_factory, $typedConfigManager);
    $this->query = $query;
    $this->serializer = $serializer;
    $this->logger = $logger_factory->get('xero');
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'xero_default_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return ['xero.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get the configuration from ConfigFormBase::config().
    $config = self::config('xero.settings');

    $tenant_options = [];
    $account_options = [];
    if (!$this->query->hasClient()) {
      $this->messenger()->addError($this->t('The xero.client is not available. Please check the Application configuration.'));
      return $form;
    }

    try {
      $tenant = $config->get('defaults.tenant');
      if ($tenant !== NULL && $tenant) {
        $accounts = $this->query->getCache('xero_account');

        if ($accounts) {
          foreach ($accounts as $account) {
            // Bank accounts do not have a code, exclude them.
            if ($account->get('Code')->getValue()) {
              $account_options[$account->get('Code')->getValue()] = $account->get('Name')->getValue();
            }
          }
        }
        else {
          $this->messenger()->addError($this->t('The xero.client did not return any accounts.'));
        }
      }

      $tenants = $this->query->getConnections();
      if (!empty($tenants)) {
        foreach ($tenants as $index => $tenant) {
          $tenant_options[$tenant['tenantId']] = $tenant['tenantName'];
        }
      }
    }
    catch (RequestException $e) {
      $this->logger->error('%message: %response', [
        '%message' => $e->getMessage(),
        '%response' => $e->getResponse()->getBody(),
      ]);
      return parent::buildForm($form, $form_state);
    }
    catch (\Exception $e) {
      $this->logger->error('%message', [
        '%message' => $e->getMessage(),
      ]);
      return parent::buildForm($form, $form_state);
    }

    $form['defaults']['tenant'] = [
      '#type' => 'select',
      '#title' => $this->t('Default Tenant'),
      '#description' => $this->t('Choose the default tenant organization to use.'),
      '#options' => $tenant_options,
      '#default_value' => $config->get('defaults.tenant'),
    ];

    $form['defaults']['account'] = [
      '#type' => 'select',
      '#title' => $this->t('Default Account'),
      '#description' => $this->t('Choose a default account.'),
      '#options' => $account_options,
      '#default_value' => $config->get('defaults.account'),
      '#disabled' => empty($account_options),
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!$this->query->hasClient()) {
      $form_state->setError($form['defaults'], $this->t('An error occurred trying to connect to Xero with the specified configuration. Please check the error logs for more information.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Set configuration.
    $config = self::config('xero.settings');
    $form_state_values = $form_state->getValues();
    $config
      ->set('defaults.account', $form_state_values['account'])
      ->set('defaults.tenant', $form_state_values['tenant']);

    $config->save();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('xero.query'),
      $container->get('serializer'),
      $container->get('logger.factory')
    );
  }

}

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

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