View source
<?php
namespace Drupal\panopoly_theme\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Extension\ThemeInstallerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Render\RendererInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PanopolyThemeSelectionForm extends FormBase {
protected $themeHandler;
protected $renderer;
protected $themeInstaller;
protected $configFactory;
public function __construct(ThemeHandlerInterface $theme_handler, RendererInterface $renderer, ThemeInstallerInterface $theme_installer, ConfigFactoryInterface $config_factory) {
$this->themeHandler = $theme_handler;
$this->renderer = $renderer;
$this->themeInstaller = $theme_installer;
$this->configFactory = $config_factory;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('theme_handler'), $container
->get('renderer'), $container
->get('theme_installer'), $container
->get('config.factory'));
}
public function getFormId() {
return 'panopoly_theme_selection_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$this
->messenger()
->deleteByType(MessengerInterface::TYPE_STATUS);
$form['#title'] = $this
->t('Choose a theme');
$options = [];
foreach ($this->themeHandler
->rebuildThemeData() as $theme) {
if (!empty($theme->info['hidden']) || strpos($theme
->getName(), 'test') !== FALSE) {
continue;
}
$label = [
'#type' => 'inline_template',
'#template' => '{{ screenshot }}<span><strong>{{ name }}</strong><p>{{ description }}</p></span>',
'#context' => [
'name' => [
'#markup' => $theme->info['name'],
],
'description' => [
'#markup' => $theme->info['description'],
],
'screenshot' => [
'#theme' => 'image',
'#uri' => file_exists($theme->info['screenshot']) ? $theme->info['screenshot'] : drupal_get_path('module', 'system') . '/images/no_screenshot.png',
'#width' => 100,
'#alt' => $theme->info['name'],
],
],
];
$options[$theme
->getName()] = $this->renderer
->renderPlain($label);
}
$form['theme'] = [
'#type' => 'radios',
'#title' => $this
->t('Choose a theme'),
'#title_display' => 'invisible',
'#required' => TRUE,
'#options' => $options,
'#default_value' => 'bartik',
];
$form['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this
->t('Save and continue'),
];
$form['#attached']['library'][] = 'panopoly_theme/selection_form';
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($theme = $form_state
->getValue('theme')) {
$this->themeInstaller
->install([
$theme,
]);
$this->configFactory
->getEditable('system.theme')
->set('default', $theme)
->save();
}
}
}