You are here

public function SubscriptionCancelForm::buildForm in Commerce Recurring Framework 8

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 ContentEntityConfirmFormBase::buildForm

File

src/Form/SubscriptionCancelForm.php, line 62

Class

SubscriptionCancelForm
Provides a confirmation form for cancelling a subscription.

Namespace

Drupal\commerce_recurring\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  $subscription = $this->entity;
  assert($subscription instanceof SubscriptionInterface);

  // Check if the subscription is already canceled.
  if ($subscription
    ->getState()
    ->getId() === 'canceled') {
    return [
      'description' => [
        '#markup' => $this
          ->t('The subscription has already been canceled.'),
      ],
    ];
  }
  if ($current_billing_period = $subscription
    ->getCurrentBillingPeriod()) {
    $end_date = $current_billing_period
      ->getEndDate()
      ->getTimestamp();
    $end_date = $this->dateFormatter
      ->format($end_date, 'long');
    $form['cancel_option'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Cancellation options'),
      '#options' => [
        'scheduled' => $this
          ->t('End of the current billing period (@end_date)', [
          '@end_date' => $end_date,
        ]),
        'now' => $this
          ->t('Immediately'),
      ],
      '#default_value' => 'scheduled',
      '#weight' => -10,
    ];

    // Disable the 'scheduled' option if one has already been scheduled.
    if ($subscription
      ->hasScheduledChange('state', 'canceled')) {
      $form['cancel_option']['scheduled']['#disabled'] = TRUE;
      $form['cancel_option']['#default_value'] = 'now';
      $form['cancel_option']['#description'] = $this
        ->t('A cancellation has already been scheduled for @end_date.', [
        '@end_date' => $end_date,
      ]);
    }
  }
  else {
    if ($subscription
      ->hasScheduledChange('state', 'canceled')) {
      $form['description'] = [
        '#markup' => $this
          ->t('A cancellation has already been scheduled for this subscription.'),
      ];
      $form['actions']['submit']['#value'] = $this
        ->t('Cancel immediately');
      $form['actions']['cancel']['#title'] = $this
        ->t('Keep existing cancellation schedule');
    }
  }
  return $form;
}