You are here

class BillingScheduleForm in Commerce Recurring Framework 8

Hierarchy

Expanded class hierarchy of BillingScheduleForm

File

src/Form/BillingScheduleForm.php, line 15

Namespace

Drupal\commerce_recurring\Form
View source
class BillingScheduleForm extends EntityForm {

  /**
   * The billing schedule plugin manager.
   *
   * @var \Drupal\commerce_recurring\BillingScheduleManager
   */
  protected $billingSchedulePluginManager;

  /**
   * The prorater plugin manager.
   *
   * @var \Drupal\commerce_recurring\ProraterManager
   */
  protected $proraterPluginManager;

  /**
   * Constructs a new BillingScheduleForm object.
   *
   * @param \Drupal\commerce_recurring\BillingScheduleManager $billing_schedule_plugin_manager
   *   The billing schedule plugin manager.
   * @param \Drupal\commerce_recurring\ProraterManager $prorater_manager
   *   The prorater plugin manager.
   */
  public function __construct(BillingScheduleManager $billing_schedule_plugin_manager, ProraterManager $prorater_manager) {
    $this->billingSchedulePluginManager = $billing_schedule_plugin_manager;
    $this->proraterPluginManager = $prorater_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.commerce_billing_schedule'), $container
      ->get('plugin.manager.commerce_prorater'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    /** @var \Drupal\commerce_recurring\Entity\BillingScheduleInterface $billing_schedule */
    $billing_schedule = $this->entity;
    $plugins = array_column($this->billingSchedulePluginManager
      ->getDefinitions(), 'label', 'id');
    asort($plugins);
    $proraters = array_column($this->proraterPluginManager
      ->getDefinitions(), 'label', 'id');
    asort($proraters);

    // Use the first available plugin as the default value.
    if (!$billing_schedule
      ->getPluginId()) {
      $plugin_ids = array_keys($plugins);
      $plugin = reset($plugin_ids);
      $billing_schedule
        ->setPluginId($plugin);
    }

    // The form state will have a plugin value if #ajax was used.
    $plugin = $form_state
      ->getValue('plugin', $billing_schedule
      ->getPluginId());
    $prorater = $form_state
      ->getValue('prorater', $billing_schedule
      ->getProraterId());

    // Pass the configuration only if the plugin hasn't been changed via #ajax.
    $plugin_configuration = $billing_schedule
      ->getPluginId() == $plugin ? $billing_schedule
      ->getPluginConfiguration() : [];
    $prorater_configuration = $billing_schedule
      ->getProraterId() == $prorater ? $billing_schedule
      ->getProraterConfiguration() : [];
    $wrapper_id = Html::getUniqueId('billing-schedule-form');
    $form['#tree'] = TRUE;
    $form['#prefix'] = '<div id="' . $wrapper_id . '">';
    $form['#suffix'] = '</div>';
    $form['label'] = [
      '#title' => t('Label'),
      '#type' => 'textfield',
      '#default_value' => $billing_schedule
        ->label(),
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $billing_schedule
        ->id(),
      '#machine_name' => [
        'exists' => [
          BillingSchedule::class,
          'load',
        ],
        'source' => [
          'label',
        ],
      ],
      '#disabled' => !$billing_schedule
        ->isNew(),
    ];
    $form['displayLabel'] = [
      '#type' => 'textfield',
      '#title' => t('Display label'),
      '#description' => t('Used to identify the billing schedule on the frontend.'),
      '#default_value' => $billing_schedule
        ->getDisplayLabel(),
      '#required' => TRUE,
    ];
    $form['billingType'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Billing type'),
      '#options' => [
        BillingScheduleInterface::BILLING_TYPE_PREPAID => $this
          ->t('Prepaid'),
        BillingScheduleInterface::BILLING_TYPE_POSTPAID => $this
          ->t('Postpaid'),
      ],
      '#default_value' => $billing_schedule
        ->getBillingType(),
    ];
    $form['plugin'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Plugin'),
      '#options' => $plugins,
      '#default_value' => $plugin,
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::ajaxRefresh',
        'wrapper' => $wrapper_id,
      ],
    ];
    $form['configuration'] = [
      '#type' => 'commerce_plugin_configuration',
      '#plugin_type' => 'commerce_billing_schedule',
      '#plugin_id' => $plugin,
      '#default_value' => $plugin_configuration,
    ];
    $form['prorater'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Prorater'),
      '#description' => $this
        ->t('Modifies unit prices to reflect partial billing periods.'),
      '#options' => $proraters,
      '#default_value' => $prorater,
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::ajaxRefresh',
        'wrapper' => $wrapper_id,
      ],
    ];
    $form['prorater_configuration'] = [
      '#type' => 'commerce_plugin_configuration',
      '#plugin_type' => 'commerce_prorater',
      '#plugin_id' => $prorater,
      '#default_value' => $prorater_configuration,
    ];
    $retry_schedule = $billing_schedule
      ->getRetrySchedule();
    $retries = range(1, 8);
    $retry_labels = [
      $this
        ->t('If the initial attempt fails, retry after'),
      $this
        ->t('If the first retry fails, retry after'),
      $this
        ->t('If the second retry fails, retry after'),
      $this
        ->t('If the third retry fails, retry after'),
      $this
        ->t('If the fourth retry fails, retry after'),
      $this
        ->t('If the fifth retry fails, retry after'),
      $this
        ->t('If the sixth retry fails, retry after'),
      $this
        ->t('If the seventh retry fails, retry after'),
    ];
    $num_retries = $form_state
      ->getValue([
      'dunning',
      'num_retries',
    ], count($retry_schedule));
    $form['dunning'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Dunning'),
      '#open' => TRUE,
    ];
    $form['dunning']['help'] = [
      '#plain_text' => $this
        ->t("Defines what should happen when a recurring order's payment fails."),
    ];
    $form['dunning']['num_retries'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Number of retries'),
      '#options' => array_combine($retries, $retries),
      '#default_value' => $num_retries,
      '#ajax' => [
        'callback' => '::ajaxRefresh',
        'wrapper' => $wrapper_id,
      ],
    ];
    for ($i = 0; $i < $num_retries; $i++) {
      $form['dunning']['retry'][$i] = [
        '#type' => 'number',
        '#title' => $retry_labels[$i],
        '#field_suffix' => $this
          ->t('days'),
        '#default_value' => isset($retry_schedule[$i]) ? $retry_schedule[$i] : 2,
        '#min' => 1,
      ];
    }
    $form['dunning']['unpaid_subscription_state'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('After the final retry'),
      '#weight' => 1000,
      '#options' => [
        'active' => $this
          ->t('Keep the subscription active'),
        'canceled' => $this
          ->t('Cancel the subscription (non-reversible)'),
      ],
      '#default_value' => $billing_schedule
        ->getUnpaidSubscriptionState(),
    ];
    $form['status'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Status'),
      '#options' => [
        FALSE => $this
          ->t('Disabled'),
        TRUE => $this
          ->t('Enabled'),
      ],
      '#default_value' => $billing_schedule
        ->status(),
    ];
    return $form;
  }

  /**
   * Ajax callback.
   */
  public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    /** @var \Drupal\commerce_recurring\Entity\BillingScheduleInterface $billing_schedule */
    $billing_schedule = $this->entity;
    if ($billing_schedule
      ->isNew()) {
      return $form;
    }
    $is_referenced = (bool) $this->entityTypeManager
      ->getStorage('commerce_subscription')
      ->getQuery()
      ->accessCheck(FALSE)
      ->condition('billing_schedule', $billing_schedule
      ->id())
      ->count()
      ->execute();
    if ($is_referenced) {

      // Disable some fields when the billing shedule is already in use by subscriptions.
      $form['billingType']['#disabled'] = TRUE;
      $form['plugin']['#disabled'] = TRUE;
      $form['configuration']['#disabled'] = TRUE;
      $form['prorater']['#disabled'] = TRUE;
      $form['prorater_configuration']['#disabled'] = TRUE;
      if (empty($form_state
        ->getUserInput())) {

        // The form is not submitted, set a message explaining why some of the
        // fields are disabled.
        $link = Link::createFromRoute('subscriptions page', 'entity.commerce_subscription.collection');
        $this
          ->messenger()
          ->addWarning($this
          ->t('Some fields are disabled since the %billing_schedule billing schedule is used by subscriptions. Check the @link.', [
          '%billing_schedule' => $billing_schedule
            ->label(),
          '@link' => $link
            ->toString(),
        ]));
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $values = $form_state
      ->getValues();

    /** @var \Drupal\commerce_recurring\Entity\BillingScheduleInterface $billing_schedule */
    $billing_schedule = $this->entity;
    $billing_schedule
      ->setPluginConfiguration($values['configuration']);
    $billing_schedule
      ->setProraterConfiguration($values['prorater_configuration']);
    $billing_schedule
      ->setRetrySchedule($values['dunning']['retry']);
    $billing_schedule
      ->setUnpaidSubscriptionState($values['dunning']['unpaid_subscription_state']);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $this->entity
      ->save();
    $this
      ->messenger()
      ->addMessage($this
      ->t('Saved the @label billing schedule.', [
      '@label' => $this->entity
        ->label(),
    ]));
    $form_state
      ->setRedirect('entity.commerce_billing_schedule.collection');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BillingScheduleForm::$billingSchedulePluginManager protected property The billing schedule plugin manager.
BillingScheduleForm::$proraterPluginManager protected property The prorater plugin manager.
BillingScheduleForm::ajaxRefresh public static function Ajax callback.
BillingScheduleForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
BillingScheduleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BillingScheduleForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
BillingScheduleForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
BillingScheduleForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
BillingScheduleForm::__construct public function Constructs a new BillingScheduleForm object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.