HidePreviewConfigForm.php in Hide Preview Button 8
File
src/Form/HidePreviewConfigForm.php
View source
<?php
namespace Drupal\hide_preview\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
class HidePreviewConfigForm extends ConfigFormBase {
const FORM_ID = 'hide_preview_config_form';
public function getFormId() {
return self::FORM_ID;
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$config = $this
->config('hide_preview.settings');
$formNames = $config
->get('hide_preview.form_names');
if (empty($formNames)) {
$formnames = '';
}
else {
$formNames = implode(PHP_EOL, $formNames);
}
$form['form_names'] = [
'#type' => 'textarea',
'#title' => $this
->t('Form names'),
'#default_value' => $formNames,
'#description' => $this
->t("<ul><li>Write only one form name per line</li>\n <li>Do not use comma as a separator</li>\n <li>Use either a form name as a string or a regular expression.<ul>\n <li>Check if the <i>form_id</i> begins with the pattern \n <i>contact_message_</i></li>\n <li>Check if the <i>form_id</i> matches the regexp \n <i>/contact_message_*/</i></li>\n </ul></ul>"),
'#required' => FALSE,
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$formNames = $form_state
->getValue('form_names');
$formNames = $this
->multiline2Array($formNames);
foreach ($formNames as &$name) {
$name = trim($name);
preg_match('/[^\\w]+/', $name, $matches);
if (count($matches)) {
if (@preg_match($name, NULL) === FALSE) {
$form_state
->setErrorByName('form_names', $this
->t('Form name "%name" contains non wordy characters and is
not a regexp.', [
'%name' => $name,
]));
}
}
}
parent::validateForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$formNames = $form_state
->getValue('form_names');
$formNames = $this
->multiline2Array($formNames);
$config = $this
->config('hide_preview.settings');
$config
->set('hide_preview.form_names', $formNames);
$config
->save();
parent::submitForm($form, $form_state);
}
public function multiline2Array($multiline = '') {
$array = preg_split("/\r\n/", $multiline);
$array = array_filter($array, [
$this,
'emptyStringFilter',
]);
return $array;
}
protected function getEditableConfigNames() {
return [
'hide_preview.settings',
];
}
private function emptyStringFilter($value) {
return $value !== NULL && $value !== '';
}
}