You are here

class SmartDateOverrideForm in Smart Date 3.0.x

Same name and namespace in other branches
  1. 8.2 modules/smart_date_recur/src/Form/SmartDateOverrideForm.php \Drupal\smart_date_recur\Form\SmartDateOverrideForm
  2. 3.x modules/smart_date_recur/src/Form/SmartDateOverrideForm.php \Drupal\smart_date_recur\Form\SmartDateOverrideForm
  3. 3.1.x modules/smart_date_recur/src/Form/SmartDateOverrideForm.php \Drupal\smart_date_recur\Form\SmartDateOverrideForm
  4. 3.2.x modules/smart_date_recur/src/Form/SmartDateOverrideForm.php \Drupal\smart_date_recur\Form\SmartDateOverrideForm
  5. 3.3.x modules/smart_date_recur/src/Form/SmartDateOverrideForm.php \Drupal\smart_date_recur\Form\SmartDateOverrideForm
  6. 3.4.x modules/smart_date_recur/src/Form/SmartDateOverrideForm.php \Drupal\smart_date_recur\Form\SmartDateOverrideForm

Form controller for Smart Date Recur instace override edit forms.

Hierarchy

Expanded class hierarchy of SmartDateOverrideForm

1 file declares its use of SmartDateOverrideForm
Instances.php in modules/smart_date_recur/src/Controller/Instances.php
1 string reference to 'SmartDateOverrideForm'
smart_date_recur.routing.yml in modules/smart_date_recur/smart_date_recur.routing.yml
modules/smart_date_recur/smart_date_recur.routing.yml

File

modules/smart_date_recur/src/Form/SmartDateOverrideForm.php, line 23

Namespace

