public function PaymentMethodAddForm::buildForm in Commerce Core 8.2
Form constructor.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
array The form structure.
Overrides FormInterface::buildForm
File
- modules/
payment/ src/ Form/ PaymentMethodAddForm.php, line 70
Class
- PaymentMethodAddForm
- Provides the payment method add form.
Namespace
Drupal\commerce_payment\FormCode
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {
/** @var \Drupal\commerce_payment\PaymentOption[] $payment_options */
$payment_options = $form_state
->get('payment_options');
if (!$payment_options) {
$payment_options = $this
->buildPaymentOptions($form_state);
if (!$payment_options) {
throw new AccessDeniedHttpException();
}
$form_state
->set('payment_options', $payment_options);
}
$payment_gateways = $form_state
->get('payment_gateways');
// Core bug #1988968 doesn't allow the payment method add form JS to depend
// on an external library, so the libraries need to be preloaded here.
foreach ($payment_gateways as $payment_gateway) {
if ($js_library = $payment_gateway
->getPlugin()
->getJsLibrary()) {
$form['#attached']['library'][] = $js_library;
}
}
// Prepare the form for ajax.
$form['#wrapper_id'] = Html::getUniqueId('payment-method-add-form-wrapper');
$form['#prefix'] = '<div id="' . $form['#wrapper_id'] . '">';
$form['#suffix'] = '</div>';
$user_input = $form_state
->getUserInput();
if (!empty($user_input['payment_method']) && isset($payment_options[$user_input['payment_method']])) {
$default_option = $payment_options[$user_input['payment_method']];
}
else {
$default_option = reset($payment_options);
}
$option_labels = array_map(function (PaymentOption $option) {
return $option
->getLabel();
}, $payment_options);
$form['#after_build'][] = [
get_class($this),
'clearValues',
];
$form['payment_method'] = [
'#type' => 'radios',
'#title' => $this
->t('Payment method'),
'#options' => $option_labels,
'#default_value' => $default_option
->getId(),
'#ajax' => [
'callback' => [
get_class($this),
'ajaxRefresh',
],
'wrapper' => $form['#wrapper_id'],
],
'#access' => count($payment_options) > 1,
];
$form_state
->set('payment_gateway', $default_option
->getPaymentGatewayId());
$form_state
->set('payment_method_type', $default_option
->getPaymentMethodTypeId());
$form = $this
->buildPaymentMethodForm($form, $form_state);
$form['actions']['#type'] = 'actions';
$form['actions']['submit_payment_method'] = [
'#type' => 'submit',
'#value' => $this
->t('Save'),
'#button_type' => 'primary',
'#submit' => [
'::submitForm',
],
];
return $form;
}