PaymentMethodAddForm.php in Commerce Purchase Order 8
File
src/PluginForm/PurchaseOrder/PaymentMethodAddForm.php
View source
<?php
namespace Drupal\commerce_purchase_order\PluginForm\PurchaseOrder;
use Drupal\commerce_payment\PluginForm\PaymentMethodFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\commerce_payment\Exception\DeclineException;
use Drupal\commerce_payment\Exception\PaymentGatewayException;
class PaymentMethodAddForm extends PaymentMethodFormBase {
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['payment_details'] = [
'#parents' => array_merge($form['#parents'], [
'payment_details',
]),
'#type' => 'container',
'#payment_method_type' => 'purchase_order',
];
$form['payment_details'] = $this
->buildPurchaseOrderForm($form['payment_details'], $form_state);
if (isset($form['billing_information'])) {
$form['billing_information']['#weight'] = 10;
}
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$payment_method = $this->entity;
$values = $form_state
->getValue($form['#parents']);
$payment_gateway_plugin = $this->plugin;
try {
$payment_gateway_plugin
->createPaymentMethod($payment_method, $values['payment_details']);
} catch (DeclineException $e) {
\Drupal::logger('commerce_payment')
->warning($e
->getMessage());
throw new DeclineException('We encountered an error processing your payment method. Please verify your details and try again.');
} catch (PaymentGatewayException $e) {
\Drupal::logger('commerce_payment')
->error($e
->getMessage());
throw new PaymentGatewayException('We encountered an unexpected error processing your payment method. Please try again later.');
}
}
protected function buildPurchaseOrderForm(array $element, FormStateInterface $form_state) {
$element['#attributes']['class'][] = 'purchase-order-form';
$element['number'] = [
'#type' => 'textfield',
'#title' => $this
->t('Purchase Order number'),
'#attributes' => [
'autocomplete' => 'off',
],
'#required' => TRUE,
'#maxlength' => 19,
'#size' => 20,
];
return $element;
}
protected function submitBillingProfileForm(array $element, FormStateInterface $form_state) {
$billing_profile = $element['#entity'];
$form_display = EntityFormDisplay::collectRenderDisplay($billing_profile, 'default');
$form_display
->extractFormValues($billing_profile, $element, $form_state);
$payment_method = $this->entity;
$payment_method
->setBillingProfile($billing_profile);
}
}