Last active
August 28, 2020 10:21
-
-
Save jorislucius/40c36be7196d32b213c514c520378587 to your computer and use it in GitHub Desktop.
Rich text editor in a custom Drupal form. Also see A custom Drupal form with multiple file upload. Also see https://www.lucius.digital/en/blog/rich-text-editor-custom-drupal-form-example-code-including-data-sanitization-security
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\ol_messages\Form; | |
use Drupal\Core\Form\FormBase; | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\Component\Utility\Html; | |
use Drupal\ol_messages\Services\OlMessages; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
/** | |
* Class MessageForm. | |
*/ | |
class MessageForm extends FormBase { | |
/** | |
* @var $messages | |
*/ | |
protected $messages; | |
/** | |
* Class constructor. | |
*/ | |
public function __construct(OlMessages $messages) { | |
$this->messages = $messages; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function create(ContainerInterface $container) { | |
return new static( | |
$container->get('olmessages.messages'), | |
); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFormId() { | |
return 'message_form'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$id = null; | |
// For 'edit' mode: do a check here to fill $id. | |
// Build form. | |
$form['message_id'] = [ | |
'#type' => 'hidden', | |
'#default_value' => $id, | |
'#weight' => '0', | |
]; | |
$form['body'] = [ | |
'#type' => 'text_format', | |
'#format' => 'basic_html', | |
'#weight' => '20', | |
'#required' => true, | |
]; | |
return $form; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validateForm(array &$form, FormStateInterface $form_state) { | |
if (strlen($form_state->getValue('body')['value']) <= 3) { | |
// Set an error for the form element with a key of "title". | |
$form_state->setErrorByName('body', $this->t('A message should contain more than 3 characters.')); | |
} | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
// Get data. | |
$id = Html::escape($form_state->getValue('message_id')); | |
$body = $form_state->getValue('body')['value']; | |
$body = check_markup($body,'basic_html'); | |
// Existing, update message. | |
if(is_numeric($id)){ | |
$this->messages->updateMessage($id, $body); | |
} | |
// New, save message. | |
elseif(empty($id)){ | |
$this->messages->saveMessage($body); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment