class PaymentMethodAddForm in Commerce Core 8.2
Same name in this branch
- 8.2 modules/payment/src/Form/PaymentMethodAddForm.php \Drupal\commerce_payment\Form\PaymentMethodAddForm
- 8.2 modules/payment/src/PluginForm/PaymentMethodAddForm.php \Drupal\commerce_payment\PluginForm\PaymentMethodAddForm
- 8.2 modules/payment_example/src/PluginForm/Onsite/PaymentMethodAddForm.php \Drupal\commerce_payment_example\PluginForm\Onsite\PaymentMethodAddForm
Provides the payment method add form.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\commerce_payment\Form\PaymentMethodAddForm implements ContainerInjectionInterface
Expanded class hierarchy of PaymentMethodAddForm
1 string reference to 'PaymentMethodAddForm'
- commerce_payment.routing.yml in modules/
payment/ commerce_payment.routing.yml - modules/payment/commerce_payment.routing.yml
File
- modules/
payment/ src/ Form/ PaymentMethodAddForm.php, line 21
Namespace
Drupal\commerce_payment\FormView source
class PaymentMethodAddForm extends FormBase implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The inline form manager.
*
* @var \Drupal\commerce\InlineFormManager
*/
protected $inlineFormManager;
/**
* Constructs a new PaymentMethodAddForm instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\commerce\InlineFormManager $inline_form_manager
* The inline form manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, InlineFormManager $inline_form_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->inlineFormManager = $inline_form_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('plugin.manager.commerce_inline_form'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'commerce_payment_method_add_form';
}
/**
* {@inheritdoc}
*/
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;
}
/**
* Builds the payment options.
*
* This will build the payment options for payment gateways that support
* creating payment methods.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return \Drupal\commerce_payment\PaymentOption[]
* The payment options.
*/
protected function buildPaymentOptions(FormStateInterface $form_state) {
$payment_gateway_storage = $this->entityTypeManager
->getStorage('commerce_payment_gateway');
$payment_gateways = $payment_gateway_storage
->loadByProperties([
'status' => TRUE,
]);
$payment_gateways = array_filter($payment_gateways, function ($payment_gateway) {
return $payment_gateway
->getPlugin() instanceof SupportsCreatingPaymentMethodsInterface;
});
if (!$payment_gateways) {
return [];
}
$form_state
->set('payment_gateways', $payment_gateways);
$payment_options = [];
// 3) Add options to create new stored payment methods of supported types.
$payment_method_type_counts = [];
// Count how many new payment method options will be built per gateway.
foreach ($payment_gateways as $payment_gateway) {
$payment_method_types = $payment_gateway
->getPlugin()
->getPaymentMethodTypes();
foreach ($payment_method_types as $payment_method_type_id => $payment_method_type) {
if (!isset($payment_method_type_counts[$payment_method_type_id])) {
$payment_method_type_counts[$payment_method_type_id] = 1;
}
else {
$payment_method_type_counts[$payment_method_type_id]++;
}
}
}
foreach ($payment_gateways as $payment_gateway) {
$payment_gateway_plugin = $payment_gateway
->getPlugin();
$payment_method_types = $payment_gateway_plugin
->getPaymentMethodTypes();
foreach ($payment_method_types as $payment_method_type_id => $payment_method_type) {
$option_id = 'new--' . $payment_method_type_id . '--' . $payment_gateway
->id();
$option_label = $payment_method_type
->getCreateLabel();
// If there is more than one option for this payment method type,
// append the payment gateway label to avoid duplicate option labels.
if ($payment_method_type_counts[$payment_method_type_id] > 1) {
$option_label = $this
->t('@payment_method_label (@payment_gateway_label)', [
'@payment_method_label' => $payment_method_type
->getCreateLabel(),
'@payment_gateway_label' => $payment_gateway_plugin
->getDisplayLabel(),
]);
}
$payment_options[$option_id] = new PaymentOption([
'id' => $option_id,
'label' => $option_label,
'payment_gateway_id' => $payment_gateway
->id(),
'payment_method_type_id' => $payment_method_type_id,
]);
}
}
return $payment_options;
}
/**
* Builds the form for adding a payment method.
*
* @param array $form
* The parent form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the complete form.
*
* @return array
* The built form.
*/
protected function buildPaymentMethodForm(array $form, FormStateInterface $form_state) {
$payment_method_storage = $this->entityTypeManager
->getStorage('commerce_payment_method');
$payment_method = $payment_method_storage
->create([
'type' => $form_state
->get('payment_method_type'),
'payment_gateway' => $form_state
->get('payment_gateway'),
'uid' => $form_state
->getBuildInfo()['args'][0]
->id(),
]);
$inline_form = $this->inlineFormManager
->createInstance('payment_gateway_form', [
'operation' => 'add-payment-method',
], $payment_method);
$form['add_payment_method'] = [
'#parents' => [
'add_payment_method',
],
'#inline_form' => $inline_form,
];
$form['add_payment_method'] = $inline_form
->buildInlineForm($form['add_payment_method'], $form_state);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\commerce\Plugin\Commerce\InlineForm\EntityInlineFormInterface $inline_form */
$inline_form = $form['add_payment_method']['#inline_form'];
/** @var \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method */
$payment_method = $inline_form
->getEntity();
$this
->messenger()
->addMessage($this
->t('%label saved to your payment methods.', [
'%label' => $payment_method
->label(),
]));
$form_state
->setRedirect('entity.commerce_payment_method.collection', [
'user' => $payment_method
->getOwnerId(),
]);
}
/**
* Clears dependent form input when the payment_method changes.
*
* Without this Drupal considers the rebuilt form to already be submitted,
* ignoring default values.
*/
public static function clearValues(array $element, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
if (!$triggering_element) {
return $element;
}
$triggering_element_name = end($triggering_element['#parents']);
if ($triggering_element_name == 'payment_method') {
$user_input =& $form_state
->getUserInput();
$form_input = NestedArray::getValue($user_input, $element['#parents']);
unset($form_input['billing_information']);
unset($form_input['add_payment_method']);
NestedArray::setValue($user_input, $element['#parents'], $form_input);
}
return $element;
}
/**
* Ajax callback.
*/
public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
return $form;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormBase:: |
public | function |
Form validation handler. Overrides FormInterface:: |
62 |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PaymentMethodAddForm:: |
protected | property | The entity type manager. | |
PaymentMethodAddForm:: |
protected | property | The inline form manager. | |
PaymentMethodAddForm:: |
public static | function | Ajax callback. | |
PaymentMethodAddForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
PaymentMethodAddForm:: |
protected | function | Builds the form for adding a payment method. | |
PaymentMethodAddForm:: |
protected | function | Builds the payment options. | |
PaymentMethodAddForm:: |
public static | function | Clears dependent form input when the payment_method changes. | |
PaymentMethodAddForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
PaymentMethodAddForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
PaymentMethodAddForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
PaymentMethodAddForm:: |
public | function | Constructs a new PaymentMethodAddForm instance. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |