Skip to content

Instantly share code, notes, and snippets.

@mrkmiller
Last active July 7, 2025 23:18
Show Gist options
  • Select an option

  • Save mrkmiller/5f45899249fd983a88826f0f332e649a to your computer and use it in GitHub Desktop.

Select an option

Save mrkmiller/5f45899249fd983a88826f0f332e649a to your computer and use it in GitHub Desktop.
Add a custom image to a theme settings page
<?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