You are here

class TagFormBase in Extensible BBCode 4.0.x

Same name and namespace in other branches
  1. 8.3 src/Form/TagFormBase.php \Drupal\xbbcode\Form\TagFormBase

Base form for custom tags.

Hierarchy

Expanded class hierarchy of TagFormBase

File

src/Form/TagFormBase.php, line 24

Namespace

Drupal\xbbcode\Form
View source
class TagFormBase extends EntityForm {
  use LabeledFormTrait;

  /**
   * The twig service.
   *
   * @var \Drupal\Core\Template\TwigEnvironment
   */
  protected $twig;

  /**
   * TagFormBase constructor.
   *
   * @param \Drupal\Core\Template\TwigEnvironment $twig
   *   The twig service.
   */
  public function __construct(TwigEnvironment $twig) {
    $this->twig = $twig;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) : array {
    $form = $this
      ->addLabelFields($form);

    /** @var \Drupal\xbbcode\Entity\TagInterface $tag */
    $tag = $this->entity;
    $sample = str_replace('{{ name }}', $tag
      ->getName(), $tag
      ->getSample());
    $form['description'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Description'),
      '#default_value' => $tag
        ->getDescription(),
      '#description' => $this
        ->t('Describe this tag. This will be shown in the filter tips and on administration pages.'),
      '#required' => TRUE,
      '#rows' => max(5, substr_count($tag
        ->getDescription(), "\n")),
    ];
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Default name'),
      '#default_value' => $tag
        ->getName(),
      '#description' => $this
        ->t('The default code name of this tag. It must contain only lowercase letters, numbers, hyphens and underscores.'),
      '#field_prefix' => '[',
      '#field_suffix' => ']',
      '#maxlength' => 32,
      '#size' => 16,
      '#required' => TRUE,
      '#pattern' => '[a-z0-9_-]+',
    ];
    $form['sample'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Sample code'),
      '#attributes' => [
        'style' => 'font-family:monospace',
      ],
      '#default_value' => $sample,
      '#description' => $this
        ->t('Give an example of how this tag should be used.'),
      '#required' => TRUE,
      '#rows' => max(5, substr_count($tag
        ->getSample(), "\n")),
    ];
    $form['editable'] = [
      '#type' => 'value',
      '#value' => TRUE,
    ];
    $template_code = $tag
      ->getTemplateCode();

