SmartDateRemoveInstanceForm.php in Smart Date 3.x
File
modules/smart_date_recur/src/Form/SmartDateRemoveInstanceForm.php
View source
<?php
namespace Drupal\smart_date_recur\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\smart_date_recur\Controller\Instances;
use Drupal\smart_date_recur\Entity\SmartDateOverride;
use Drupal\smart_date_recur\Entity\SmartDateRule;
class SmartDateRemoveInstanceForm extends ConfirmFormBase {
protected $rrule;
protected $index;
protected $oid;
public function getFormId() {
return "smart_date_recur_remove_form";
}
public function buildForm(array $form, FormStateInterface $form_state, SmartDateRule $rrule = NULL, string $index = NULL, $ajax = FALSE) {
$this->rrule = $rrule;
$this->index = $index;
$result = \Drupal::entityQuery('smart_date_override')
->condition('rrule', $rrule
->id())
->condition('rrule_index', $index)
->execute();
if ($result && ($override = SmartDateOverride::load(array_pop($result)))) {
$this->oid = $override
->id();
}
$form = parent::buildForm($form, $form_state);
if ($ajax) {
$this
->addAjaxWrapper($form);
$form['actions']['cancel']['#attributes']['class'][] = 'use-ajax';
$form['actions']['cancel']['#url']
->setRouteParameter('modal', TRUE);
$form['actions']['submit']['#ajax'] = [
'callback' => '::ajaxSubmit',
];
}
return $form;
}
public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
$form_state
->disableRedirect();
$instanceController = new Instances();
$instanceController
->setSmartDateRule($this->rrule);
$instanceController
->setUseAjax(TRUE);
$instanceController
->setUpdateButton(FALSE);
$response = new AjaxResponse();
$response
->addCommand(new ReplaceCommand('#manage-instances', $instanceController
->listInstancesOutput()));
return $response;
}
protected function addAjaxWrapper(array &$form) {
$form['#prefix'] = '<div id="manage-instances">';
$form['#suffix'] = '</div>';
}
public function getQuestion() {
$question = $this
->t('Are you sure you want to remove this instance?');
if ($this->oid) {
$question .= ' ' . $this
->t('Your existing overridden data will be deleted.');
}
return $question;
}
public function getCancelUrl() {
$rrule = $this->rrule
->id();
return new Url('smart_date_recur.instances', [
'rrule' => $rrule,
]);
}
public function getConfirmText() {
return $this
->t('Remove Instance');
}
public function getDescription() {
return $this
->t('You will be able to restore the instance if necessary.');
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$instanceController = new Instances();
$instanceController
->setSmartDateRule($this->rrule);
$instanceController
->removeInstance($this->index, $this->oid);
$form_state
->setRedirectUrl($this
->getCancelUrl());
}
}