'PrimeFaces p:focus on p:dataTable Element

I am currently trying to setup an editable data table that uses ajax to maintain focus when a user edits a cell using either JavaScript or a backing bean, because when a cell edit occurs data in other parts of the table will need to be updated, thus the table should be redrawn, unfocusing the focused element. Currently I'm trying to do this using a p:focus, using a CellEditEvent listener to get the component id. Unfortunately, assigning to the variable for the focused component id is not changing which element is focused on the page.

Here is the relevant HTML:

<h:form id="addForm">
    <p:focus id="focusID" for="#{beanView.focus}" />
    <h:panelGroup id="entrypg">
        <p:commandButton id="updateButton" widgetVar="updateButton" update="addForm:myDT" />                         
        <p:dataTable id="myDT" widgetVar="myDT" var="iter" value="#{beanView.valList}" 
                editable="true" editMode="cell">
            <p:ajax event="cellEdit" listener="#{beanView.onCellEdit}" oncomplete="$('#addForm\\\:updateButton').click();"/>
            <p:column headerText="X">
                <p:cellEditor>
                    <f:facet name="output">
                        <h:outputText value="#{iter.x}" />
                    </f:facet>
                    <f:facet name="input">
                        <p:inputText value="#{iter.x}" />
                    </f:facet>
                </p:cellEditor>
            </p:column>
        </p:dataTable>
    </h:panelGroup>
</h:form>

And the cell edit handler in the view:

public void onCellEdit(CellEditEvent edit) {    
    if(edit.getNewValue() != null) {
        focus = edit.getColumn().getChildren().get(0).getClientId();
    }
}

I am also open to better ways one could do this, as I'm unsureif p:focus is designed for this purpose.

Thanks!



Solution 1:[1]

Ok I've gotten it to work using widgets:

function forceFocus(index) {
    var widget = PF('myDT');
    widget.showCellEditor($('[role="gridcell"].ui-editable-column:eq(' + index + ')'));
}

The showCellEditor does pretty much exactly what I need, it highlights a cell and focuses it allowing immediate editing. It also seems to preserve focus between ajax calls.

More logic would be needed if you wanted to do this to a table with more than 1 editable column.

Edit: Ok it seems like its not storing the focus between table redraws, but it should be doable to grab the focus before the table is redrawn and restore it after its redrawn with the above function

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1