"Fossies" - the Fresh Open Source Software Archive

Member "drupal-9.1.0-rc1/core/lib/Drupal/Core/Form/form.api.php" (18 Nov 2020, 13103 Bytes) of package /linux/www/drupal-9.1.0-rc1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "form.api.php": 9.0.8_vs_9.1.0-rc1.

    1 <?php
    2 
    3 /**
    4  * @file
    5  * Callbacks and hooks related to form system.
    6  */
    7 
    8 /**
    9  * @addtogroup callbacks
   10  * @{
   11  */
   12 
   13 /**
   14  * Perform a single batch operation.
   15  *
   16  * Callback for batch_set().
   17  *
   18  * @param $multiple_params
   19  *   Additional parameters specific to the batch. These are specified in the
   20  *   array passed to batch_set().
   21  * @param array|\ArrayAccess $context
   22  *   The batch context array, passed by reference. This contains the following
   23  *   properties:
   24  *   - 'finished': A float number between 0 and 1 informing the processing
   25  *     engine of the completion level for the operation. 1 (or no value
   26  *     explicitly set) means the operation is finished: the operation will not
   27  *     be called again, and execution passes to the next operation or the
   28  *     callback_batch_finished() implementation. Any other value causes this
   29  *     operation to be called again; however it should be noted that the value
   30  *     set here does not persist between executions of this callback: each time
   31  *     it is set to 1 by default by the batch system.
   32  *   - 'sandbox': This may be used by operations to persist data between
   33  *     successive calls to the current operation. Any values set in
   34  *     $context['sandbox'] will be there the next time this function is called
   35  *     for the current operation. For example, an operation may wish to store a
   36  *     pointer in a file or an offset for a large query. The 'sandbox' array key
   37  *     is not initially set when this callback is first called, which makes it
   38  *     useful for determining whether it is the first call of the callback or
   39  *     not:
   40  *     @code
   41  *       if (empty($context['sandbox'])) {
   42  *         // Perform set-up steps here.
   43  *       }
   44  *     @endcode
   45  *     The values in the sandbox are stored and updated in the database between
   46  *     http requests until the batch finishes processing. This avoids problems
   47  *     if the user navigates away from the page before the batch finishes.
   48  *   - 'message': A text message displayed in the progress page.
   49  *   - 'results': The array of results gathered so far by the batch processing.
   50  *     This array is highly useful for passing data between operations. After
   51  *     all operations have finished, this is passed to callback_batch_finished()
   52  *     where results may be referenced to display information to the end-user,
   53  *     such as how many total items were processed.
   54  *   It is discouraged to typehint this parameter as an array, to allow an
   55  *   object implement \ArrayAccess to be passed.
   56  */
   57 function callback_batch_operation($multiple_params, &$context) {
   58   $node_storage = \Drupal::entityTypeManager()->getStorage('node');
   59   $database = \Drupal::database();
   60 
   61   if (!isset($context['sandbox']['progress'])) {
   62     $context['sandbox']['progress'] = 0;
   63     $context['sandbox']['current_node'] = 0;
   64     $context['sandbox']['max'] = $database->query('SELECT COUNT(DISTINCT [nid]) FROM {node}')->fetchField();
   65   }
   66 
   67   // For this example, we decide that we can safely process
   68   // 5 nodes at a time without a timeout.
   69   $limit = 5;
   70 
   71   // With each pass through the callback, retrieve the next group of nids.
   72   $result = $database->queryRange("SELECT [nid] FROM {node} WHERE [nid] > :nid ORDER BY [nid] ASC", 0, $limit, [':nid' => $context['sandbox']['current_node']]);
   73   foreach ($result as $row) {
   74 
   75     // Here we actually perform our processing on the current node.
   76     $node_storage->resetCache([$row['nid']]);
   77     $node = $node_storage->load($row['nid']);
   78     $node->value1 = $options1;
   79     $node->value2 = $options2;
   80     node_save($node);
   81 
   82     // Store some result for post-processing in the finished callback.
   83     $context['results'][] = $node->title;
   84 
   85     // Update our progress information.
   86     $context['sandbox']['progress']++;
   87     $context['sandbox']['current_node'] = $node->nid;
   88     $context['message'] = t('Now processing %node', ['%node' => $node->title]);
   89   }
   90 
   91   // Inform the batch engine that we are not finished,
   92   // and provide an estimation of the completion level we reached.
   93   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
   94     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
   95   }
   96 }
   97 
   98 /**
   99  * Complete a batch process.
  100  *
  101  * Callback for batch_set().
  102  *
  103  * This callback may be specified in a batch to perform clean-up operations, or
  104  * to analyze the results of the batch operations.
  105  *
  106  * @param $success
  107  *   A boolean indicating whether the batch has completed successfully.
  108  * @param $results
  109  *   The value set in $context['results'] by callback_batch_operation().
  110  * @param $operations
  111  *   If $success is FALSE, contains the operations that remained unprocessed.
  112  * @param string $elapsed
  113  *   A string representing the elapsed time for the batch process, e.g.,
  114  *   '1 min 30 secs'.
  115  */
  116 function callback_batch_finished($success, $results, $operations, $elapsed) {
  117   if ($success) {
  118     // Here we do something meaningful with the results.
  119     $message = t("@count items were processed (@elapsed).", [
  120       '@count' => count($results),
  121       '@elapsed' => $elapsed,
  122     ]);
  123     $list = [
  124       '#theme' => 'item_list',
  125       '#items' => $results,
  126     ];
  127     $message .= \Drupal::service('renderer')->render($list);
  128     \Drupal::messenger()->addStatus($message);
  129   }
  130   else {
  131     // An error occurred.
  132     // $operations contains the operations that remained unprocessed.
  133     $error_operation = reset($operations);
  134     $message = t('An error occurred while processing %error_operation with arguments: @arguments', [
  135       '%error_operation' => $error_operation[0],
  136       '@arguments' => print_r($error_operation[1], TRUE),
  137     ]);
  138     \Drupal::messenger()->addError($message);
  139   }
  140 }
  141 
  142 /**
  143  * @} End of "addtogroup callbacks".
  144  */
  145 
  146 /**
  147  * @addtogroup hooks
  148  * @{
  149  */
  150 
  151 /**
  152  * Alter the Ajax command data that is sent to the client.
  153  *
  154  * @param \Drupal\Core\Ajax\CommandInterface[] $data
  155  *   An array of all the rendered commands that will be sent to the client.
  156  */
  157 function hook_ajax_render_alter(array &$data) {
  158   // Inject any new status messages into the content area.
  159   $status_messages = ['#type' => 'status_messages'];
  160   $command = new \Drupal\Core\Ajax\PrependCommand('#block-system-main .content', \Drupal::service('renderer')->renderRoot($status_messages));
  161   $data[] = $command->render();
  162 }
  163 
  164 /**
  165  * Perform alterations before a form is rendered.
  166  *
  167  * One popular use of this hook is to add form elements to the node form. When
  168  * altering a node form, the node entity can be retrieved by invoking
  169  * $form_state->getFormObject()->getEntity().
  170  *
  171  * Implementations are responsible for adding cache contexts/tags/max-age as
  172  * needed. See https://www.drupal.org/developing/api/8/cache.
  173  *
  174  * In addition to hook_form_alter(), which is called for all forms, there are
  175  * two more specific form hooks available. The first,
  176  * hook_form_BASE_FORM_ID_alter(), allows targeting of a form/forms via a base
  177  * form (if one exists). The second, hook_form_FORM_ID_alter(), can be used to
  178  * target a specific form directly.
  179  *
  180  * The call order is as follows: all existing form alter functions are called
  181  * for module A, then all for module B, etc., followed by all for any base
  182  * theme(s), and finally for the theme itself. The module order is determined
  183  * by system weight, then by module name.
  184  *
  185  * Within each module, form alter hooks are called in the following order:
  186  * first, hook_form_alter(); second, hook_form_BASE_FORM_ID_alter(); third,
  187  * hook_form_FORM_ID_alter(). So, for each module, the more general hooks are
  188  * called first followed by the more specific.
  189  *
  190  * @param $form
  191  *   Nested array of form elements that comprise the form.
  192  * @param $form_state
  193  *   The current state of the form. The arguments that
  194  *   \Drupal::formBuilder()->getForm() was originally called with are available
  195  *   in the array $form_state->getBuildInfo()['args'].
  196  * @param $form_id
  197  *   String representing the name of the form itself. Typically this is the
  198  *   name of the function that generated the form.
  199  *
  200  * @see hook_form_BASE_FORM_ID_alter()
  201  * @see hook_form_FORM_ID_alter()
  202  *
  203  * @ingroup form_api
  204  */
  205 function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  206   if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
  207     $upload_enabled_types = \Drupal::config('mymodule.settings')->get('upload_enabled_types');
  208     $form['workflow']['upload_' . $form['type']['#value']] = [
  209       '#type' => 'radios',
  210       '#title' => t('Attachments'),
  211       '#default_value' => in_array($form['type']['#value'], $upload_enabled_types) ? 1 : 0,
  212       '#options' => [t('Disabled'), t('Enabled')],
  213     ];
  214     // Add a custom submit handler to save the array of types back to the config file.
  215     $form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';
  216   }
  217 }
  218 
  219 /**
  220  * Provide a form-specific alteration instead of the global hook_form_alter().
  221  *
  222  * Implementations are responsible for adding cache contexts/tags/max-age as
  223  * needed. See https://www.drupal.org/developing/api/8/cache.
  224  *
  225  * Modules can implement hook_form_FORM_ID_alter() to modify a specific form,
  226  * rather than implementing hook_form_alter() and checking the form ID, or
  227  * using long switch statements to alter multiple forms.
  228  *
  229  * Form alter hooks are called in the following order: hook_form_alter(),
  230  * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  231  * hook_form_alter() for more details.
  232  *
  233  * @param $form
  234  *   Nested array of form elements that comprise the form.
  235  * @param $form_state
  236  *   The current state of the form. The arguments that
  237  *   \Drupal::formBuilder()->getForm() was originally called with are available
  238  *   in the array $form_state->getBuildInfo()['args'].
  239  * @param $form_id
  240  *   String representing the name of the form itself. Typically this is the
  241  *   name of the function that generated the form.
  242  *
  243  * @see hook_form_alter()
  244  * @see hook_form_BASE_FORM_ID_alter()
  245  * @see \Drupal\Core\Form\FormBuilderInterface::prepareForm()
  246  *
  247  * @ingroup form_api
  248  */
  249 function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  250   // Modification for the form with the given form ID goes here. For example, if
  251   // FORM_ID is "user_register_form" this code would run only on the user
  252   // registration form.
  253 
  254   // Add a checkbox to registration form about agreeing to terms of use.
  255   $form['terms_of_use'] = [
  256     '#type' => 'checkbox',
  257     '#title' => t("I agree with the website's terms and conditions."),
  258     '#required' => TRUE,
  259   ];
  260 }
  261 
  262 /**
  263  * Provide a form-specific alteration for shared ('base') forms.
  264  *
  265  * Implementations are responsible for adding cache contexts/tags/max-age as
  266  * needed. See https://www.drupal.org/developing/api/8/cache.
  267  *
  268  * By default, when \Drupal::formBuilder()->getForm() is called, Drupal looks
  269  * for a function with the same name as the form ID, and uses that function to
  270  * build the form. In contrast, base forms allow multiple form IDs to be mapped
  271  * to a single base (also called 'factory') form function.
  272  *
  273  * Modules can implement hook_form_BASE_FORM_ID_alter() to modify a specific
  274  * base form, rather than implementing hook_form_alter() and checking for
  275  * conditions that would identify the shared form constructor.
  276  *
  277  * To identify the base form ID for a particular form (or to determine whether
  278  * one exists) check the $form_state. The base form ID is stored under
  279  * $form_state->getBuildInfo()['base_form_id'].
  280  *
  281  * Form alter hooks are called in the following order: hook_form_alter(),
  282  * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  283  * hook_form_alter() for more details.
  284  *
  285  * @param $form
  286  *   Nested array of form elements that comprise the form.
  287  * @param $form_state
  288  *   The current state of the form.
  289  * @param $form_id
  290  *   String representing the name of the form itself. Typically this is the
  291  *   name of the function that generated the form.
  292  *
  293  * @see hook_form_alter()
  294  * @see hook_form_FORM_ID_alter()
  295  * @see \Drupal\Core\Form\FormBuilderInterface::prepareForm()
  296  *
  297  * @ingroup form_api
  298  */
  299 function hook_form_BASE_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  300   // Modification for the form with the given BASE_FORM_ID goes here. For
  301   // example, if BASE_FORM_ID is "node_form", this code would run on every
  302   // node form, regardless of node type.
  303 
  304   // Add a checkbox to the node form about agreeing to terms of use.
  305   $form['terms_of_use'] = [
  306     '#type' => 'checkbox',
  307     '#title' => t("I agree with the website's terms and conditions."),
  308     '#required' => TRUE,
  309   ];
  310 }
  311 
  312 /**
  313  * Alter batch information before a batch is processed.
  314  *
  315  * Called by batch_process() to allow modules to alter a batch before it is
  316  * processed.
  317  *
  318  * @param $batch
  319  *   The associative array of batch information. See batch_set() for details on
  320  *   what this could contain.
  321  *
  322  * @see batch_set()
  323  * @see batch_process()
  324  *
  325  * @ingroup batch
  326  */
  327 function hook_batch_alter(&$batch) {
  328 }
  329 
  330 /**
  331  * @} End of "addtogroup hooks".
  332  */