View source
<?php
namespace Drupal\asset_injector\Form;
use Psr\Log\LoggerInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\Plugin\PluginFormFactoryInterface;
use Drupal\Core\Executable\ExecutableManagerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
class AssetInjectorFormBase extends EntityForm {
protected $logger;
protected $entity;
protected $manager;
protected $dispatcher;
protected $language;
protected $themeHandler;
protected $contextRepository;
protected $pluginFormFactory;
public static function create(ContainerInterface $container) {
return new static($container
->get('logger.factory')
->get('asset_injector'), $container
->get('plugin.manager.condition'), $container
->get('context.repository'), $container
->get('language_manager'), $container
->get('theme_handler'), $container
->get('plugin_form.factory'));
}
public function __construct(LoggerInterface $logger, ExecutableManagerInterface $manager, ContextRepositoryInterface $context_repository, LanguageManagerInterface $language, ThemeHandlerInterface $theme_handler, PluginFormFactoryInterface $plugin_form_manager) {
$this->logger = $logger;
$this->manager = $manager;
$this->contextRepository = $context_repository;
$this->language = $language;
$this->themeHandler = $theme_handler;
$this->pluginFormFactory = $plugin_form_manager;
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['#tree'] = TRUE;
$form_state
->setTemporaryValue('gathered_contexts', $this->contextRepository
->getAvailableContexts());
$entity = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Label'),
'#maxlength' => 255,
'#default_value' => $entity
->label(),
'#description' => $this
->t('Label for the @type.', [
'@type' => $entity
->getEntityType()
->getLabel(),
]),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $entity
->id(),
'#machine_name' => [
'exists' => '\\' . $entity
->getEntityType()
->getClass() . '::load',
'replace_pattern' => '[^a-z0-9_]+',
'replace' => '_',
],
'#disabled' => !$entity
->isNew(),
];
$form['code'] = [
'#type' => 'textarea',
'#title' => $this
->t('Code'),
'#description' => $this
->t('The actual code goes in here.'),
'#rows' => 10,
'#default_value' => $entity->code,
'#required' => TRUE,
'#prefix' => '<div>',
'#suffix' => '<div class="resizable"><div class="ace-editor"></div></div></div>',
];
$form['conditions'] = $this
->buildConditionsInterface([], $form_state);
$form['conditions']['#weight'] = 99;
$form['conditions_and_or'] = [
'#type' => 'details',
'#title' => $this
->t('Condition Requirements'),
'#group' => 'conditions_tabs',
'#weight' => 999,
'#tree' => FALSE,
];
$form['conditions_and_or']['conditions_require_all'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Require all conditions'),
'#description' => $this
->t('Check to require all conditions. Leave uncheck to require any condition.'),
'#default_value' => $entity->conditions_require_all,
];
$form['#attached']['library'][] = 'asset_injector/ace-editor';
return $form;
}
protected function buildConditionsInterface(array $form, FormStateInterface $form_state) {
$form['conditions_tabs'] = [
'#type' => 'vertical_tabs',
'#title' => $this
->t('Conditions'),
'#parents' => [
'conditions_tabs',
],
'#attached' => [
'library' => [
'asset_injector/asset_injector',
],
],
];
$conditions = $this->entity
->getConditions();
foreach ($this->manager
->getDefinitionsForContexts($form_state
->getTemporaryValue('gathered_contexts')) as $condition_id => $definition) {
if ($condition_id == 'language' && !$this->language
->isMultilingual()) {
continue;
}
$condition_config = isset($conditions[$condition_id]) ? $conditions[$condition_id] : [];
$condition = $this->manager
->createInstance($condition_id, $condition_config);
$form_state
->set([
'conditions',
$condition_id,
], $condition);
$condition_form = $condition
->buildConfigurationForm([], $form_state);
$condition_form['#type'] = 'details';
$condition_form['#title'] = $condition
->getPluginDefinition()['label'];
$condition_form['#group'] = 'conditions_tabs';
if ($condition_id == 'current_theme') {
$condition_form['theme']['#multiple'] = TRUE;
}
$form[$condition_id] = $condition_form;
}
if (isset($form['node_type'])) {
$form['node_type']['#title'] = $this
->t('Content types');
$form['node_type']['bundles']['#title'] = $this
->t('Content types');
$form['node_type']['negate']['#type'] = 'hidden';
$form['node_type']['negate']['#value'] = $form['node_type']['negate']['#default_value'];
}
if (isset($form['request_path'])) {
$form['request_path']['#title'] = $this
->t('Pages');
$form['request_path']['negate']['#type'] = 'radios';
$form['request_path']['negate']['#default_value'] = (int) $form['request_path']['negate']['#default_value'];
$form['request_path']['negate']['#title_display'] = 'invisible';
$form['request_path']['negate']['#options'] = [
$this
->t('Show for the listed pages'),
$this
->t('Hide for the listed pages'),
];
}
return $form;
}
public function actionsElement(array $form, FormStateInterface $form_state) {
$element = parent::actionsElement($form, $form_state);
$element['saveContinue'] = [
'#type' => 'submit',
'#value' => $this
->t('Save and Continue Editing'),
'#name' => 'save_continue',
'#submit' => [
'::submitForm',
'::save',
],
'#weight' => 7,
];
return $element;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$conditions = $form_state
->getValue('conditions');
foreach ($conditions as $condition_id => &$values) {
if ($condition_id == 'current_theme' && empty($values['theme'])) {
$values['theme'] = '';
$form_state
->setValue('conditions', $conditions);
}
if (array_key_exists('negate', $values)) {
$form_state
->setValue([
'conditions',
$condition_id,
'negate',
], (bool) $values['negate']);
}
$condition = $form_state
->get([
'conditions',
$condition_id,
]);
$values = $form_state
->getValue([
'conditions',
$condition_id,
]);
foreach ($values as &$value) {
if (is_array($value)) {
$value = array_filter($value);
}
}
$form_state
->setValue([
'conditions',
$condition_id,
], $values);
$condition
->validateConfigurationForm($form['conditions'][$condition_id], SubformState::createForSubform($form['conditions'][$condition_id], $form, $form_state));
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$code = $form_state
->getValue('code');
$code = preg_replace('~\\r\\n?~', "\n", $code);
$form_state
->setValue('code', $code);
parent::submitForm($form, $form_state);
foreach ($form_state
->getValue('conditions') as $condition_id => $values) {
$condition = $form_state
->get([
'conditions',
$condition_id,
]);
$condition
->submitConfigurationForm($form['conditions'][$condition_id], SubformState::createForSubform($form['conditions'][$condition_id], $form, $form_state));
$condition_configuration = $condition
->getConfiguration();
$this->entity
->getConditionsCollection()
->addInstanceId($condition_id, $condition_configuration);
}
}
public function save(array $form, FormStateInterface $form_state) {
$entity = $this->entity;
$status = $entity
->save();
switch ($status) {
case SAVED_NEW:
$message = $this
->t('Created the %label Asset Injector.', [
'%label' => $entity
->label(),
]);
$log = '%type asset %id created';
break;
default:
$message = $this
->t('Saved the %label Asset Injector.', [
'%label' => $entity
->label(),
]);
$log = '%type asset %id saved';
}
$this
->messenger()
->addMessage($message);
$this->logger
->notice($log, [
'%type' => $entity
->getEntityTypeId(),
'%id' => $entity
->id(),
]);
$trigger = $form_state
->getTriggeringElement();
if (isset($trigger['#name']) && $trigger['#name'] != 'save_continue') {
$form_state
->setRedirectUrl($entity
->toUrl('collection'));
}
else {
$form_state
->setRedirectUrl($entity
->toUrl());
}
}
}