xero-8.x-2.x-dev/examples/src/Form/InvoiceForm.php
examples/src/Form/InvoiceForm.php
<?php
namespace Drupal\xero_example\Form;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Utility\Random;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\xero\XeroQuery;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Posts an invoice that is created automatically.
*
* @ingroup xero_example
*/
class InvoiceForm extends FormBase implements ContainerInjectionInterface {
/**
* The Xero Query.
*
* @var \Drupal\xero\XeroQuery
*/
protected $query;
/**
* The Typed Data Manager.
*
* @var \Drupal\Core\TypedData\TypedDataManagerInterface
*/
protected $typedDataManager;
/**
* Initialization method.
*
* @param \Drupal\xero\XeroQuery $query
* The xero.query service.
* @param \Drupal\Core\TypedData\TypedDataManagerInterface $typedDataManager
* The typed_data_manager service.
*/
public function __construct(XeroQuery $query, TypedDataManagerInterface $typedDataManager) {
$this->query = $query;
$this->typedDataManager = $typedDataManager;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'xero_example_invoice_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$storage = $form_state->getStorage();
if (!empty($storage) && isset($storage['invoice'])) {
$form['invoice-wrapper'] = [
'#type' => 'container',
'#attributes' => ['class' => ['status']],
'invoice' => $storage['invoice']->view(),
];
}
$form['invoice'] = [
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => !empty($storage) && isset($storage['invoice']),
'code' => [
'#type' => 'textfield',
'#title' => $this->t('Account Code'),
'#required' => TRUE,
'#parents' => ['code'],
'#default_value' => $this->configFactory()->get('xero.settings')->get('defaults.account'),
],
];
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add Invoice'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
try {
// Creates a random invoice and posts it.
$listDefinition = $this->typedDataManager->createListDataDefinition('xero_invoice');
/** @var \Drupal\xero\Plugin\DataType\XeroItemList $invoices */
$invoices = $this->typedDataManager->create($listDefinition, []);
$random = new Random();
// Appends a new invoice onto the stack.
$invoices->appendItem(
[
'Contact' => ['Name' => $random->name(15)],
'Type' => 'ACCREC',
'Date' => date('Y-m-d'),
'DueDate' => date('Y-m-d', time() + 1296000),
'LineAmountTypes' => 'NoTax',
'Status' => 'SUBMITTED',
// It is possible to define everything in values, but this example
// will use Typed Data to set new items.
'LineItems' => [],
]
);
// Sets the reference value programmatically.
$invoices
->get(0)
->get('Reference')
->setValue($random->string());
// Adds some random line items programmatically.
$numItems = mt_rand(1, 5);
for ($i = 0; $i < $numItems; $i++) {
$lineItemValues = [
'Description' => $random->sentences(2, TRUE),
'LineAmount' => 5.25,
'AccountCode' => $form_state->getValue('code'),
];
// Appends line item array by getting the first Invoice, then getting
// the LineItems element of the Invoice.
$invoices
->get(0)
->get('LineItems')
->appendItem($lineItemValues);
}
// Posts the data, which should return invoices back.
$returnedInvoices = $this->query
->setType('xero_invoice')
->setMethod('post')
->setData($invoices)
->execute();
if ($returnedInvoices) {
$form_state->setStorage([
'invoice' => $returnedInvoices->get(0),
]);
$form_state->setRebuild(TRUE);
$this->messenger()->addStatus($this->t(
'Successfully created invoice %name',
['%name' => $returnedInvoices->get(0)->get('InvoiceID')->getValue()]
));
}
else {
$form_state->setRebuild(TRUE);
$this->messenger()->addError($this->t('Query failed'));
}
}
catch (PluginException $e) {
$this->messenger()->addError($this->t('Plugin error: %error', ['%error' => $e->getMessage()]));
}
catch (\Exception $e) {
$this->messenger()->addError($this->t('Unknown error: %error', ['%error' => $e->getMessage()]));
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('xero.query'),
$container->get('typed_data_manager')
);
}
}
