foldershare-8.x-1.2/src/Form/CommandFormWrapper.php
src/Form/CommandFormWrapper.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 | <?php namespace Drupal\foldershare\Form; use Drupal\Core\Url; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\CloseModalDialogCommand; use Drupal\Core\Ajax\InvokeCommand; use Drupal\Core\Ajax\RedirectCommand; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\foldershare\Constants; use Drupal\foldershare\Utilities\FormatUtilities; use Drupal\foldershare\Plugin\FolderShareCommandManager; use Drupal\foldershare\Plugin\FolderShareCommand\FolderShareCommandInterface; use Drupal\foldershare\Ajax\OpenErrorDialogCommand; use Drupal\foldershare\Entity\Exception\RuntimeExceptionWithMarkup; /** * Creates a form that wraps a command plugin to prompt for its parameters. * * This form is invoked to prompt the user for additional plugin * command-specific parameters, beyond primary parameters for the parent * folder (if any), destination folder (if any), and selection (if any). * Each plugin has its own (optional) form fragment that prompts for its * parameters. This form page incorporates that fragment and adds a * page title and submit button. It further orchestrates creation of * the plugin and invokation of its functions. * * The form page accepts a URL with a single required 'encoded' parameter * that includes a base64-encoded JSON-encoded associative array that * has the plugin ID, configuration (parent, destination, selection), * and URL to get back to the invoking page. * * <B>Warning:</B> This class is strictly internal to the FolderShare * module. The class's existance, name, and content may change from * release to release without any promise of backwards compatability. * * @ingroup foldershare */ class CommandFormWrapper extends FormBase { /*-------------------------------------------------------------------- * * Fields - cached from dependency injection. * *--------------------------------------------------------------------*/ /** * The plugin manager for folder shared commands. * * @var \Drupal\foldershare\FolderShareCommand\FolderShareCommandManager */ protected $commandPluginManager ; /** * The command's plugin ID from command parameters. * * The plugin ID is a unique string that identifies the plugin within * the set of loaded plugins in the plugin manager. * * @var string */ protected $pluginId ; /** * An instance of the command plugin. * * The command instance is created using the plugin ID from the * URL parameters. * * @var \Drupal\foldershare\FolderShareCommand\FolderShareCommandInterface */ protected $command ; /** * The URL to redirect to (or back to) after form submission. * * The URL comes from the command parameters and indicates the original * page to return to after the command executes. * * @var string */ protected $url ; /** * The parent form ID that triggered the command. * * The parent form ID comes from the command parameters and indicates the * parent form ID that triggered the command. This is used to direct an * AJAX refresh back to that form when the command finishes. * * @var string */ protected $parentFormId ; /** * Whether to enable AJAX. * * The flag comes from the command parameters given to buildForm(). * By default, this is FALSE, but it can be set TRUE if the caller * sets the flag in the parameters. This would be the case if the * caller has embedded the form within an AJAX dialog and therefore * requires that this form continue to use AJAX as well. * * @var bool */ protected $enableAjax ; /*-------------------------------------------------------------------- * * Construction. * *--------------------------------------------------------------------*/ /** * Constructs a new form. * * @param \Drupal\foldershare\FolderShareCommand\FolderShareCommandManager $commandPluginManager * The command plugin manager. */ public function __construct(FolderShareCommandManager $commandPluginManager ) { // Save the plugin manager, which we'll need to create a plugin // instance based upon a parameter on the form's URL. $this ->commandPluginManager = $commandPluginManager ; $this ->enableAjax = TRUE; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container ) { return new static ( $container ->get( 'foldershare.plugin.manager.foldersharecommand' ) ); } /*-------------------------------------------------------------------- * * Form setup. * *--------------------------------------------------------------------*/ /** * {@inheritdoc} */ public function getFormId() { return str_replace ( '\\' , '_' , get_class( $this )); } /*-------------------------------------------------------------------- * * Form build. * *--------------------------------------------------------------------*/ /** * {@inheritdoc} */ public function buildForm( array $form , FormStateInterface $formState = NULL, string $encoded = NULL) { // // Decode parameters. // ------------------ // Decode the incoming URL's parameters, which include: // - The command plugin's ID. // - The configuration for that command, including a selection, parent, // destination, etc. // - The URL of the page to return to. // - Whethe AJAX is enabled. $parameters = $this ->decodeParameters( $encoded ); if ( empty ( $parameters ) === TRUE) { return $form ; } $this ->pluginId = $parameters [ 'pluginId' ]; $configuration = $parameters [ 'configuration' ]; $this ->url = $parameters [ 'url' ]; $this ->parentFormId = $parameters [ 'parentFormId' ]; if (isset( $parameters [ 'enableAjax' ]) === TRUE) { $this ->enableAjax = $parameters [ 'enableAjax' ]; } else { $this ->enableAjax = FALSE; } $forPage = ( $this ->enableAjax === FALSE); // // Instantiate plugin. // ------------------- // The plugin ID gives us the name of the plugin. Create one and pass // in the configuration. This initializes the plugin's internal // structure, but does not validate or execute it. The plugin's form // below may prompt the user for additional configuration values. $this ->command = $this ->commandPluginManager->createInstance( $this ->pluginId, $configuration ); $def = $this ->command->getPluginDefinition(); // // Pre-validate. // ------------- // The invoker of this form should already have checked that the // parent and selection are valid for this command. But validate // again now to insure that internal cached values from validation // are set before we continue. If validation fails, there is no // point in building much of a form. try { $this ->command->validateParentConstraints(); $this ->command->validateSelectionConstraints(); } catch (RuntimeExceptionWithMarkup $e ) { $this ->messenger()->addMessage( $e ->getMarkup(), 'error' ); return NULL; } catch (\Exception $e ) { $this ->messenger()->addMessage( $e ->getMessage(), 'error' ); return NULL; } // // Set up form. // ------------ // The command provides its own form fragment to prompt for the // values it needs to complete its configuration. $commandFormWrapper = Constants::MODULE . '_command_form_wrapper' ; $form [ '#prefix' ] = '<div id="' . $commandFormWrapper . '">' ; $form [ '#suffix' ] = '</div>' ; // Attach libraries. $form [ '#attached' ][ 'library' ][] = Constants::LIBRARY_MODULE; $form [ '#attributes' ][ 'class' ][] = $def [ 'id' ]; $form [ '#attributes' ][ 'class' ][] = 'foldershare-dialog' ; // Mark form as tree-structured and non-collapsable. $form [ '#tree' ] = TRUE; // // Set the page title, if any. // --------------------------- // Get the command's page title. This may vary based on whether the // form is in a stand-alone page or in a dialog. The title may be empty. $form [ '#title' ] = $this ->command->getTitle( $forPage ); // // Set the description, if any. // ---------------------------- // Get the command's description. This may vary based on whether the // form is in a stand-alone page or in a dialog. $description = $this ->command->getDescription( $forPage ); if ( empty ( $description ) === FALSE) { if ( is_array ( $description ) === FALSE) { $primaryDescription = $description ; $secondaryDescription = '' ; } elseif ( count ( $description ) === 1) { $primaryDescription = $description [0]; $secondaryDescription = '' ; } else { $primaryDescription = $description [0]; $secondaryDescription = $description [1]; } if ( empty ( $primaryDescription ) === FALSE) { $form [ 'primary-description' ] = [ '#type' => 'html_tag' , '#name' => 'primary-description' , '#weight' => -100, '#tag' => 'p' , '#value' => $primaryDescription , '#attributes' => [ 'class' => [ 'foldershare-primary-description' , ], ], ]; } if ( empty ( $secondaryDescription ) === FALSE) { $form [ 'secondary-description' ] = [ '#type' => 'html_tag' , '#name' => 'secondary-description' , '#weight' => -99, '#tag' => 'p' , '#value' => $secondaryDescription , '#attributes' => [ 'class' => [ 'foldershare-secondary-description' , ], ], ]; } } // // Add actions. // ------------ // Add the submit button. $form [ 'actions' ] = [ '#type' => 'actions' , '#weight' => 1000, 'submit' => [ '#type' => 'submit' , '#name' => 'submit' , '#value' => $this ->command->getSubmitButtonName(), '#button_type' => 'primary' , ], ]; // When AJAX is enabled, add an AJAX callback to the submit button // and a cancel button. if ( $this ->enableAjax === TRUE) { $form [ 'actions' ][ 'cancel' ] = [ '#type' => 'button' , '#name' => 'cancel' , '#value' => $this ->t( 'Cancel' ), '#attributes' => [ 'class' => [ // Marking the button with "dialog-cancel" marks the button as // a cancel button that simply closes the dialog, without sending // anything to the server. 'dialog-cancel' , ], ], ]; $form [ 'actions' ][ 'submit' ][ '#ajax' ] = [ 'callback' => [ $this , 'submitFormAjax' ], 'event' => 'click' , 'wrapper' => $commandFormWrapper , 'disable-refocus' => TRUE, 'url' => Url::fromRoute( 'entity.foldersharecommand.plugin' , [ 'encoded' => base64_encode (json_encode( $parameters )), ]), 'options' => [ 'query' => [ 'ajax_form' => 1, ], ], 'progress' => [ 'type' => 'none' , ], ]; } // // Add command form. // ----------------- // Add the command's form. $form = $this ->command->buildConfigurationForm( $form , $formState ); return $form ; } /*-------------------------------------------------------------------- * * Form validate. * *--------------------------------------------------------------------*/ /** * {@inheritdoc} */ public function validateForm( array & $form , FormStateInterface $formState ) { // Validate the user's input for the form by passing them to the // command to validate. if ( $this ->command === NULL) { // Fail. No command? return ; } // // Validate additions // ------------------ // Let the command's form validate the user's input. $this ->command->validateConfigurationForm( $form , $formState ); if ( $formState ->hasAnyErrors() === TRUE) { // The command's validation failed. There is no point in continuing. return ; } if ( $formState ->isRebuilding() === TRUE) { // The command directs that the form should be rebuilt and form use // should continue. return ; } // // Validate rest // ------------- // The command's configuration form should have validated whatever // additional parameters it has added. And earlier we validated the // parent and selection. But just to be sure, validate everything // one last time. Since validation skips work if it has already // been done, this will be fast if everything is validated fine already. try { $this ->command->validateConfiguration(); } catch (RuntimeExceptionWithMarkup $e ) { $this ->messenger()->addMessage( $e ->getMarkup(), 'error' ); } catch (\Exception $e ) { // Validation failed. This should not be possible if all prior // validation checks occurred as they were supposed to. $this ->messenger()->addMessage( $e ->getMessage(), 'error' ); } } /*-------------------------------------------------------------------- * * Form submit. * *--------------------------------------------------------------------*/ /** * {@inheritdoc} */ public function submitForm( array & $form , FormStateInterface $formState ) { if ( $this ->enableAjax === TRUE) { return ; } switch ( $formState ->getTriggeringElement()[ '#name' ]) { default : case 'cancel' : // On cancel, return to the starting page. On anything else (there // shouldn't be anything), update the page as well. // // This chould never occur. The dialogs are marked so that cancel // automatically takes down the dialog. if ( $this ->url !== NULL) { $formState ->setRedirectUrl(Url::fromUri( $this ->url)); } break ; case 'submit' : // On submit, execute command, then return to the starting page. if ( $this ->command !== NULL) { $this ->command->submitConfigurationForm( $form , $formState ); } if ( $this ->url !== NULL) { $formState ->setRedirectUrl(Url::fromUri( $this ->url)); } break ; } } /** * {@inheritdoc} */ public function submitFormAjax( array & $form , FormStateInterface $formState ) { $response = new AjaxResponse(); if ( $formState ->isRebuilding() === TRUE) { return $form ; } switch ( $formState ->getTriggeringElement()[ '#name' ]) { case 'cancel' : // On cancel, close the dialog and return to the starting page. // // This chould never occur. The dialogs are marked so that cancel // automatically takes down the dialog. $response ->addCommand( new CloseModalDialogCommand()); return $response ; case 'submit' : // On submit, execute command, then close dialog and return // to the starting page. if ( $this ->command === NULL) { // This should not be possible. $response ->addCommand( new CloseModalDialogCommand()); return $response ; } break ; default : // On any unrecognized trigger, the best we can do is force a // refresh of the page after taking down the dialog. // Redirect to a new page. $response ->addCommand( new CloseModalDialogCommand()); if ( $this ->url !== NULL) { $response ->addCommand( new RedirectCommand( $this ->url)); } else { $url = Url::fromRoute( '<current>' ); $response ->addCommand( new RedirectCommand( $url ->toString())); } return $response ; } // // Execute. // -------- // The command doesn't need more operands. Validate, check permissions, // then execute. Failures either set form element errors or set page // errors. Pull out those errors and report them. $this ->messenger()->deleteAll(); try { $this ->command->validateConfiguration(); if ( $this ->command->isValidated() === TRUE) { $this ->command->submitConfigurationForm( $form , $formState ); } } catch (AccessDeniedHttpException $e ) { $this ->messenger()->addMessage(FormatUtilities::createFormattedMessage( $this ->t( 'You do not have sufficient permissions.' ), $this ->t( 'The operation could not be completed.' )), 'error' ); } catch (NotFoundHttpException $e ) { $this ->messenger()->addMessage(FormatUtilities::createFormattedMessage( $this ->t( 'One or more items could not be found.' ), $this ->t( 'The operation could not be completed.' )), 'error' ); } catch (RuntimeExceptionWithMarkup $e ) { $this ->messenger()->addMessage( $e ->getMarkup(), 'error' ); } catch (\Exception $e ) { $this ->messenger()->addMessage( $e ->getMessage(), 'error' ); } $response ->addCommand( new CloseModalDialogCommand()); // If there are any errors, present them in an error dialog. $msgs = $this ->messenger()->all(); if (isset( $msgs [ 'error' ]) === TRUE || isset( $msgs [ 'warning' ]) === TRUE) { $cmd = new OpenErrorDialogCommand( $this ->t( 'Problem' )); $cmd ->setFromPageMessages(); $response ->addCommand( $cmd ); } elseif ( $formState ->hasAnyErrors() === TRUE) { $cmd = new OpenErrorDialogCommand( $this ->t( 'Problem' )); $cmd ->setFromFormErrors( $formState ); $response ->addCommand( $cmd ); } else { // Otherwise the command executed correctly. Handle the post-execute // behaviors. $executeBehavior = $this ->command->getExecuteBehavior(); switch ( $executeBehavior ) { default : case FolderShareCommandInterface::POST_EXECUTE_PAGE_REFRESH: case FolderShareCommandInterface::POST_EXECUTE_PAGE_REDIRECT: // Redirect to a new page. if ( $this ->url !== NULL) { $response ->addCommand( new RedirectCommand( $this ->url)); } else { $url = Url::fromRoute( '<current>' ); $response ->addCommand( new RedirectCommand( $url ->toString())); } break ; case FolderShareCommandInterface::POST_EXECUTE_VIEW_REFRESH: // Refresh the view associated with the menu the command came from. $selector = '#' . $this ->parentFormId; $method = 'trigger' ; $args = [ 'FolderShareRefreshView' , ]; $response ->addCommand( new InvokeCommand( $selector , $method , $args )); break ; } } $this ->command = NULL; return $response ; } /*-------------------------------------------------------------------- * * Utilities. * *--------------------------------------------------------------------*/ /** * Decodes plugin information passed to the form via its URL. * * @param string $encoded * The base64 encoded string included as a parameter on the form URL. */ private function decodeParameters(string $encoded ) { // // The incoming parameters are an encoded associative array that provides // the plugin ID, configuration, and redirect URL. Encoding has expressed // the array as a base64 string so that it could be included as a // URL parameter. Decoding reverses the base64 encode, and a JSON decode // to return an object, which we cast to an array as needed. // // Decode parameters. $parameters = ( array ) json_decode( base64_decode ( $encoded ), TRUE); if ( empty ( $parameters ) === TRUE) { // Fail. No parameters? // // This should not be possible because the route requires that there // be parameters. At a minimum, we need the command plugin ID. $this ->messenger()->addMessage( $this ->t( "Communications problem.\nThe '@operation' command could not be completed because it is missing one or more required parameters." , [ '@operation' => $this ->command->label(), ]), 'error' ); return []; } // Get plugin ID. if ( empty ( $parameters [ 'pluginId' ]) === TRUE) { // Fail. No plugin ID? // // The parameters are malformed and missing the essential plugin ID. $this ->messenger()->addMessage( $this ->t( "Communications problem.\nThe '@operation' command could not be completed because it is missing one or more required parameters." , [ '@operation' => $this ->command->label(), ]), 'error' ); return []; } // Get initial configuration. if (isset( $parameters [ 'configuration' ]) === FALSE) { // Fail. No configuration? // // The parameters are malformed and missing the essential configuration. $this ->messenger()->addMessage( $this ->t( "Communications problem.\nThe '@operation' command could not be completed because it is missing one or more required parameters." , [ '@operation' => $this ->command->label(), ]), 'error' ); return []; } // Insure the configuration is an array. $parameters [ 'configuration' ] = ( array ) $parameters [ 'configuration' ]; return $parameters ; } } |