diff --git a/css_editor.module b/css_editor.module index 53b5a57..53b7710 100644 --- a/css_editor.module +++ b/css_editor.module @@ -51,6 +51,17 @@ function css_editor_form_system_theme_settings_alter(&$form, FormStateInterface '#type' => 'checkbox', '#default_value' => $config->get('enabled'), ); + // Text box for custom file name + $form['css_editor']['custom_filename'] = array( + '#type' => 'textfield', + '#title' => t('Custom Filename (Optional)'), + '#default_value' => $config->get('custom_filename'), + '#size' => 60, + '#maxlength' => 128, + '#pattern' => '[A-Za-z0-9\-_]+', + '#required' => FALSE, + '#description' => t("If you want to save this CSS file with a custom filename, enter that filename here, omitting the file extension.
The filename must include only letters, numbers, dashes, and underscores."), + ); // Editor box. $form['css_editor']['css'] = array( '#type' => 'textarea', @@ -96,6 +107,7 @@ function css_editor_form_system_theme_settings_alter(&$form, FormStateInterface 'url' => $preview_url, ), ); + // Attach CSS and Javascript libraries. $form['#attached']['library'][] = 'css_editor/codemirror'; $form['#attached']['library'][] = 'css_editor/css_editor'; @@ -112,14 +124,29 @@ function _css_editor_theme_settings_form_submit($form, FormStateInterface $form_ if ($theme) { // Save file. $path = 'public://css_editor'; - $file = $path . DIRECTORY_SEPARATOR . $theme . '.css'; + $oldPath = \Drupal::config('css_editor.theme.' . $theme)->get('path'); + + if (!empty($form_state->getValue(['css_editor', 'custom_filename']))) { + // custom path definition + $file = $path . DIRECTORY_SEPARATOR . $form_state->getValue(['css_editor', 'custom_filename']) . '.css'; + } else { + $file = $path . DIRECTORY_SEPARATOR . $theme . '.css'; + } if (\Drupal::service('file_system')->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) { \Drupal::service('file_system')->saveData($form_state->getValue(['css_editor', 'css']), $file, FileSystemInterface::EXISTS_REPLACE); \Drupal::service('file_system')->chmod($file); } + // delete obsolete file + if ($oldPath!=$file) { + \Drupal::logger('css_editor')->notice("Attempting to delete an obsolete file: ".$oldPath); + \Drupal::service('file_system')->delete($oldPath); + } + \Drupal::logger('css_editor')->notice("Saving path: ".$oldPath); + // Save settings. \Drupal::configFactory()->getEditable('css_editor.theme.' . $theme) ->set('enabled', $form_state->getValue(['css_editor', 'enabled'])) + ->set('custom_filename', $form_state->getValue(['css_editor', 'custom_filename'])) ->set('plaintext_enabled', $form_state->getValue(['css_editor', 'plaintext_enabled'])) ->set('autopreview_enabled', $form_state->getValue(['css_editor', 'autopreview_enabled'])) ->set('css', $form_state->getValue(['css_editor', 'css']))