View source
<?php
namespace Drupal\ckeditor_test\Form;
use Drupal\ckeditor\Ajax\AddStyleSheetCommand;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AjaxCssForm extends FormBase {
protected $fileUrlGenerator;
public function __construct(FileUrlGeneratorInterface $file_url_generator) {
$this->fileUrlGenerator = $file_url_generator;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('file_url_generator'));
}
public function getFormId() {
return 'ckeditor_test_ajax_css_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['inline'] = [
'#type' => 'container',
'#attached' => [
'library' => [
'ckeditor_test/ajax_css',
],
],
'#children' => $this
->t('Here be dragons.'),
];
$form['iframe'] = [
'#type' => 'text_format',
'#default_value' => $this
->t('Here be llamas.'),
];
$form['actions'] = [
'css_inline' => [
'#type' => 'submit',
'#value' => $this
->t('Add CSS to inline CKEditor instance'),
'#ajax' => [
'callback' => [
$this,
'addCssInline',
],
],
],
'css_frame' => [
'#type' => 'submit',
'#value' => $this
->t('Add CSS to iframe CKEditor instance'),
'#ajax' => [
'callback' => [
$this,
'addCssIframe',
],
],
],
'#type' => 'actions',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
protected function generateResponse($editor_id) {
$url = \Drupal::service('extension.list.module')
->getPath('ckeditor_test') . '/css/test.css';
$url = $this->fileUrlGenerator
->generateString($url);
$response = new AjaxResponse();
return $response
->addCommand(new AddStyleSheetCommand($editor_id, [
$url,
]));
}
public function addCssInline() {
return $this
->generateResponse('edit-inline');
}
public function addCssIframe() {
return $this
->generateResponse('edit-iframe-value');
}
}