Setting selected elements in a BaseElementSelectorModal (or BaseElementIndex) I'm writing a Javascript based plugin which creates an instance of Craft.BaseElementSelectorModal.

When the modal is created, I'd like to have some of the entries in the modal's element index auto-selected (i.e. their containers should have the sel class added, just like when the user actually selects an entry). I have an array of entry IDs to work with, but I'm struggling to find a way to actually set the element index' selected entries.

As far as I can tell, there aren't any parameters I can set to the BaseElementSelectorModal (aside from disabledElementIds, which I can't use as I don't actually want the entries to be disabled, only selected).

I can get to the modal's BaseElementIndex instance – is there a way to programmatically select an array of entries?
After much exploring in craft.js, I've concluded that this can't be done in a clean way.

However, I found a workaround which seems to do the trick.

First, here's (a simplified version of) the code that creates the modal (which is stored in the variable modal):

var modal = new Craft.BaseElementSelectorModal('Entry', {
    criteria: criteria,
    onSelect: onElementSelect
});


After creating the modal, I use setInterval to look up the modal.elementIndex property. The reason I use a poller is that this property is actually null until the internal AJAX call to actions/elementIndex/getElements is completed. Anyway, I poll the elementIndex property every 10ms, until the property is found (or after 5 seconds have passed, when its safe to assume something has gone awry).

Finally, the element index' method selectElementAfterUpdate is used to select the entries. The method only takes a single entry ID, so I have to call it once for every entry ID in the entryIds array.

var pollCount = 0;
var pollInterval = 10;

var poller = setInterval(function () {
    pollCount++;
    if (pollInterval * pollCount &gt;= 5000) clearInterval(poller);
    if (modal.elementIndex)
    {
        clearInterval(poller);
        $.map(entryIds, function (entryId) {
            modal.elementIndex.selectElementAfterUpdate(entryId);
        });
    }
}, pollInterval);


Not very smooth! But it works.