You are here

class YamlFormEntityForm in YAML Form 8

Base for controller for form.

Hierarchy

Expanded class hierarchy of YamlFormEntityForm

1 file declares its use of YamlFormEntityForm
YamlFormUiEntityForm.php in modules/yamlform_ui/src/YamlFormUiEntityForm.php

File

src/YamlFormEntityForm.php, line 14

Namespace

Drupal\yamlform
View source
class YamlFormEntityForm extends BundleEntityFormBase {
  use YamlFormDialogTrait;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Form element manager.
   *
   * @var \Drupal\yamlform\YamlFormElementManagerInterface
   */
  protected $elementManager;

  /**
   * Form element validator.
   *
   * @var \Drupal\yamlform\YamlFormEntityElementsValidator
   */
  protected $elementsValidator;

  /**
   * The token manager.
   *
   * @var \Drupal\yamlform\YamlFormTranslationManagerInterface
   */
  protected $tokenManager;

  /**
   * Constructs a new YamlFormUiElementFormBase.
   *
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   * @param \Drupal\yamlform\YamlFormElementManagerInterface $element_manager
   *   The form element manager.
   * @param \Drupal\yamlform\YamlFormEntityElementsValidator $elements_validator
   *   Form element validator.
   * @param \Drupal\yamlform\YamlFormTokenManagerInterface $token_manager
   *   The token manager.
   */
  public function __construct(RendererInterface $renderer, YamlFormElementManagerInterface $element_manager, YamlFormEntityElementsValidator $elements_validator, YamlFormTokenManagerInterface $token_manager) {
    $this->renderer = $renderer;
    $this->elementManager = $element_manager;
    $this->elementsValidator = $elements_validator;
    $this->tokenManager = $token_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('renderer'), $container
      ->get('plugin.manager.yamlform.element'), $container
      ->get('yamlform.elements_validator'), $container
      ->get('yamlform.token_manager'));
  }

  /**
   * {@inheritdoc}
   */
  protected function prepareEntity() {
    if ($this->operation == 'duplicate') {
      $this
        ->setEntity($this
        ->getEntity()
        ->createDuplicate());
    }
    parent::prepareEntity();
  }

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

    /** @var \Drupal\yamlform\YamlFormInterface $yamlform */
    $yamlform = $this
      ->getEntity();

    // Customize title for duplicate form.
    if ($this->operation == 'duplicate') {

      // Display custom title.
      $form['#title'] = $this
        ->t("Duplicate '@label' form", [
        '@label' => $yamlform
          ->label(),
      ]);

      // If template, clear template's description and remove template flag.
      if ($yamlform
        ->isTemplate()) {
        $yamlform
          ->set('description', '');
        $yamlform
          ->set('template', FALSE);
      }
    }
    $form = parent::buildForm($form, $form_state);
    $form = $this
      ->buildDialog($form, $form_state);
    return $form;
  }

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

    /** @var \Drupal\yamlform\YamlFormInterface $yamlform */
    $yamlform = $this
      ->getEntity();

    // Only display id, title, and description for new forms.
    // Once a form is created this information is moved to the form's settings
    // tab.
    if ($yamlform
      ->isNew()) {
      $form['id'] = [
        '#type' => 'machine_name',
        '#default_value' => $yamlform
          ->id(),
        '#machine_name' => [
          'exists' => '\\Drupal\\yamlform\\Entity\\YamlForm::load',
          'source' => [
            'title',
          ],
        ],
        '#maxlength' => 32,
        '#disabled' => (bool) $yamlform
          ->id() && $this->operation != 'duplicate',
        '#required' => TRUE,
      ];
      $form['title'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Title'),
        '#maxlength' => 255,
        '#default_value' => $yamlform
          ->label(),
        '#required' => TRUE,
        '#id' => 'title',
        '#attributes' => [
          'autofocus' => 'autofocus',
        ],
      ];
      $form['description'] = [
        '#type' => 'yamlform_html_editor',
        '#title' => $this
          ->t('Administrative description'),
        '#default_value' => $yamlform
          ->get('description'),
      ];
      $form = $this
        ->protectBundleIdElement($form);
    }

    // Call the isolated edit form that can be overridden by the
    // yamlform_ui.module.
    $form = $this
      ->editForm($form, $form_state);
    return parent::form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    unset($actions['delete']);
    return $actions;
  }

  /**
   * Edit form element's source code form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  protected function editForm(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\yamlform\YamlFormInterface $yamlform */
    $yamlform = $this
      ->getEntity();
    $t_args = [
      ':form_api_href' => 'https://www.drupal.org/node/37775',
      ':render_api_href' => 'https://www.drupal.org/developing/api/8/render',
      ':yaml_href' => 'https://en.wikipedia.org/wiki/YAML',
    ];
    $form['elements'] = [
      '#type' => 'yamlform_codemirror',
      '#mode' => 'yaml',
      '#title' => $this
        ->t('Elements (YAML)'),
      '#description' => $this
        ->t('Enter a <a href=":form_api_href">Form API (FAPI)</a> and/or a <a href=":render_api_href">Render Array</a> as <a href=":yaml_href">YAML</a>.', $t_args) . '<br/>' . '<em>' . $this
        ->t('Please note that comments are not supported and will be removed.') . '</em>',
      '#default_value' => $yamlform
        ->get('elements'),
      '#required' => TRUE,
    ];
    $form['token_tree_link'] = $this->tokenManager
      ->buildTreeLink();
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // Validate elements YAML.
    if ($messages = $this->elementsValidator
      ->validate($this
      ->getEntity())) {
      $form_state
        ->setErrorByName('elements');
      foreach ($messages as $message) {
        drupal_set_message($message, 'error');
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($response = $this
      ->validateDialog($form, $form_state)) {
      return $response;
    }
    parent::submitForm($form, $form_state);
    if ($this
      ->isModalDialog()) {
      return $this
        ->redirectForm($form, $form_state, Url::fromRoute('entity.yamlform.edit_form', [
        'yamlform' => $this
          ->getEntity()
          ->id(),
      ]));
    }
  }

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

    /** @var \Drupal\yamlform\YamlFormInterface $yamlform */
    $yamlform = $this
      ->getEntity();
    $is_new = $yamlform
      ->isNew();
    $yamlform
      ->save();
    if ($is_new) {
      $this
        ->logger('yamlform')
        ->notice('Form @label created.', [
        '@label' => $yamlform
          ->label(),
      ]);
      drupal_set_message($this
        ->t('Form %label created.', [
        '%label' => $yamlform
          ->label(),
      ]));
    }
    else {
      $this
        ->logger('yamlform')
        ->notice('Form @label elements saved.', [
        '@label' => $yamlform
          ->label(),
      ]);
      drupal_set_message($this
        ->t('Form %label elements saved.', [
        '%label' => $yamlform
          ->label(),
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BundleEntityFormBase::protectBundleIdElement protected function Protects the bundle entity's ID property's form element against changes.
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
EntityForm::$entity protected property The entity being used by this form. 7
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::$privateEntityManager private property The entity manager.
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 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
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 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
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::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
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
EntityForm::__get public function
EntityForm::__set public function
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.
YamlFormDialogTrait::buildDialog protected function Add modal dialog support to a form.
YamlFormDialogTrait::isModalDialog protected function Is the current request for an AJAX modal dialog.
YamlFormDialogTrait::redirectForm protected function Handler dialog redirect after form is submitted.
YamlFormDialogTrait::validateDialog protected function Display validation error messages in modal dialog.
YamlFormEntityForm::$elementManager protected property Form element manager.
YamlFormEntityForm::$elementsValidator protected property Form element validator.
YamlFormEntityForm::$renderer protected property The renderer.
YamlFormEntityForm::$tokenManager protected property The token manager.
YamlFormEntityForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions 1
YamlFormEntityForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
YamlFormEntityForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
YamlFormEntityForm::editForm protected function Edit form element's source code form. 1
YamlFormEntityForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
YamlFormEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity
YamlFormEntityForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
YamlFormEntityForm::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
YamlFormEntityForm::validateForm public function Form validation handler. Overrides FormBase::validateForm 1
YamlFormEntityForm::__construct public function Constructs a new YamlFormUiElementFormBase.