You are here

class WebformDevelSubmissionApiForm in Webform 8.5

Same name and namespace in other branches
  1. 6.x modules/webform_devel/src/Form/WebformDevelSubmissionApiForm.php \Drupal\webform_devel\Form\WebformDevelSubmissionApiForm

Form used to test programmatic submissions of webforms.

Hierarchy

Expanded class hierarchy of WebformDevelSubmissionApiForm

1 string reference to 'WebformDevelSubmissionApiForm'
webform_devel.routing.yml in modules/webform_devel/webform_devel.routing.yml
modules/webform_devel/webform_devel.routing.yml

File

modules/webform_devel/src/Form/WebformDevelSubmissionApiForm.php, line 19

Namespace

Drupal\webform_devel\Form
View source
class WebformDevelSubmissionApiForm extends FormBase {

  /**
   * The webform submission storage.
   *
   * @var \Drupal\webform\WebformSubmissionStorageInterface
   */
  protected $submissionStorage;

  /**
   * The webform request handler.
   *
   * @var \Drupal\webform\WebformRequestInterface
   */
  protected $requestHandler;

  /**
   * The webform submission generation service.
   *
   * @var \Drupal\webform\WebformSubmissionGenerateInterface
   */
  protected $generate;

  /**
   * Constructs a WebformDevelSubmissionApiForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\webform\WebformRequestInterface $request_handler
   *   The webform request handler.
   * @param \Drupal\webform\WebformSubmissionGenerateInterface $submission_generate
   *   The webform submission generation service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, WebformRequestInterface $request_handler, WebformSubmissionGenerateInterface $submission_generate) {
    $this->submissionStorage = $entity_type_manager
      ->getStorage('webform_submission');
    $this->requestHandler = $request_handler;
    $this->generate = $submission_generate;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('webform.request'), $container
      ->get('webform_submission.generate'));
  }

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

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

    /** @var \Drupal\webform\WebformInterface $webform */

    /** @var \Drupal\Core\Entity\EntityInterface $source_entity */
    list($webform, $source_entity) = $this->requestHandler
      ->getWebformEntities();
    $values = [];

    // Set webform id.
    $values['webform_id'] = $webform
      ->id();

    // Set source entity type and id.
    if ($source_entity) {
      $values['entity_type'] = $source_entity
        ->getEntityTypeId();
      $values['entity_id'] = $source_entity
        ->id();
    }
    WebformSubmission::preCreate($this->submissionStorage, $values);

    // Generate data as last value.
    unset($values['data']);
    $values['data'] = $this->generate
      ->getData($webform);
    $form['submission'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Submission values'),
      '#open' => TRUE,
    ];
    $form['submission']['message'] = [
      '#type' => 'webform_message',
      '#message_message' => $this
        ->t("Submitting the below values will trigger the %title webform's ::validateFormValues() and ::submitFormValues() callbacks.", [
        '%title' => $webform
          ->label(),
      ]),
      '#message_type' => 'warning',
    ];
    $form['submission']['values'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'yaml',
      '#title' => $this
        ->t('Values'),
      '#title_display' => 'hidden',
      '#default_value' => $values,
    ];
    $form['php'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('PHP usage'),
      '#description' => $this
        ->t('Below is an example of how to programatically validate and submit a webform submission using PHP.'),
    ];
    $form['php']['code'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'php',
      '#title' => $this
        ->t('PHP'),
      '#title_display' => 'hidden',
      '#attributes' => [
        'readonly' => 'readonly',
        'disabled' => 'disabled',
      ],
      '#default_value' => '
// Get submission values and data.
$values = ' . Variable::export($values) . ';

// Check that the webform is open.
$webform = \\Drupal\\webform\\entity\\Webform::load(\'' . $webform
        ->id() . '\');
$is_open = \\Drupal\\webform\\WebformSubmissionForm::isOpen($webform);
if ($is_open === TRUE) {
  // Validate webform submission values.
  $errors = \\Drupal\\webform\\WebformSubmissionForm::validateFormValues($values);

  // Submit webform submission values.
  if (empty($errors)) {
    $webform_submission = \\Drupal\\webform\\WebformSubmissionForm::submitFormValues($values);
  }
}',
    ];
    $form['actions'] = [];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValue('values');

    // Check if the webform is open to new submissions.
    $webform = Webform::load($values['webform_id']);
    if (!$webform) {
      $form_state
        ->setErrorByName('values', $this
        ->t('Webform %webform_id not found.', [
        '%webform_id' => $values['webform_id'],
      ]));
      return;
    }
    $is_open = WebformSubmissionForm::isOpen($webform);
    if ($is_open !== TRUE) {
      $form_state
        ->setErrorByName('values', $is_open);
    }

    // Validate values.
    if ($errors = WebformSubmissionForm::validateFormValues($values)) {
      foreach ($errors as $error) {
        $form_state
          ->setErrorByName('values', $error);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValue('values');
    $webform_submission = WebformSubmissionForm::submitFormValues($values);
    $this
      ->messenger()
      ->addStatus($this
      ->t('New submission %title added.', [
      '%title' => $webform_submission
        ->label(),
    ]));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::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.
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.
WebformDevelSubmissionApiForm::$generate protected property The webform submission generation service.
WebformDevelSubmissionApiForm::$requestHandler protected property The webform request handler.
WebformDevelSubmissionApiForm::$submissionStorage protected property The webform submission storage.
WebformDevelSubmissionApiForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
WebformDevelSubmissionApiForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformDevelSubmissionApiForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformDevelSubmissionApiForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WebformDevelSubmissionApiForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
WebformDevelSubmissionApiForm::__construct public function Constructs a WebformDevelSubmissionApiForm object.