    // Load the template code from a file if necessary.
    // Not used for custom tags, but allows replacing files with inline code.
    if (!$template_code && ($file = $tag
      ->getTemplateFile())) {

      // The source must be loaded directly, because the template class won't
      // have it unless it is loaded from the file cache.
      try {
        $path = $this->twig
          ->load($file)
          ->getSourceContext()
          ->getPath();
        $template_code = rtrim(file_get_contents($path));
      } catch (TwigError $exception) {
        watchdog_exception('xbbcode', $exception);
        $this
          ->messenger()
          ->addError($exception
          ->getMessage());
      }
    }
    $form['template_code'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Template code'),
      '#attributes' => [
        'style' => 'font-family:monospace',
      ],
      '#default_value' => $template_code,
      '#description' => $this
        ->t('The template for rendering this tag.'),
      '#required' => TRUE,
      '#rows' => max(5, 1 + substr_count($template_code, "\n")),
      '#attached' => $tag
        ->getAttachments(),
    ];
    $form['help'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Coding help'),
      '#open' => FALSE,
    ];
    $form['help']['variables'] = [
      '#theme' => 'xbbcode_help',
      '#title' => $this
        ->t('The above field should be filled with <a href="http://twig.sensiolabs.org/documentation">Twig</a> template code. The following variables are available for use:'),
      '#label_prefix' => 'tag.',
      '#rows' => [
        'content' => $this
          ->t('The text between opening and closing tags, after rendering nested elements. Example: <code>[url=http://www.drupal.org]<strong>Drupal</strong>[/url]</code>'),
        'option' => $this
          ->t('The single tag attribute, if one is entered. Example: <code>[url=<strong>http://www.drupal.org</strong>]Drupal[/url]</code>.'),
        'attribute' => [
          'suffix' => [
            's.*',
            "('*')",
          ],
          'description' => $this
            ->t('A named tag attribute. Example: <code>{{ tag.attributes.by }}</code> for <code>[quote by=<strong>Author</strong> date=2008]Text[/quote]</code>.'),
        ],
        'source' => $this
          ->t('The source content of the tag. Example: <code>[code]<strong>&lt;strong&gt;[i]...[/i]&lt;/strong&gt;</strong>[/code]</code>.'),
        'outerSource' => $this
          ->t('The content of the tag, wrapped in the original opening and closing elements. Example: <code><strong>[url=http://www.drupal.org]Drupal[/url]</strong></code>.<br/>
          This can be printed to render the tag as if it had not been processed.'),
      ],
    ];
    $form['preview'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Preview'),
    ];
    try {
      $template = $this->twig
        ->load(EntityTagPlugin::TEMPLATE_PREFIX . "\n" . $template_code);
      $processor = new CallbackTagProcessor(static function (TagElementInterface $element) use ($template) {
        return $template
          ->render([
          'tag' => new PreparedTagElement($element),
        ]);
      });
      $parser = new XBBCodeParser([
        $tag
          ->getName() => $processor,
      ]);
      $tree = $parser
        ->parse($sample);
      XBBCodeFilter::filterXss($tree);
      $output = $tree
        ->render();
      $form['preview']['code']['#markup'] = Markup::create($output);
    } catch (TwigError $exception) {
      $this
        ->messenger()
        ->addError($exception
        ->getRawMessage());
      $form['preview']['code']['template'] = $this
        ->templateError($exception);
    }
    $form['attached'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Attachments (advanced)'),
      '#description' => $this
        ->t('Changes are not reflected in the preview until the form is saved.'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];
    $libraries = $tag
      ->getAttachments()['library'] ?? [];
    $form['attached']['library'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Libraries'),
      '#default_value' => implode("\n", $libraries),
      '#rows' => max(1, 1 + count($libraries)),
      '#description' => $this
        ->t('Libraries are static assets (scripts and stylesheets) <a href=":url">defined by modules or themes</a>, to be included wherever this tag is rendered. Specify one library per line, in the form <code>module_name/library_name</code>.', [
        ':url' => 'https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module#library',
      ]),
    ];
    return parent::form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) : void {
    parent::copyFormValuesToEntity($entity, $form, $form_state);
    assert($entity instanceof TagInterface);
    $attached = [];
    if ($libraries = trim($form_state
      ->getValue([
      'attached',
      'library',
    ]))) {
      $attached['library'] = explode("\n", $libraries);
    }
    $entity
      ->set('attached', $attached);
  }

  /**
   * Render the code of a broken template with line numbers.
   *
   * @param \Twig\Error\Error $exception
   *   The twig error for an inline template.
   *
   * @return array
   *   Render array showing the code with the error's line highlighted.
   */
  public function templateError(TwigError $exception) : array {
    $source = $exception
      ->getSourceContext();
    $code = $source ? $source
      ->getCode() : '';
    $lines = explode("\n", $code);

    // Remove the inline template header.
    array_shift($lines);
    $number = $exception
      ->getTemplateLine() - 2;
    $output = [
      '#prefix' => '<pre class="template">',
      '#suffix' => '</pre>',
    ];
    foreach ($lines as $i => $line) {
      $output[$i] = [
        '#prefix' => '<span>',
        '#suffix' => "</span>\n",
        '#markup' => new HtmlEscapedText($line),
      ];
    }
    $output[$number]['#prefix'] = '<span class="line-error">';
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntity() : EntityInterface {
    $entity = parent::getEntity();
    assert($entity instanceof EntityInterface);
    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) : array {
    $actions = parent::actions($form, $form_state);
    if (!$this->entity
      ->isNew()) {

      // Add access check on the save button.
      if (isset($actions['submit'])) {
        $actions['submit']['#access'] = $this->entity
          ->access('update');
      }
      try {
        $actions['copy'] = [
          '#type' => 'link',
          '#attributes' => [
            'class' => [
              'button',
            ],
          ],
          '#title' => $this
            ->t('Copy'),
          '#access' => $this->entity
            ->access('create'),
          '#url' => $this->entity
            ->toUrl('copy-form'),
        ];
      } catch (EntityMalformedException $e) {
      }
    }
    return $actions;
  }

}

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::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::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
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
EntityForm::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 FormInterface::submitForm 20
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 105
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
LabeledFormTrait::addLabelFields public function Add label fields to the form array.
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.
TagFormBase::$twig protected property The twig service.
TagFormBase::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions 1
TagFormBase::copyFormValuesToEntity protected function Copies top-level form values to entity properties. Overrides EntityForm::copyFormValuesToEntity 1
TagFormBase::form public function Gets the actual form array to be built. Overrides EntityForm::form 1
TagFormBase::getEntity public function Gets the form entity. Overrides LabeledFormTrait::getEntity
TagFormBase::templateError public function Render the code of a broken template with line numbers.
TagFormBase::__construct public function TagFormBase constructor. 1