How to add ckeditor5 in a form?


This is my actual first attempt to write a form with external html editor in textarea field.

That i have done:

  1. I generated the form using:
    mix phx.gen.html Content Article articles heading:string tag:string slug:string article:text

  2. Updated ecto

  3. Added the CKeditor in in root.html.heex using:

  4. I have added the additional script from here within the article_form.html.heex and i can see the field updated and i can use the editor.

The problem:
When i press submit it gives me error that the field is empty.

What i tried:
I am very bad in JS so please be understanding. I got the idea that i have to collect the data from the editor and ‘send/push’ it to the form somehow (my guess is to the id of the original field) but i can’t get it to work. I have read few other topics from here but i don’t really get how to make it work.

I will appreciate if someone can guide me to the solution.


Can you show some code?
Have you done phx-update=ignore ?

Hey TwistingTwists,

I have not done any phx-update changes. That is all my code in the form. I am not sure even where to put that.

<.simple_form :let={f} for={@changeset} action={@action}>
  <.error :if={@changeset.action}>
    Oops, something went wrong! Please check the errors below.
  <.input field={f[:heading]} type="text" label="Heading" />
  <.input field={f[:tag]} type="text" label="Tag" />
  <.input field={f[:slug]} type="text" label="Slug" />
  <.input field={f[:article]} type="text" label="Article" />
    <.button id="submit">Save Article</.button>

let editor;

    .create( document.querySelector( '#article_article' ) )
    .then( newEditor => {
        editor = newEditor;
    } )
    .catch( error => {
        console.error( error );
    } );

// Assuming there is a <button id="submit">Submit</button> in your application.
editor.model.document.on( 'change:data', () => {
    console.log( editor.getData() );
} );


Sorry, the console.log was me trying to see if something comes out. The actual line is:

    const editorData = editor.getData();

Are you aware about JS hooks ?

1 Like

The problem with that is i am not sure how they are suppose to work exactly. I guess i have to dig into it and see what i can do.

OK, so i figured it out. The editor is expecting to have the textarea instead of text field type. If i change it in the form then all works just fine.

This blog post may be useful to guide you how to setup the editor.

1 Like

Thanks. That will be an upgrade that i might want to do. Funny enough that is a paid feature on the ck editor and with some additional coding it could make it even better than the paid service.