GoogleImageSitemapDeleteConfirmForm.php in Google Image Sitemap 1.0.x
File
src/Form/GoogleImageSitemapDeleteConfirmForm.php
View source
<?php
namespace Drupal\google_image_sitemap\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Database\Connection;
use Drupal\Core\Form\ConfirmFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class GoogleImageSitemapDeleteConfirmForm extends ConfirmFormBase {
protected $connection;
private $sitemapId;
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('database'));
}
public function getFormId() {
return 'google_image_sitemap_delete_form';
}
public function getQuestion() {
return $this
->t('Are you sure you want to delete this sitemap?');
}
public function getCancelUrl() {
return new Url('google_image_sitemap.list');
}
public function buildForm(array $form, FormStateInterface $form_state, $sitemapId = NULL) {
$this->sitemapId = $sitemapId;
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$query = $this->connection
->select('google_image_sitemap', 'gis')
->fields('gis', [
'sid',
'node_type',
])
->condition('sid', $this->sitemapId);
$result = $query
->execute()
->fetch();
if (!empty($result)) {
$this->connection
->delete('google_image_sitemap')
->condition('sid', $this->sitemapId)
->execute();
$filename = $result->node_type == 'all' ? 'google_image_sitemap.xml' : 'sitemap_' . $result->node_type . '.xml';
$path = \Drupal::service('file_system')
->realpath(\Drupal::config('system.file')
->get('default_scheme') . "://") . '/google_image_sitemap/' . $filename;
if (file_exists($path)) {
file_unmanaged_delete($path);
$this
->messenger()
->addStatus($this
->t("Sitemap [@xml_file] deleted successfully!", [
'@xml_file' => $filename,
]));
}
else {
$this
->messenger()
->addStatus($this
->t("Sitemap deleted successfully!"));
}
$form_state
->setRedirectUrl($this
->getCancelUrl());
return;
}
else {
throw new NotFoundHttpException();
}
}
}