wysiwyg_template.module in Wysiwyg API template plugin 3.0.x
File
wysiwyg_template.module
View source
<?php
use Drupal\Core\Url;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\node\Entity\NodeType;
use Drupal\wysiwyg_template\Entity\Template;
function wysiwyg_template_editor_js_settings_alter(array &$settings) {
$route_match = Drupal::routeMatch();
$entity_type = NULL;
$bundle = NULL;
foreach (Drupal::service('wysiwyg_template.services')
->getEntityTypesAndBundles() as $entity_type => $defintion) {
if (empty($defintion['bundles'])) {
continue;
}
if ($route_match
->getRouteName() === 'entity.' . $entity_type . '.edit_form') {
$bundle = $route_match
->getParameter($entity_type)
->bundle();
}
else {
if ($route_match
->getRouteName() === $entity_type . '.add') {
$bundle = $route_match
->getParameter($entity_type . '_type')
->get('type');
}
}
if ($bundle !== NULL && isset($defintion['bundles'][$bundle])) {
break;
}
$bundle = NULL;
}
if ($bundle !== NULL) {
foreach ($settings['editor']['formats'] as $format => $config) {
if (isset($config['editorSettings']['templates_files'])) {
$url = Url::fromRoute('wysiwyg_template.list_js.type', [
'entity_type' => $entity_type,
'bundle' => $bundle,
]);
$settings['editor']['formats'][$format]['editorSettings']['templates_files'] = [
$url
->toString(),
];
}
}
}
}
function wysiwyg_template_form_node_type_form_alter(array &$form, FormStateInterface $form_state) {
$bundle = $form_state
->getFormObject()
->getEntity();
$templates = Template::loadByTypeAndBundle('node', $bundle
->id());
$form['wysiwyg_template'] = [
'#type' => 'details',
'#title' => t('WYSIWYG template'),
'#group' => 'additional_settings',
];
$form['wysiwyg_template']['wysiwyg_template_default'] = [
'#type' => 'select',
'#options' => array_map(static function ($item) {
return $item
->label();
}, $templates),
'#default_value' => $bundle
->getThirdPartySetting('wysiwyg_template', 'default_template'),
'#title' => t('Default template for this content type'),
'#empty_value' => '',
];
$form['#entity_builders'][] = 'wysiwyg_template_form_node_type_form_builder';
}
function wysiwyg_template_form_node_type_form_builder($entity_type, NodeTypeInterface $type, array &$form, FormStateInterface $form_state) {
$type
->setThirdPartySetting('wysiwyg_template', 'default_template', $form_state
->getValue('wysiwyg_template_default'));
}
function wysiwyg_template_form_node_form_alter(array &$form, FormStateInterface $form_state) {
$node = $form_state
->getFormObject()
->getEntity();
$type = NodeType::load($node
->getType());
if ($node
->isNew() && ($template_id = $type
->getThirdPartySetting('wysiwyg_template', 'default_template'))) {
$template = Template::load($template_id);
$form['body']['widget'][0]['#default_value'] = $template
->getBody();
}
}