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.
19 class EditorImageDialog extends FormBase {
22 * The file storage service.
24 * @var \Drupal\Core\Entity\EntityStorageInterface
26 protected $fileStorage;
29 * Constructs a form object for image dialog.
31 * @param \Drupal\Core\Entity\EntityStorageInterface $file_storage
32 * The file storage service.
34 public function __construct(EntityStorageInterface $file_storage) {
35 $this->fileStorage = $file_storage;
41 public static function create(ContainerInterface $container) {
43 $container->get('entity.manager')->getStorage('file')
50 public function getFormId() {
51 return 'editor_image_dialog';
57 * @param \Drupal\editor\Entity\Editor $editor
58 * The text editor to which this dialog corresponds.
60 public function buildForm(array $form, FormStateInterface $form_state, Editor $editor = NULL) {
61 // This form is special, in that the default values do not come from the
62 // server side, but from the client side, from a text editor. We must cache
63 // this data in form state, because when the form is rebuilt, we will be
64 // receiving values from the form, instead of the values from the text
65 // editor. If we don't cache it, this data will be lost.
66 if (isset($form_state->getUserInput()['editor_object'])) {
67 // By convention, the data that the text editor sends to any dialog is in
68 // the 'editor_object' key. And the image dialog for text editors expects
69 // that data to be the attributes for an <img> element.
70 $image_element = $form_state->getUserInput()['editor_object'];
71 $form_state->set('image_element', $image_element);
72 $form_state->setCached(TRUE);
75 // Retrieve the image element's attributes from form state.
76 $image_element = $form_state->get('image_element') ?: [];
79 $form['#tree'] = TRUE;
80 $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
81 $form['#prefix'] = '<div id="editor-image-dialog-form">';
82 $form['#suffix'] = '</div>';
84 // Construct strings to use in the upload validators.
85 $image_upload = $editor->getImageUploadSettings();
86 if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) {
87 $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height'];
92 $max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size());
94 $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL;
95 $fid = $existing_file ? $existing_file->id() : NULL;
98 '#title' => $this->t('Image'),
99 '#type' => 'managed_file',
100 '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'],
101 '#default_value' => $fid ? [$fid] : NULL,
102 '#upload_validators' => [
103 'file_validate_extensions' => ['gif png jpg jpeg'],
104 'file_validate_size' => [$max_filesize],
105 'file_validate_image_resolution' => [$max_dimensions],
110 $form['attributes']['src'] = [
111 '#title' => $this->t('URL'),
112 '#type' => 'textfield',
113 '#default_value' => isset($image_element['src']) ? $image_element['src'] : '',
114 '#maxlength' => 2048,
118 // If the editor has image uploads enabled, show a managed_file form item,
119 // otherwise show a (file URL) text form item.
120 if ($image_upload['status']) {
121 $form['attributes']['src']['#access'] = FALSE;
122 $form['attributes']['src']['#required'] = FALSE;
125 $form['fid']['#access'] = FALSE;
126 $form['fid']['#required'] = FALSE;
129 // The alt attribute is *required*, but we allow users to opt-in to empty
130 // alt attributes for the very rare edge cases where that is valid by
131 // specifying two double quotes as the alternative text in the dialog.
132 // However, that *is* stored as an empty alt attribute, so if we're editing
133 // an existing image (which means the src attribute is set) and its alt
134 // attribute is empty, then we show that as two double quotes in the dialog.
135 // @see https://www.drupal.org/node/2307647
136 $alt = isset($image_element['alt']) ? $image_element['alt'] : '';
137 if ($alt === '' && !empty($image_element['src'])) {
140 $form['attributes']['alt'] = [
141 '#title' => $this->t('Alternative text'),
142 '#placeholder' => $this->t('Short description for the visually impaired'),
143 '#type' => 'textfield',
145 '#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).'),
146 '#default_value' => $alt,
147 '#maxlength' => 2048,
150 // When Drupal core's filter_align is being used, the text editor may
151 // offer the ability to change the alignment.
152 if (isset($image_element['data-align']) && $editor->getFilterFormat()->filters('filter_align')->status) {
154 '#title' => $this->t('Align'),
157 'none' => $this->t('None'),
158 'left' => $this->t('Left'),
159 'center' => $this->t('Center'),
160 'right' => $this->t('Right'),
162 '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'],
163 '#wrapper_attributes' => ['class' => ['container-inline']],
164 '#attributes' => ['class' => ['container-inline']],
165 '#parents' => ['attributes', 'data-align'],
169 // When Drupal core's filter_caption is being used, the text editor may
170 // offer the ability to in-place edit the image's caption: show a toggle.
171 if (isset($image_element['hasCaption']) && $editor->getFilterFormat()->filters('filter_caption')->status) {
173 '#title' => $this->t('Caption'),
174 '#type' => 'checkbox',
175 '#default_value' => $image_element['hasCaption'] === 'true',
176 '#parents' => ['attributes', 'hasCaption'],
181 '#type' => 'actions',
183 $form['actions']['save_modal'] = [
185 '#value' => $this->t('Save'),
186 // No regular submit-handler. This form only works via JavaScript.
189 'callback' => '::submitForm',
200 public function submitForm(array &$form, FormStateInterface $form_state) {
201 $response = new AjaxResponse();
203 // Convert any uploaded files from the FID values to data-entity-uuid
204 // attributes and set data-entity-type to 'file'.
205 $fid = $form_state->getValue(['fid', 0]);
207 $file = $this->fileStorage->load($fid);
208 $file_url = file_create_url($file->getFileUri());
209 // Transform absolute image URLs to relative image URLs: prevent problems
210 // on multisite set-ups and prevent mixed content errors.
211 $file_url = file_url_transform_relative($file_url);
212 $form_state->setValue(['attributes', 'src'], $file_url);
213 $form_state->setValue(['attributes', 'data-entity-uuid'], $file->uuid());
214 $form_state->setValue(['attributes', 'data-entity-type'], 'file');
217 // When the alt attribute is set to two double quotes, transform it to the
218 // empty string: two double quotes signify "empty alt attribute". See above.
219 if (trim($form_state->getValue(['attributes', 'alt'])) === '""') {
220 $form_state->setValue(['attributes', 'alt'], '');
223 if ($form_state->getErrors()) {
224 unset($form['#prefix'], $form['#suffix']);
225 $form['status_messages'] = [
226 '#type' => 'status_messages',
229 $response->addCommand(new HtmlCommand('#editor-image-dialog-form', $form));
232 $response->addCommand(new EditorDialogSave($form_state->getValues()));
233 $response->addCommand(new CloseModalDialogCommand());