ConditionDeleteForm.php in Context 8.4        
                          
                  
                        
  
  
  
  
File
  modules/context_ui/src/Form/ConditionDeleteForm.php
  
    View source  
  <?php
namespace Drupal\context_ui\Form;
use Drupal\context\ContextManager;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\context\ContextInterface;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ConditionDeleteForm extends ConfirmFormBase {
  
  protected $context;
  
  protected $condition;
  
  protected $contextManager;
  
  public function __construct(ContextManager $contextManager) {
    $this->contextManager = $contextManager;
  }
  
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('context.manager'));
  }
  
  public function getFormId() {
    return 'context_ui_condition_delete_form';
  }
  
  public function getQuestion() {
    return $this
      ->t('Are you sure you want to delete the %label condition?', [
      '%label' => $this->condition
        ->getPluginDefinition()['label'],
    ]);
  }
  
  public function getCancelUrl() {
    return $this->context
      ->toUrl('edit-form');
  }
  
  public function getConfirmText() {
    return $this
      ->t('Delete');
  }
  
  public function buildForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL, $condition_id = NULL) {
    $this->context = $context;
    $this->condition = $context
      ->getCondition($condition_id);
    $form = parent::buildForm($form, $form_state);
    
    if ($this
      ->getRequest()
      ->isXmlHttpRequest()) {
      unset($form['actions']['cancel']);
    }
    
    $form['actions']['submit']['#ajax'] = [
      'callback' => '::submitFormAjax',
    ];
    return $form;
  }
  
  public function submitForm(array &$form, FormStateInterface $form_state) {
    
    $this->context
      ->removeCondition($this->condition
      ->getConfiguration()['id'])
      ->save();
    
    if (!$this
      ->getRequest()
      ->isXmlHttpRequest()) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The condition %name has been removed.', [
        '%name' => $this->condition
          ->getPluginDefinition()['label'],
      ]));
      $form_state
        ->setRedirectUrl($this
        ->getCancelUrl());
    }
  }
  
  public function submitFormAjax() {
    $contextForm = $this->contextManager
      ->getForm($this->context, 'edit');
    $response = new AjaxResponse();
    $response
      ->addCommand(new CloseModalDialogCommand());
    $response
      ->addCommand(new ReplaceCommand('#context-conditions', $contextForm['conditions']));
    return $response;
  }
}