You are here

class BatchExampleForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/batch_example/src/Form/BatchExampleForm.php \Drupal\batch_example\Form\BatchExampleForm

Form with examples on how to use cache.

Hierarchy

Expanded class hierarchy of BatchExampleForm

1 string reference to 'BatchExampleForm'
batch_example.routing.yml in batch_example/batch_example.routing.yml
batch_example/batch_example.routing.yml

File

batch_example/src/Form/BatchExampleForm.php, line 11

Namespace

Drupal\batch_example\Form
View source
class BatchExampleForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'batch_example_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = [
      '#type' => 'markup',
      '#markup' => $this
        ->t('This example offers two different batches. The first does 1000 identical operations, each completed in on run; the second does 20 operations, but each takes more than one run to operate if there are more than 5 nodes.'),
    ];
    $form['batch'] = [
      '#type' => 'select',
      '#title' => 'Choose batch',
      '#options' => [
        'batch_1' => $this
          ->t('batch 1 - 1000 operations'),
        'batch_2' => $this
          ->t('batch 2 - 20 operations.'),
      ],
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Go',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Gather our form value.
    $value = $form_state
      ->getValues()['batch'];

    // Set the batch, using convenience methods.
    $batch = [];
    switch ($value) {
      case 'batch_1':
        $batch = $this
          ->generateBatch1();
        break;
      case 'batch_2':
        $batch = $this
          ->generateBatch2();
        break;
    }
    batch_set($batch);
  }

  /**
   * Generate Batch 1.
   *
   * Batch 1 will process one item at a time.
   *
   * This creates an operations array defining what batch 1 should do, including
   * what it should do when it's finished. In this case, each operation is the
   * same and by chance even has the same $nid to operate on, but we could have
   * a mix of different types of operations in the operations array.
   */
  public function generateBatch1() {
    $num_operations = 1000;
    $this
      ->messenger()
      ->addMessage($this
      ->t('Creating an array of @num operations', [
      '@num' => $num_operations,
    ]));
    $operations = [];

    // Set up an operations array with 1000 elements, each doing function
    // batch_example_op_1.
    // Each operation in the operations array means at least one new HTTP
    // request, running Drupal from scratch to accomplish the operation. If the
    // operation returns with $context['finished'] != TRUE, then it will be
    // called again.
    // In this example, $context['finished'] is always TRUE.
    for ($i = 0; $i < $num_operations; $i++) {

      // Each operation is an array consisting of
      // - The function to call.
      // - An array of arguments to that function.
      $operations[] = [
        'batch_example_op_1',
        [
          $i + 1,
          $this
            ->t('(Operation @operation)', [
            '@operation' => $i,
          ]),
        ],
      ];
    }
    $batch = [
      'title' => $this
        ->t('Creating an array of @num operations', [
        '@num' => $num_operations,
      ]),
      'operations' => $operations,
      'finished' => 'batch_example_finished',
    ];
    return $batch;
  }

  /**
   * Generate Batch 2.
   *
   * Batch 2 will process five items at a time.
   *
   * This creates an operations array defining what batch 2 should do, including
   * what it should do when it's finished. In this case, each operation is the
   * same and by chance even has the same $nid to operate on, but we could have
   * a mix of different types of operations in the operations array.
   */
  public function generateBatch2() {
    $num_operations = 20;
    $operations = [];

    // 20 operations, each one loads all nodes.
    for ($i = 0; $i < $num_operations; $i++) {
      $operations[] = [
        'batch_example_op_2',
        [
          $this
            ->t('(Operation @operation)', [
            '@operation' => $i,
          ]),
        ],
      ];
    }
    $batch = [
      'operations' => $operations,
      'finished' => 'batch_example_finished',
      // @current, @remaining, @total, @percentage, @estimate and @elapsed.
      // These placeholders are replaced with actual values in _batch_process(),
      // using strtr() instead of t(). The values are determined based on the
      // number of operations in the 'operations' array (above), NOT by the
      // number of nodes that will be processed. In this example, there are 20
      // operations, so @total will always be 20, even though there are multiple
      // nodes per operation.
      // Defaults to t('Completed @current of @total.').
      'title' => $this
        ->t('Processing batch 2'),
      'init_message' => $this
        ->t('Batch 2 is starting.'),
      'progress_message' => $this
        ->t('Processed @current out of @total.'),
      'error_message' => $this
        ->t('Batch 2 has encountered an error.'),
    ];
    return $batch;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BatchExampleForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
BatchExampleForm::generateBatch1 public function Generate Batch 1.
BatchExampleForm::generateBatch2 public function Generate Batch 2.
BatchExampleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BatchExampleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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. Overrides UrlGeneratorTrait::redirect
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 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.