I'm trying to use Behat to set the value of a CKEditor 5 field. I am using CKEditor 5 with Drupal 9.
For CKEditor 4, I used a gist by johnennewdeeson:
/**
* @Then I fill in wysiwyg on field :locator with :value
*/
public function iFillInWysiwygOnFieldWith($locator, $value) {
$el = $this->getSession()->getPage()->findField($locator);
if (empty($el)) {
throw new ExpectationException('Could not find WYSIWYG with locator: ' . $locator, $this->getSession());
}
$fieldId = $el->getAttribute('id');
if (empty($fieldId)) {
throw new Exception('Could not find an id for field with locator: ' . $locator);
}
$this->getSession()
->executeScript("CKEDITOR.instances[\"$fieldId\"].setData(\"$value\");");
}
This works great with CKEditor 4, but when I try to do the same thing with CKEditor 5, I get the following error:
CKEDITOR is not defined
How can I set the value of CKEditor 5 in Behat/Mink?
As described in How to get the editor instance object from the DOM element?, you can search for ck-editor__editable
and use that to locate the specific editor instance that you need to manipulate.
So the code looks like this:
$this->getSession()
->executeScript(
"
const domEditableElement = document.querySelector(\"$MY_SELECTOR\");
if (domEditableElement.ckeditorInstance) {
const editorInstance = domEditableElement.ckeditorInstance;
if (editorInstance) {
editorInstance.setData(\"$value\");
} else {
throw new Exception('Could not get the editor instance!');
}
} else {
throw new Exception('Could not find the element!');
}
");