View source
<?php
namespace Drupal\webform_composite\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\webform\Plugin\WebformElementManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WebformCompositeSourceForm extends EntityForm {
protected $supportedProperties = [
'key' => 'key',
'type' => 'type',
'title' => 'title',
'help' => 'help',
'description' => 'description',
'options' => 'options',
'required' => 'required',
];
protected $entityTypeManager;
protected $currentUser;
protected $elementManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user, WebformElementManagerInterface $element_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->currentUser = $current_user;
$this->elementManager = $element_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.query'), $container
->get('current_user'), $container
->get('plugin.manager.webform.element'));
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$composite = $this->entity;
$description = $this
->t('Key-value pairs MUST be specified as "safe_key: \'Some readable option\'". Use of only alphanumeric characters and underscores is recommended in keys. One option per line. Option groups can be created by using just the group name followed by indented group options.');
$description .= ' ' . $this
->t("Descriptions, which are only applicable to radios and checkboxes, can be delimited using ' -- '.");
$form['source'] = [
'#type' => 'webform_codemirror',
'#mode' => 'yaml',
'#title' => $this
->t('Source (YAML)'),
'#description' => $description,
'#default_value' => $composite
->getElementsRaw(),
];
$form['#attached']['library'][] = 'webform/webform.codemirror.yaml';
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function save(array $form, FormStateInterface $form_state) {
$composite = $this->entity;
$composite
->set('elements', $form_state
->getValue('source'));
$status = $composite
->save();
if ($status) {
$this
->messenger()
->addMessage($this
->t('Composite %label has been saved.', [
'%label' => $composite
->label(),
]));
}
else {
$this
->messenger()
->addMessage($this
->t('Composite %label was not saved.', [
'%label' => $composite
->label(),
]), 'error');
}
$form_state
->setRedirect('entity.webform_composite.list');
}
public function exist($id) {
$entity = $this->entityTypeManager
->getStorage('webform_composite')
->getQuery()
->condition('id', $id)
->execute();
return (bool) $entity;
}
}