这个简单的自定义组件可以用来包裹其他组件,如果使用属性 disabled="true" 或评估为 true 的 EL 表达式,则会禁用它们。它的预期工作方式是,如果包装的组件已经被禁用,那么如果使用 disabledPanel(或 ajax 重新呈现)并将其设置为 disabled="true",则它不会被启用。该组件仅尝试禁用 UIInput 和 UICommand 组件,我认为这样是可以的,但也可以更改。
xmlns:fnc="http://myco.co.uk/fnc"
...
<fnc:disablePanel disabled="#{bean.isItDisabled}">
<h:inputText/>
...
</fnc:disablePanel>
...
UIDisablePanel.java
package uk.co.myco.component;
import java.io.IOException;
import javax.faces.component.*;
import javax.faces.context.FacesContext;
@FacesComponent("uk.co.myco.component.UIDisablePanel")
public class UIDisablePanel extends UIComponentBase {
private enum PropertyKeys {
disabled;
}
public UIDisablePanel() {
setRendererType(null);
}
@Override
public void encodeBegin(FacesContext context) throws IOException {
boolean toDisable = isDisabled();
processDisablePanel(this, toDisable);
}
public void processDisablePanel(UIComponent root, boolean toDisable) {
for (UIComponent c : root.getChildren()) {
if (c instanceof UIInput || c instanceof UICommand) {
if(toDisable) {
Boolean curState = (Boolean) c.getAttributes().get("disabled");
if(curState == null || curState == false) {
c.getAttributes().put("UIPanelDisableFlag", true);
c.getAttributes().put("disabled", true);
}
}
else {
if(c.getAttributes().get("UIPanelDisableFlag") != null) {
c.getAttributes().remove("UIPanelDisableFlag");
c.getAttributes().put("disabled", false);
}
}
}
if (c.getChildCount() > 0) {
processDisablePanel(c, toDisable);
}
}
}
@Override
public String getFamily() {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean isDisabled() {
return (boolean) getStateHelper().eval(PropertyKeys.disabled, false);
}
public void setDisabled(boolean disabled) {
getStateHelper().put(PropertyKeys.disabled, disabled);
}
}
disablepanel.taglib.xml
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd">
<namespace>http://myco.co.uk/fnc</namespace>
<tag>
<tag-name>disablePanel</tag-name>
<component>
<component-type>uk.co.myco.component.UIDisablePanel</component-type>
</component>
<attribute>
<name>disabled</name>
</attribute>
</tag>
</facelet-taglib>
<h:form disable="#{bean.permission}" />
。 - SomeFatMan