Last active
July 7, 2025 23:18
-
-
Save mrkmiller/5f45899249fd983a88826f0f332e649a to your computer and use it in GitHub Desktop.
Add a custom image to a theme settings page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // TODO: Replace THEMENAME with the machine name for your theme. | |
| use Drupal\Core\Form\FormStateInterface; | |
| use Drupal\file\Entity\File; | |
| /** | |
| * Implements hook_form_FORM_ID_alter(). | |
| */ | |
| function THEMENAME_form_system_theme_settings_alter(&$form, FormStateInterface $form_state, $form_id = NULL) { | |
| $form['custom_image'] = [ | |
| '#type' => 'managed_file', | |
| '#title' => t('Custom Image'), | |
| '#description' => t('Upload a custom image to the theme.'), | |
| '#default_value' => theme_get_setting('custom_image'), | |
| '#upload_location' => 'public://theme_images/', | |
| '#upload_validators' => [ | |
| 'file_validate_extensions' => ['png jpg jpeg gif'], | |
| 'file_validate_size' => [25600000], // 25 MB limit | |
| ], | |
| ]; | |
| $form['#submit'][] = '_THEMENAME_custom_image_submit'; | |
| } | |
| /** | |
| * Submit handler for custom image file management. | |
| * | |
| * @param $form | |
| * @param FormStateInterface $form_state | |
| */ | |
| function _THEMENAME_custom_image_submit($form, FormStateInterface $form_state) { | |
| $fid = $form_state->getValue('custom_image'); | |
| $fid = is_array($fid) ? reset($fid) : $fid; | |
| $config = \Drupal::configFactory()->getEditable('THEMENAME.settings'); | |
| $previous_fid = $config->get('custom_image')[0] ?? NULL; | |
| // If nothing changed, return early. | |
| if ($fid == $previous_fid) { | |
| return; | |
| } | |
| // If a previous file exists and is being removed or replaced, delete the old file. | |
| if ($previous_fid) { | |
| if ($old_file = File::load($previous_fid)) { | |
| $old_file->delete(); | |
| } | |
| } | |
| // If a new file is uploaded, make it permanent. | |
| if (!empty($fid)) { | |
| if ($file = File::load($fid)) { | |
| if ($file->isTemporary()) { | |
| $file->setPermanent(); | |
| $file->save(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment