class CronExampleForm
Same name in other branches
- 8.x-1.x cron_example/src/Form/CronExampleForm.php \Drupal\cron_example\Form\CronExampleForm
- 4.0.x modules/cron_example/src/Form/CronExampleForm.php \Drupal\cron_example\Form\CronExampleForm
Form with examples on how to use cron.
Hierarchy
- class \Drupal\Core\Form\FormBase implements \Drupal\Core\Form\FormInterface, \Drupal\Core\DependencyInjection\ContainerInjectionInterface uses \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Logger\LoggerChannelTrait, \Drupal\Core\Messenger\MessengerTrait, \Drupal\Core\Routing\RedirectDestinationTrait, \Drupal\Core\StringTranslation\StringTranslationTrait
- class \Drupal\Core\Form\ConfigFormBase extends \Drupal\Core\Form\FormBase uses \Drupal\Core\Form\ConfigFormBaseTrait
- class \Drupal\cron_example\Form\CronExampleForm extends \Drupal\Core\Form\ConfigFormBase
- class \Drupal\Core\Form\ConfigFormBase extends \Drupal\Core\Form\FormBase uses \Drupal\Core\Form\ConfigFormBaseTrait
Expanded class hierarchy of CronExampleForm
1 string reference to 'CronExampleForm'
- cron_example.routing.yml in modules/
cron_example/ cron_example.routing.yml - modules/cron_example/cron_example.routing.yml
File
-
modules/
cron_example/ src/ Form/ CronExampleForm.php, line 18
Namespace
Drupal\cron_example\FormView source
class CronExampleForm extends ConfigFormBase {
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The cron service.
*
* @var \Drupal\Core\CronInterface
*/
protected $cron;
/**
* The queue factory.
*
* @var \Drupal\Core\Queue\QueueFactory
*/
protected $queue;
/**
* The state keyvalue collection.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* Constructs new CronExampleForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\CronInterface $cron
* The cron service.
* @param \Drupal\Core\Queue\QueueFactory $queue
* The queue factory.
* @param \Drupal\Core\State\StateInterface $state
* The state keyvalue collection.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
*/
public function __construct(ConfigFactoryInterface $config_factory, AccountInterface $current_user, CronInterface $cron, QueueFactory $queue, StateInterface $state, TimeInterface $time) {
parent::__construct($config_factory);
$this->currentUser = $current_user;
$this->cron = $cron;
$this->queue = $queue;
$this->state = $state;
$this->time = $time;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$form = new static($container->get('config.factory'), $container->get('current_user'), $container->get('cron'), $container->get('queue'), $container->get('state'), $container->get('datetime.time'));
$form->setMessenger($container->get('messenger'));
return $form;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'cron_example';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('cron_example.settings');
$form['status'] = [
'#type' => 'details',
'#title' => $this->t('Cron status information'),
'#open' => TRUE,
];
$form['status']['intro'] = [
'#type' => 'item',
'#markup' => $this->t('The cron example demonstrates hook_cron() and hook_queue_info() processing. If you have administrative privileges you can run cron from this page and see the results.'),
];
$next_execution = $this->state
->get('cron_example.next_execution');
$request_time = $this->time
->getRequestTime();
$next_execution = !empty($next_execution) ? $next_execution : $request_time;
$args = [
'%time' => date('c', $this->state
->get('cron_example.next_execution')),
'%seconds' => $next_execution - $request_time,
];
$form['status']['last'] = [
'#type' => 'item',
'#markup' => $this->t('cron_example_cron() will next execute the first time cron runs after %time (%seconds seconds from now)', $args),
];
if ($this->currentUser
->hasPermission('administer site configuration')) {
$form['cron_run'] = [
'#type' => 'details',
'#title' => $this->t('Run cron manually'),
'#open' => TRUE,
];
$form['cron_run']['cron_reset'] = [
'#type' => 'checkbox',
'#title' => $this->t("Run cron_example's cron regardless of whether interval has expired."),
'#default_value' => FALSE,
];
$form['cron_run']['cron_trigger']['actions'] = [
'#type' => 'actions',
];
$form['cron_run']['cron_trigger']['actions']['sumbit'] = [
'#type' => 'submit',
'#value' => $this->t('Run cron now'),
'#submit' => [
[
$this,
'cronRun',
],
],
];
}
$form['cron_queue_setup'] = [
'#type' => 'details',
'#title' => $this->t('Cron queue setup (for hook_cron_queue_info(), etc.)'),
'#open' => TRUE,
];
$queue_1 = $this->queue
->get('cron_example_queue_1');
$queue_2 = $this->queue
->get('cron_example_queue_2');
$args = [
'%queue_1' => $queue_1->numberOfItems(),
'%queue_2' => $queue_2->numberOfItems(),
];
$form['cron_queue_setup']['current_cron_queue_status'] = [
'#type' => 'item',
'#markup' => $this->t('There are currently %queue_1 items in queue 1 and %queue_2 items in queue 2', $args),
];
$form['cron_queue_setup']['num_items'] = [
'#type' => 'select',
'#title' => $this->t('Number of items to add to queue'),
'#options' => array_combine([
1,
5,
10,
100,
1000,
], [
1,
5,
10,
100,
1000,
]),
'#default_value' => 5,
];
$form['cron_queue_setup']['queue'] = [
'#type' => 'radios',
'#title' => $this->t('Queue to add items to'),
'#options' => [
'cron_example_queue_1' => $this->t('Queue 1'),
'cron_example_queue_2' => $this->t('Queue 2'),
],
'#default_value' => 'cron_example_queue_1',
];
$form['cron_queue_setup']['actions'] = [
'#type' => 'actions',
];
$form['cron_queue_setup']['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add jobs to queue'),
'#submit' => [
[
$this,
'addItems',
],
],
];
$form['configuration'] = [
'#type' => 'details',
'#title' => $this->t('Configuration of cron_example_cron()'),
'#open' => TRUE,
];
$form['configuration']['cron_example_interval'] = [
'#type' => 'select',
'#title' => $this->t('Cron interval'),
'#description' => $this->t('Time after which cron_example_cron will respond to a processing request.'),
'#default_value' => $config->get('interval'),
'#options' => [
60 => $this->t('1 minute'),
300 => $this->t('5 minutes'),
3600 => $this->t('1 hour'),
86400 => $this->t('1 day'),
],
];
return parent::buildForm($form, $form_state);
}
/**
* Allow user to directly execute cron, optionally forcing it.
*/
public function cronRun(array &$form, FormStateInterface &$form_state) {
$cron_reset = $form_state->getValue('cron_reset');
if (!empty($cron_reset)) {
$this->state
->set('cron_example.next_execution', 0);
}
// Use a state variable to signal that cron was run manually from this form.
$this->state
->set('cron_example_show_status_message', TRUE);
if ($this->cron
->run()) {
$this->messenger()
->addMessage($this->t('Cron ran successfully.'));
}
else {
$this->messenger()
->addError($this->t('Cron run failed.'));
}
}
/**
* Add the items to the queue when signaled by the form.
*/
public function addItems(array &$form, FormStateInterface &$form_state) {
$values = $form_state->getValues();
$queue_name = $form['cron_queue_setup']['queue'][$values['queue']]['#title'];
$num_items = $form_state->getValue('num_items');
// Queues are defined by a QueueWorker Plugin which are selected by their
// id attritbute.
// @see \Drupal\cron_example\Plugin\QueueWorker\ReportWorkerOne
$queue = $this->queue
->get($values['queue']);
$request_time = $this->time
->getRequestTime();
for ($i = 1; $i <= $num_items; $i++) {
// Create a new item, a new data object, which is passed to the
// QueueWorker's processItem() method.
$item = new \stdClass();
$item->created = $request_time;
$item->sequence = $i;
$queue->createItem($item);
}
$args = [
'%num' => $num_items,
'%queue' => $queue_name,
];
$this->messenger()
->addMessage($this->t('Added %num items to %queue', $args));
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Update the interval as stored in configuration. This will be read when
// this modules hook_cron function fires and will be used to ensure that
// action is taken only after the appropiate time has elapsed.
$this->config('cron_example.settings')
->set('interval', $form_state->getValue('cron_example_interval'))
->save();
parent::submitForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'cron_example.settings',
];
}
}
Members
Title Sort descending | Modifiers | Object type | Summary | Overriden Title | Overrides |
---|---|---|---|---|---|
ConfigFormBaseTrait::config | protected | function | Retrieves a configuration object. | ||
CronExampleForm::$cron | protected | property | The cron service. | ||
CronExampleForm::$currentUser | protected | property | The current user. | ||
CronExampleForm::$queue | protected | property | The queue factory. | ||
CronExampleForm::$state | protected | property | The state keyvalue collection. | ||
CronExampleForm::$time | protected | property | The time service. | ||
CronExampleForm::addItems | public | function | Add the items to the queue when signaled by the form. | ||
CronExampleForm::buildForm | public | function | Form constructor. | Overrides ConfigFormBase::buildForm | |
CronExampleForm::create | public static | function | Instantiates a new instance of this class. | Overrides ConfigFormBase::create | |
CronExampleForm::cronRun | public | function | Allow user to directly execute cron, optionally forcing it. | ||
CronExampleForm::getEditableConfigNames | protected | function | Gets the configuration names that will be editable. | Overrides ConfigFormBaseTrait::getEditableConfigNames | |
CronExampleForm::getFormId | public | function | Returns a unique string identifying the form. | Overrides FormInterface::getFormId | |
CronExampleForm::submitForm | public | function | Form submission handler. | Overrides ConfigFormBase::submitForm | |
CronExampleForm::__construct | public | function | Constructs new CronExampleForm object. | Overrides ConfigFormBase::__construct | |
DependencySerializationTrait::$_entityStorages | protected | property | |||
DependencySerializationTrait::$_serviceIds | protected | property | |||
DependencySerializationTrait::__sleep | public | function | 1 | ||
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::configFactory | protected | function | Gets the config factory for this form. | 3 | |
FormBase::container | private | function | Returns the service container. | ||
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. | ||
FormBase::validateForm | public | function | Form validation handler. | Overrides FormInterface::validateForm | 73 |
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. | 17 | |
MessengerTrait::messenger | public | function | Gets the messenger. | 17 | |
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. | ||
StringTranslationTrait::$stringTranslation | protected | property | The string translation service. | 3 | |
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. |