Добрый день. У меня есть реализация drag-and-drop с использованием primefaces. Это для перетаскиваемых.
<p:dataGrid id="availableComputers" value="#{coltsysLab.computer}" var="computer" columns="3" emptyMessage="No Computers Added Yet">
<p:column>
<p:graphicImage id="computer" value="http://localhost:8080/COLTSysResources/resources/images/#{computer.pic}" styleClass="computerImage" rendered="#{computer.status=='AVAILABLE'}"/>
<p:draggable for="computer" revert="true" scope="#{computer.status}" stack=".computerImage"/>
<p:contextMenu for="computer">
<p:menuitem value="Add Information" icon="ui-icon-plusthick" onclick="addInfoDlg.show();" action="#{coltsysLab.passComputerId(computer)}"/>
<p:menuitem process="@this" value="Computer Information" icon="ui-icon-search" oncomplete="viewInfoDlg.show()" action="#{coltsysLab.passComputerId(computer)}"/>
</p:contextMenu>
</p:column>
Это для слотов с возможностью переключения.
<p:dataGrid id="slots" value="#{coltsysLab.op}" var="com1" columns="#{coltsysLab.column}" >
<p:outputPanel id="drop" styleClass="slot">
<p:droppable for="drop" datasource=":organizeForm:availableComputers" tolerance="fit" scope="AVAILABLE">
<p:ajax process="slots" listener="#{coltsysLab.onDrop}" update=":organizeForm:growl :organizeForm:selectedComputers"/>
</p:droppable>
</p:outputPanel>
Я смог получить dragId и dropId через DragDropEvent на бэкэнде. Но как я смогу сохранить положение каждого слота с перетаскиваемым? Я хочу сохранить его в базе данных, чтобы при открытии страницы он отображал сохраненные позиции каждого перетаскиваемого.
-
Я добавил код из предложения kolossus, я хочу получить позицию перетаскиваемого объекта, но здесь он выводит значение null
.
String dropId = event.getDropId();
UIComponent theContainer = FacesContext.getCurrentInstance().getViewRoot().findComponent(":organizeForm:slots");
UIComponent theComponent = FacesContext.getCurrentInstance().getViewRoot().findComponent(":organizeForm:availableComputers:computer");
List<UIComponent> childComponents = theContainer.getChildren();
for (UIComponent child : childComponents) {
System.out.println(child.getClientId());
if (dropId.equals(child.getClientId())) {
GraphicImage gImage = (GraphicImage) theComponent;
String currentPosition = gImage.getStyle();
System.out.println(currentPosition);
}
}
Когда я использую элемент проверки браузера, я могу видеть его стиль, как я смогу получить значение?
Позиция элементов страницы представлена атрибутом style
. Поэтому в вашем случае вам просто нужно получить текущее значение упавшего компонента. Для этого вам нужно получить компонент в представлении его clientId. К сожалению, JSF не предоставляет простой способ получить эту информацию (хотя довольно легко получить компонент по его id
); Я знаю только подход грубой силы:
String dropId = dde.getDropId(); //get the currently dropped component
UIComponent theContainer = FacesContext.getCurrentInstance().getViewRoot().findComponent("slots"); //you need a reference to the drop container
List<UIComponent> childComponents = theContainer.getChildren(); //all dropped components are children of the datagrid
for(UIComponent child: childComponents){
if(dropId.equals(child.getClientId()));{
GraphicImage gImage = (GraphicImage) theComponent;
String currentPosition = gImage.getStyle();
}
}
UIComponent theComponent = FacesContext.getCurrentInstance().getViewRoot().findComponent("availableComputers:computer");
но он возвращает ноль на getStyleslots
в атрибутprocess
прослушивателя drop ajax. Если вы проверите источник элемента просматриваемой страницы, вы заметите, что атрибут style обновлен, но это происходит только на стороне клиента; JSF по-прежнему необходимо информировать об изменении стиля