xero-8.x-2.x-dev/examples/src/Form/GetItemForm.php

examples/src/Form/GetItemForm.php
<?php

namespace Drupal\xero_example\Form;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\xero\XeroItemManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Demonstrates fetching data by guid.
 *
 * @ingroup xero_example
 */
class GetItemForm extends FormBase implements ContainerInjectionInterface {

  /**
   * Xero item manager.
   *
   * @var \Drupal\xero\XeroItemManagerInterface
   */
  protected $itemManager;

  /**
   * Initialization method.
   *
   * @param \Drupal\xero\XeroItemManagerInterface $itemManager
   *   The xero.item_manager service.
   */
  public function __construct(XeroItemManagerInterface $itemManager) {
    $this->itemManager = $itemManager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $storage = $form_state->getStorage();
    if (isset($storage['data']) && isset($storage['type'])) {
      $form['result'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => ['message', 'info'],
        ],
        'data' => $storage['data']->view(),
      ];
    }

    $form['guid'] = [
      '#type' => 'textfield',
      '#title' => $this->t('GUID'),
      '#required' => TRUE,
    ];

    $form['type'] = [
      '#type' => 'select',
      '#title' => $this->t('Xero Type'),
      '#options' => [
        'xero_account' => $this->t('Account'),
        'xero_contact' => $this->t('Contact'),
        'xero_invoice' => $this->t('Invoice'),
      ],
      '#required' => TRUE,
    ];

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Fetch'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    try {
      $item = $this->itemManager->loadItem($form_state->getValue('type'), $form_state->getValue('guid'));

      if ($item) {
        $form_state->setStorage([
          'data' => $item,
          'type' => $form_state->getValue('type'),
        ]);
      }
      else {
        $form_state->setStorage([]);
        $this->messenger()->addWarning('Data not found. Check error log.');
      }
    }
    catch (\Exception $e) {
      $this->messenger()->addError($e->getMessage());
      $form_state->setStorage([]);
    }

    $form_state->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('xero.item_manager'));
  }

}

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

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