How to set fields in `Editor`/`EditorWebView`

I’m making a button in the AddCards menu, that pulls in data from an online dictionary, and sets the fields accordingly.

I found the Editor class, but it seems very complicated with the fields themselves in JS. I couldn’t find any methods to edit the fields programatically in that file.

Would I need to run my own JS similar to how loadNote works? Is there some way to sync the note object with the JS, edit it, then send it back to JS?

I’m not really sure how to do this (this is my first addon) so I’d appreciate the help :slight_smile:

I’m not allowed to put links in my post, so here are the files I used for reference:

ankitects/anki/blob/main/qt/aqt/addcards.py
ankitects/anki/blob/main/qt/aqt/editor.py

You can access field content with note.items(). It returns a list of key-value pairs, so you can read each field’s content with value and decide if changes should be made.

After you’ve made changes, call note.flush() to write them to the database (except in add mode).

def write_field_contents(note, contents : [str], addMode=False):
    for i, (key, value) in enumerate(note.items()):
        note[key] = contents[i]

    if not addMode:
        note.flush()
3 Likes

Thanks, this seems to do something, when I close it now asks to save changes.
The UI is not updating, however.

Managed to fix this with a call to loadNoteKeepingFocus. Thanks so much!

3 Likes