You are here

class WebformDevelEntityFormApiExportForm in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_devel/src/Form/WebformDevelEntityFormApiExportForm.php \Drupal\webform_devel\Form\WebformDevelEntityFormApiExportForm

Export a webform's element to Form API (FAPI).

Hierarchy

Expanded class hierarchy of WebformDevelEntityFormApiExportForm

File

modules/webform_devel/src/Form/WebformDevelEntityFormApiExportForm.php, line 17

Namespace

Drupal\webform_devel\Form
View source
class WebformDevelEntityFormApiExportForm extends WebformDevelEntityFormApiBaseForm {

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

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();
    $elements = $webform
      ->getElementsDecoded();
    $this
      ->cleanupElements($elements);
    $this
      ->setDefaultValues($elements);
    $elements['actions'] = [
      '#type' => 'actions',
      '#tree' => TRUE,
      'submit' => [
        '#type' => 'submit',
        '#value' => (string) $this
          ->t('Save configuration'),
        '#button_type' => 'primary',
      ],
    ];
    $webform_id = $webform
      ->id();
    $webform_label = $webform
      ->label();
    $webform_form_name = str_replace('_', '', ucwords($webform_id, '_')) . 'SettingsForm';

    // Filenames.
    $file_names = [
      'info' => "/{$webform_id}/{$webform_id}.info.yml",
      'routing' => "/{$webform_id}/{$webform_id}.routing.yml",
      'form' => "/{$webform_id}/src/Form/{$webform_form_name}.php",
      'config' => "/{$webform_id}/config/install/{$webform_id}.settings.yml",
    ];

    // Form.
    $webform_elements = str_replace("\n", "\n    ", trim($this
      ->renderExport($elements)));
    $webform_elements = preg_replace("/'##([^#]+)##'/ims", '$config->get(\'$1\')', $webform_elements);
    $build = [
      '#type' => 'inline_template',
      '#template' => $this
        ->getPhpTemplate(),
      '#context' => [
        'name' => $webform
          ->id(),
        'label' => $webform
          ->label(),
        'class_name' => str_replace('_', '', ucwords($webform
          ->id(), '_')),
        'form' => Markup::create($webform_elements),
      ],
    ];
    $form_php = $this->renderer
      ->render($build);

    // Config.
    $config = $this->generate
      ->getData($webform);

    // Form.
    $form['code'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Form API (FAPI) Code'),
      '#file_names' => $file_names,
      '#tree' => TRUE,
    ];
    $form['code']['description'] = [
      '#markup' => $this
        ->t('Learn more about <a href="https://www.drupal.org/docs/8/api/form-api">Form API in Drupal 8</a>.'),
      '#prefix' => '<p>',
      '#suffix' => '</p>',
    ];

    // Info.
    $form['code']['info'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'yaml',
      '#title' => $this
        ->t('Module info'),
      '#description' => $this
        ->t('Filename: %file', [
        '%file' => $file_names['info'],
      ]),
      '#help' => FALSE,
      '#attributes' => [
        'readonly' => TRUE,
      ],
      '#default_value' => Yaml::encode([
        'name' => $webform_label,
        'type' => 'module',
        'description' => $webform
          ->getDescription(),
        'package' => 'Webform Custom',
        'core' => '8.x',
        'configure' => "{$webform_id}.settings",
        'dependencies' => [
          'webform:webform',
        ],
      ]),
    ];

    // Routing.
    $form['code']['routing'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'yaml',
      '#title' => $this
        ->t('Routing'),
      '#description' => $this
        ->t('Filename: %file', [
        '%file' => $file_names['routing'],
      ]),
      '#help' => FALSE,
      '#attributes' => [
        'readonly' => TRUE,
      ],
      '#default_value' => Yaml::encode([
        $webform_id . '.settings' => [
          'path' => '/admin/config/' . $webform_id,
          'defaults' => [
            '_form' => "\\Drupal\\{$webform_id}\\Form\\{$webform_form_name}",
            '_title' => $webform_label,
          ],
          'requirements' => [
            '_permission' => 'administer configuration',
          ],
        ],
      ]),
    ];

    // Form (API).
    $form['code']['form'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'php',
      '#title' => $this
        ->t('Configuration settings form'),
      '#description' => $this
        ->t('Filename: %file', [
        '%file' => $file_names['form'],
      ]),
      '#help' => FALSE,
      '#attributes' => [
        'readonly' => TRUE,
      ],
      '#default_value' => $form_php,
    ];

