3 namespace Drupal\editor\Form;
5 use Drupal\Component\Utility\Bytes;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\editor\Entity\Editor;
9 use Drupal\Core\Ajax\AjaxResponse;
10 use Drupal\Core\Ajax\HtmlCommand;
11 use Drupal\editor\Ajax\EditorDialogSave;
12 use Drupal\Core\Ajax\CloseModalDialogCommand;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14 use Drupal\Core\Entity\EntityStorageInterface;
17 * Provides an image dialog for text editors.
21 class EditorImageDialog extends FormBase {
24 * The file storage service.
26 * @var \Drupal\Core\Entity\EntityStorageInterface
28 protected $fileStorage;
31 * Constructs a form object for image dialog.
33 * @param \Drupal\Core\Entity\EntityStorageInterface $file_storage
34 * The file storage service.
36 public function __construct(EntityStorageInterface $file_storage) {
37 $this->fileStorage = $file_storage;
43 public static function create(ContainerInterface $container) {
45 $container->get('entity.manager')->getStorage('file')
52 public function getFormId() {
53 return 'editor_image_dialog';
59 * @param \Drupal\editor\Entity\Editor $editor
60 * The text editor to which this dialog corresponds.
62 public function buildForm(array $form, FormStateInterface $form_state, Editor $editor = NULL) {
63 // This form is special, in that the default values do not come from the
64 // server side, but from the client side, from a text editor. We must cache
65 // this data in form state, because when the form is rebuilt, we will be
66 // receiving values from the form, instead of the values from the text
67 // editor. If we don't cache it, this data will be lost.
68 if (isset($form_state->getUserInput()['editor_object'])) {
69 // By convention, the data that the text editor sends to any dialog is in
70 // the 'editor_object' key. And the image dialog for text editors expects
71 // that data to be the attributes for an <img> element.
72 $image_element = $form_state->getUserInput()['editor_object'];
73 $form_state->set('image_element', $image_element);
74 $form_state->setCached(TRUE);
77 // Retrieve the image element's attributes from form state.
78 $image_element = $form_state->get('image_element') ?: [];
81 $form['#tree'] = TRUE;
82 $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
83 $form['#prefix'] = '<div id="editor-image-dialog-form">';
84 $form['#suffix'] = '</div>';
86 // Construct strings to use in the upload validators.
87 $image_upload = $editor->getImageUploadSettings();
88 if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) {
89 $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height'];
94 $max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size());
96 $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL;
97 $fid = $existing_file ? $existing_file->id() : NULL;
100 '#title' => $this->t('Image'),
101 '#type' => 'managed_file',
102 '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'],
103 '#default_value' => $fid ? [$fid] : NULL,
104 '#upload_validators' => [
105 'file_validate_extensions' => ['gif png jpg jpeg'],
106 'file_validate_size' => [$max_filesize],
107 'file_validate_image_resolution' => [$max_dimensions],
112 $form['attributes']['src'] = [
113 '#title' => $this->t('URL'),
114 '#type' => 'textfield',
115 '#default_value' => isset($image_element['src']) ? $image_element['src'] : '',
116 '#maxlength' => 2048,
120 // If the editor has image uploads enabled, show a managed_file form item,
121 // otherwise show a (file URL) text form item.
122 if ($image_upload['status']) {
123 $form['attributes']['src']['#access'] = FALSE;
124 $form['attributes']['src']['#required'] = FALSE;
127 $form['fid']['#access'] = FALSE;
128 $form['fid']['#required'] = FALSE;
131 // The alt attribute is *required*, but we allow users to opt-in to empty
132 // alt attributes for the very rare edge cases where that is valid by
133 // specifying two double quotes as the alternative text in the dialog.
134 // However, that *is* stored as an empty alt attribute, so if we're editing
135 // an existing image (which means the src attribute is set) and its alt
136 // attribute is empty, then we show that as two double quotes in the dialog.
137 // @see https://www.drupal.org/node/2307647
138 $alt = isset($image_element['alt']) ? $image_element['alt'] : '';
139 if ($alt === '' && !empty($image_element['src'])) {
142 $form['attributes']['alt'] = [
143 '#title' => $this->t('Alternative text'),
144 '#placeholder' => $this->t('Short description for the visually impaired'),
145 '#type' => 'textfield',
147 '#required_error' => $this->t('Alternative text is required.<br />(Only in rare cases should this be left empty. To create empty alternative text, enter <code>""</code> — two double quotes without any content).'),
148 '#default_value' => $alt,
149 '#maxlength' => 2048,
152 // When Drupal core's filter_align is being used, the text editor may
153 // offer the ability to change the alignment.
154 if (isset($image_element['data-align']) && $editor->getFilterFormat()->filters('filter_align')->status) {
156 '#title' => $this->t('Align'),
159 'none' => $this->t('None'),
160 'left' => $this->t('Left'),
161 'center' => $this->t('Center'),
162 'right' => $this->t('Right'),
164 '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'],
165 '#wrapper_attributes' => ['class' => ['container-inline']],
166 '#attributes' => ['class' => ['container-inline']],
167 '#parents' => ['attributes', 'data-align'],
171 // When Drupal core's filter_caption is being used, the text editor may
172 // offer the ability to in-place edit the image's caption: show a toggle.
173 if (isset($image_element['hasCaption']) && $editor->getFilterFormat()->filters('filter_caption')->status) {
175 '#title' => $this->t('Caption'),
176 '#type' => 'checkbox',
177 '#default_value' => $image_element['hasCaption'] === 'true',
178 '#parents' => ['attributes', 'hasCaption'],
183 '#type' => 'actions',
185 $form['actions']['save_modal'] = [
187 '#value' => $this->t('Save'),
188 // No regular submit-handler. This form only works via JavaScript.
191 'callback' => '::submitForm',
202 public function submitForm(array &$form, FormStateInterface $form_state) {
203 $response = new AjaxResponse();
205 // Convert any uploaded files from the FID values to data-entity-uuid
206 // attributes and set data-entity-type to 'file'.
207 $fid = $form_state->getValue(['fid', 0]);
209 $file = $this->fileStorage->load($fid);
210 $file_url = file_create_url($file->getFileUri());
211 // Transform absolute image URLs to relative image URLs: prevent problems
212 // on multisite set-ups and prevent mixed content errors.
213 $file_url = file_url_transform_relative($file_url);
214 $form_state->setValue(['attributes', 'src'], $file_url);
215 $form_state->setValue(['attributes', 'data-entity-uuid'], $file->uuid());
216 $form_state->setValue(['attributes', 'data-entity-type'], 'file');
219 // When the alt attribute is set to two double quotes, transform it to the
220 // empty string: two double quotes signify "empty alt attribute". See above.
221 if (trim($form_state->getValue(['attributes', 'alt'])) === '""') {
222 $form_state->setValue(['attributes', 'alt'], '');
225 if ($form_state->getErrors()) {
226 unset($form['#prefix'], $form['#suffix']);
227 $form['status_messages'] = [
228 '#type' => 'status_messages',
231 $response->addCommand(new HtmlCommand('#editor-image-dialog-form', $form));
234 $response->addCommand(new EditorDialogSave($form_state->getValues()));
235 $response->addCommand(new CloseModalDialogCommand());