class TagFormBase in Extensible BBCode 4.0.x
Same name and namespace in other branches
- 8.3 src/Form/TagFormBase.php \Drupal\xbbcode\Form\TagFormBase
Base form for custom tags.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, RedirectDestinationTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\xbbcode\Form\TagFormBase uses LabeledFormTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of TagFormBase
File
- src/
Form/ TagFormBase.php, line 24
Namespace
Drupal\xbbcode\FormView 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><strong>[i]...[/i]</strong></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
Name![]() |
Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity being used by this form. | 11 |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface:: |
3 |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
13 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
6 |
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
3 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
12 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Initialize the form state and the entity before the first form build. | 3 |
EntityForm:: |
protected | function | Prepares the entity object before the form is built first. | 3 |
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityFormInterface:: |
47 |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
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:: |
20 |
FormBase:: |
protected | property | The config factory. | 3 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 3 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides ContainerInjectionInterface:: |
105 |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function | Returns a redirect response object for the specified route. | |
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormBase:: |
public | function |
Form validation handler. Overrides FormInterface:: |
72 |
LabeledFormTrait:: |
public | function | Add label fields to the form array. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
TagFormBase:: |
protected | property | The twig service. | |
TagFormBase:: |
protected | function |
Returns an array of supported actions for the current entity form. Overrides EntityForm:: |
1 |
TagFormBase:: |
protected | function |
Copies top-level form values to entity properties. Overrides EntityForm:: |
1 |
TagFormBase:: |
public | function |
Gets the actual form array to be built. Overrides EntityForm:: |
1 |
TagFormBase:: |
public | function |
Gets the form entity. Overrides LabeledFormTrait:: |
|
TagFormBase:: |
public | function | Render the code of a broken template with line numbers. | |
TagFormBase:: |
public | function | TagFormBase constructor. | 1 |