Drupal\smart_date_recur\Form
View source
class SmartDateOverrideForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'smart_date_override_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $rrule = NULL, $index = NULL, $ajax = FALSE) {

    // TODO: Show some kind of entity summary? Title at least?
    $instances = $rrule
      ->getRuleInstances();
    if ($ajax) {
      $form['#prefix'] = '<div id="manage-instances">';
      $form['#suffix'] = '</div>';
    }

    // Get field config.
    $field_config = FieldConfig::loadByName($rrule
      ->get('entity_type')
      ->getString(), $rrule
      ->get('bundle')
      ->getString(), $rrule
      ->get('field_name')
      ->getString());
    $defaults = $field_config
      ->getDefaultValueLiteral()[0];
    $values['start'] = DrupalDateTime::createFromTimestamp($instances[$index]['value']);
    $values['end'] = DrupalDateTime::createFromTimestamp($instances[$index]['end_value']);
    $values['duration'] = ($instances[$index]['end_value'] - $instances[$index]['value']) / 60;
    $element = [
      'value' => [
        '#type' => 'datetime',
      ],
    ];
    SmartDateWidgetBase::createWidget($element, $values, $defaults);

    // Add the wrapper class for the Smart Date field so JS and CSS apply.
    $element['#attributes']['class'][] = 'smartdate--widget';
    $form['override'] = $element;
    $form['#attached']['library'][] = 'smart_date/smart_date';

    // Pass in values to identify the override.
    $form['rrule'] = [
      '#type' => 'hidden',
      '#value' => $rrule
        ->id(),
    ];
    $form['rrule_index'] = [
      '#type' => 'hidden',
      '#value' => $index,
    ];
    if (!empty($instances[$index]['oid'])) {
      $form['oid'] = [
        '#type' => 'hidden',
        '#value' => $instances[$index]['oid'],
      ];
    }
    if ($ajax) {
      $form['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Save'),
        '#button_type' => 'primary',
        '#ajax' => [
          'callback' => '::ajaxSubmit',
        ],
      ];
      $cancelurl = new Url('smart_date_recur.instances', [
        'rrule' => (int) $rrule
          ->id(),
        'modal' => TRUE,
      ]);
      $form['ajaxcancel'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Cancel'),
        '#attributes' => [
          'class' => [
            'button',
            'use-ajax',
          ],
        ],
        '#url' => $cancelurl,
        '#cache' => [
          'contexts' => [
            'url.query_args:destination',
          ],
        ],
      ];
    }
    else {
      $form['actions']['#type'] = 'actions';
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Save'),
        '#button_type' => 'primary',
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // TODO: check that end > start.
    // TODO: check that values != default.
  }

  /**
   * Ajax submit function.
   *
   * @param array $form
   *   The render array of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state to submit.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The return value of the AJAX submission.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $status_messages = [
      '#type' => 'status_messages',
    ];
    $messages = \Drupal::service('renderer')
      ->renderRoot($status_messages);
    if (!empty($messages)) {
      $response
        ->addCommand(new RemoveCommand('.messages-list'));
      $response
        ->addCommand(new PrependCommand('#manage-instances', $messages));
      return $response;
    }
    $form_state
      ->disableRedirect();

    /* @var \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager */
    $entityTypeManager = \Drupal::service('entity_type.manager');

    /* @var \Drupal\smart_date_recur\Entity\SmartDateRule $rrule */
    $rrule = $entityTypeManager
      ->getStorage('smart_date_rule')
      ->load($form_state
      ->getValue('rrule'));
    $instanceController = new Instances();
    $instanceController
      ->setSmartDateRule($rrule);
    $instanceController
      ->setUseAjax(TRUE);
    $response = new AjaxResponse();
    $response
      ->addCommand(new ReplaceCommand('#manage-instances', $instanceController
      ->listInstancesOutput()));
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->override($form_state);
    if (!isset($form['ajaxcancel'])) {

      /* @var \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager */
      $entityTypeManager = \Drupal::service('entity_type.manager');

      /* @var \Drupal\smart_date_recur\Entity\SmartDateRule $rrule */
      $rrule = $entityTypeManager
        ->getStorage('smart_date_rule')
        ->load($form_state
        ->getValue('rrule'));
      $instanceController = new Instances();

      // Force refresh of parent entity.
      $instanceController
        ->applyChanges($rrule);

      // Output message about operation performed, if not using AJAX.
      $this
        ->messenger()
        ->addMessage($this
        ->t('The instance has been rescheduled.'));
    }

    // Redirect to rrule instance listing.
    $form_state
      ->setRedirect('smart_date_recur.instances', [
      'rrule' => $form_state
        ->getValue('rrule'),
    ]);
  }

  /**
   * Create or updating an override entity, this means overriding one rule item.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The provided form values.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function override(FormStateInterface $form_state) {
    if (!empty($form_state
      ->getValue('oid'))) {

      // Existing override, so retrieve and update values.
      $override = SmartDateOverride::load($form_state
        ->getValue('oid'));

      // Only the values, end_value, and duration are changeable.
      $override
        ->set('value', $form_state
        ->getValue('value')
        ->getTimestamp());
      $override
        ->set('end_value', $form_state
        ->getValue('end_value')
        ->getTimestamp());
      $override
        ->set('duration', $form_state
        ->getValue('duration'));
    }
    else {
      $values = [
        'rrule' => $form_state
          ->getValue('rrule'),
        'rrule_index' => $form_state
          ->getValue('rrule_index'),
        'value' => $form_state
          ->getValue('value')
          ->getTimestamp(),
        'end_value' => $form_state
          ->getValue('end_value')
          ->getTimestamp(),
        'duration' => $form_state
          ->getValue('duration'),
      ];

      // New override, so construct object.
      $override = SmartDateOverride::create($values);
    }
    $override
      ->save();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 105
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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.
SmartDateOverrideForm::ajaxSubmit public function Ajax submit function.
SmartDateOverrideForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
SmartDateOverrideForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SmartDateOverrideForm::override protected function Create or updating an override entity, this means overriding one rule item.
SmartDateOverrideForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
SmartDateOverrideForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.