从dataTable的ContextMenu获取列值

时间:2016-12-22 13:48:21

标签: primefaces jsf-2.2

在p:contextMenu的对话框中显示所选行值很容易。但是,是否有一种简单的方法可以显示列值(例如" 2:b")或获取右键单击发生的列索引?

<p:dataTable id="dt" value="#{['a','b','c']}" var="x" selection="#{bean.x}" 
             widgetVar="dtv" selectionMode="single" rowKey="#{x}">
   <p:column>1:#{x}</p:column>
   <p:column>2:#{x}</p:column>
</p:dataTable>
<p:contextMenu for="dt">
   <p:menuitem value="Show" update="di" oncomplete="PF('wv').show()" />
</p:contextMenu>
<p:dialog id="di" widgetVar="wv">X=#{bean.x}</p:dialog>

在JavaEE 7上使用:PF6.0

1 个答案:

答案 0 :(得分:0)

只是想法......

XHTML

我添加了两个<h:inputHidden/>组件和JavaScript函数applySelectedCell,它们在显示上下文菜单之前调用。

<h:form prependId="false">
    <script type="text/javascript">
        function applySelectedCell(event) {
            var cell = $(event.target);
            if (!cell.is('td')) {
                cell = cell.closest('td');
            }
            var row = cell.closest('tr');

            var selectedCell = row.children().index(cell);
            $('#selectedCell').val(selectedCell);
            $('#selectedHtmlValue').val(cell.text());
        }
    </script>
    <h:inputHidden id="selectedCell" value="#{bean.selectedCell}"/>
    <h:inputHidden id="selectedHtmlValue" value="#{bean.selectedHtmlValue}"/>

    <p:dataTable id="dt" value="#{['a','b','c']}" var="x" selection="#{bean.x}"
                 widgetVar="dtv" selectionMode="single" rowKey="#{x}">
        <p:column>1:<div style="background: yellow;">#{x}</div></p:column>
        <p:column>2:#{x}</p:column>
    </p:dataTable>
    <p:contextMenu for="dt" beforeShow="applySelectedCell(event);">
        <p:menuitem value="Show" update="di" oncomplete="PF('wv').show()" />
    </p:contextMenu>
    <p:dialog id="di" widgetVar="wv">
        <div>Cell value (Bean) = #{bean.selectedBeanValue}</div>
        <div>Cell value (HTML) = #{bean.selectedHtmlValue}</div>
    </p:dialog>
</h:form>

支持bean

@ViewScoped
@Named
public class Bean implements Serializable {
    private String x = "a";
    private Integer selectedCell;
    private String selectedHtmlValue;

    public String getX() {
        return x;
    }

    public void setX(String x) {
        this.x = x;
    }

    public Integer getSelectedCell() {
        return selectedCell;
    }

    public void setSelectedCell(Integer selectedCell) {
        this.selectedCell = selectedCell;
    }

    public String getSelectedHtmlValue() {
        return selectedHtmlValue;
    }

    public void setSelectedHtmlValue(String selectedHtmlValue) {
        this.selectedHtmlValue = selectedHtmlValue;
    }

    public String getSelectedBeanValue() {
        if (selectedCell != null) {
            return (selectedCell + 1) + ":" + x;
        } else {
            return x;
        }
    }
}