    // Config.
    $form['code']['config'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'yaml',
      '#title' => $this
        ->t('Default configuration'),
      '#description' => $this
        ->t('Filename: %file', [
        '%file' => $file_names['config'],
      ]),
      '#help' => FALSE,
      '#attributes' => [
        'readonly' => TRUE,
      ],
      '#default_value' => Yaml::encode($config),
    ];
    $form['actions'] = [
      '#type' => 'actions',
      'download' => [
        '#type' => 'submit',
        '#value' => $this
          ->t('Download'),
        '#button_type' => 'primary',
      ],
      'test' => [
        '#type' => 'link',
        '#title' => $this
          ->t('Test'),
        '#url' => Url::fromRoute('entity.webform.fapi_test_form', [
          'webform' => $webform_id,
        ]),
        '#attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_WIDE, [
          'button',
        ]),
      ],
    ];
    WebformDialogHelper::attachLibraries($form);
    return $form;
  }

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

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();

    // Get the Tar archive.
    $archive_file_path = \Drupal::service('file_system')
      ->getTempDirectory() . '/' . $webform
      ->id() . '.tar.gz';
    $archive = new \Archive_Tar($archive_file_path, 'gz');

    // Add code to archive.
    $file_names = $form['code']['#file_names'];
    $code = $form_state
      ->getValue('code');
    foreach ($file_names as $key => $file_name) {
      $archive
        ->addString($file_name, $code[$key]);
    }

    // Set archive as the response and delete the temp file.
    $response = new BinaryFileResponse($archive_file_path, 200, [], FALSE);
    $response
      ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $webform
      ->id() . '.tar.gz');
    $response
      ->deleteFileAfterSend(TRUE);
    $form_state
      ->setResponse($response);
  }

  /****************************************************************************/

  // Helper functions.

  /****************************************************************************/

  /**
   * Set webform elements default values using test data.
   *
   * @param array $elements
   *   An render array representing elements.
   */
  protected function setDefaultValues(array &$elements) {

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();
    $flattened_elements =& WebformFormHelper::flattenElements($elements);
    foreach ($flattened_elements as $element_key => &$element) {
      $element_plugin = $this->elementManager
        ->getElementInstance($element);
      if ($element_plugin
        ->isInput($element)) {
        $element['#default_value'] = "##{$element_key}##";
      }
    }
  }

  /**
   * Get the form's PHP template.
   *
   * @return string
   *   The form's PHP template.
   */
  protected function getPhpTemplate() {
    return <<<'EOT'
<?php

namespace Drupal\{{ name }}\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * {{ label }} configuration settings form.
 */
class {{ class_name }}SettingsForm extends ConfigFormBase {

  /**
   * The webform token manager.
   *
   * @var \Drupal\webform\WebformTokenManagerInterface
   */
  protected $tokenManager;

  /**
   * The webform element plugin manager.
   *
   * @var \Drupal\webform\Plugin\WebformElementManagerInterface
   */
  protected $elementManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->tokenManager = $container->get('webform.token_manager');
    $instance->elementManager = $container->get('plugin.manager.webform.element');
    return $instance;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['{{ name }}.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('{{ name }}.settings');

    {{ form }}

    // Process elements.
    $this->elementManager->processElements($form);

    // Replace tokens.
    $form = $this->tokenManager->replace($form);

    // Attach the webform library.
    $form['#attached']['library'][] = 'webform/webform.form';

    // Autofocus: Save details open/close state.
    $form['#attributes']['class'][] = 'js-webform-autofocus';
    $form['#attached']['library'][] = 'webform/webform.form.auto_focus';

    // Unsaved: Warn users about unsaved changes.
    $form['#attributes']['class'][] = 'js-webform-unsaved';
    $form['#attached']['library'][] = 'webform/webform.form.unsaved';

    // Details save: Attach details element save open/close library.
    $form['#attached']['library'][] = 'webform/webform.element.details.save';

    // Details toggle: Display collapse/expand all details link.
    $form['#attributes']['class'][] = 'js-webform-details-toggle';
    $form['#attributes']['class'][] = 'webform-details-toggle';
    $form['#attached']['library'][] = 'webform/webform.element.details.toggle';

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Get all values.
    $values = $form_state->getValues();

    // Remove Form API values.
    unset(
      $values['form_build_id'],
      $values['form_token'],
      $values['form_id'],
      $values['op'],
      $values['actions']
    );

    // Save config.
    $this->config('{{ name }}.settings')
      ->setData($values)
      ->save();

    // Display message.
    parent::submitForm($form, $form_state);
  }

}
EOT;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 11
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 35
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 3
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 9
EntityForm::form public function Gets the actual form array to be built. 36
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 47
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
FormBase::$configFactory protected property The config factory. 3
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. 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 72
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.
WebformDevelEntityFormApiBaseForm::$archiverManager protected property The archiver manager.
WebformDevelEntityFormApiBaseForm::$elementManager protected property The webform element plugin manager.
WebformDevelEntityFormApiBaseForm::$generate protected property The webform submission generator service.
WebformDevelEntityFormApiBaseForm::$renderer protected property The renderer.
WebformDevelEntityFormApiBaseForm::$tokenManager protected property The webform token manager.
WebformDevelEntityFormApiBaseForm::$translatableProperties protected property An array of translatable properties.
WebformDevelEntityFormApiBaseForm::cleanupElements protected function Cleanup webform elements.
WebformDevelEntityFormApiBaseForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformDevelEntityFormApiBaseForm::initialize protected function Initialize WebformDevelEntityFormApiBaseForm object.
WebformDevelEntityFormApiBaseForm::isPropertyTranslatable protected function Determine if an element property is translatable.
WebformDevelEntityFormApiBaseForm::renderExport protected function Export a PHP render array.
WebformDevelEntityFormApiBaseForm::varExport protected function Outputs string representation of a variable using array short syntax.
WebformDevelEntityFormApiBaseForm::wrapTranslatableValue protected function Wrap translatable value in <T> tags.
WebformDevelEntityFormApiExportForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
WebformDevelEntityFormApiExportForm::getPhpTemplate protected function Get the form's PHP template.
WebformDevelEntityFormApiExportForm::setDefaultValues protected function Set webform elements default values using test data.
WebformDevelEntityFormApiExportForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm