TableDragExampleResetForm.php
View source
<?php
namespace Drupal\tabledrag_example\Form;
use Drupal\Core\Database\Connection;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\tabledrag_example\Fixtures;
use Symfony\Component\DependencyInjection\ContainerInterface;
class TableDragExampleResetForm extends ConfirmFormBase {
protected $database;
public static function create(ContainerInterface $container) {
return new static($container->get('database'));
}
public function __construct(Connection $database) {
$this->database = $database;
}
public function getFormId() {
return 'tabledrag_example_reset';
}
public function getQuestion() {
return $this->t('Reset demo data for TableDrag Example');
}
public function getCancelUrl() {
return new Url('tabledrag_example.description');
}
public function getDescription() {
return $this->t('Are you sure you want to reset demo data?');
}
public function getConfirmText() {
return $this->t('Yes, Reset It!');
}
public function getCancelText() {
return $this->t('Cancel');
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$data = Fixtures::getSampleItems();
foreach ($data as $id => $item) {
$id++;
$this->database
->update('tabledrag_example')
->fields([
'weight' => 0,
'pid' => 0,
'description' => $item['description'],
'itemgroup' => $item['itemgroup'],
])
->condition('id', $id, '=')
->execute();
}
$this->messenger()
->addMessage($this->t('Data for TableDrag Example has been reset.'), 'status');
$form_state->setRedirect('tabledrag_example.description');
}
}