【问题标题】:Primefaces set focus from beanPrimefaces 从 bean 设置焦点
【发布时间】:2018-03-05 14:00:51
【问题描述】:

如果我想将焦点设置到验证失败的字段。我可以使用<p:focus context='@form'/> 来实现这个简单的案例,很简单。但我的问题是,并非所有验证都可以在前端执行。例如,我希望用户输入用户名,当用户提交表单时,bean 会检查数据库中用户名是否已存在,如果存在,则将错误消息设置到字段并设置焦点。在这种情况下,<p:focus /> 标签不再起作用,因为它实际上已经通过了前端验证。

我找到了this 答案并尝试实现它,我会说它只能部分工作。为什么?因为如果您通过为其声明一个变量从 bean 手动设置焦点,它将覆盖 <p:focus context='@form'/> 标记。当这个焦点标签失去作用时,如果有任何前端验证失败,它就不会再把焦点带到那个特定的字段上。

我尝试的是使用widgetVar 来执行焦点。我为我的字段声明了一个 widgetVar 名称,比如说 widgetVar='username',在托管 bean 上,我使用以下代码来关注它:

RequestContext.getCurrentInstance().execute("PF('username').focus()");

不幸的是,它不起作用。不确定execute() 是否以这种方式不起作用或语句有问题。对不起,我的英语不好,任何帮助或建议将不胜感激。

【问题讨论】:

  • 您的 Primefaces 版本是多少?
  • @JorgeCampos Primefaces 6.1

标签: jsf primefaces


【解决方案1】:

PrimeFaces 6.3 及更高版本

如 cmets 中所述,PrimeFaces class 中提供了一个实用方法:

PrimeFaces.current().focus(String expression)

表达式相对于view root,或者:

PrimeFaces.current().focus(String expression, UIComponent base)

表达式相对于提供的基本组件。

PrimeFaces 6.3 之前

只需检查 PrimeFaces 在focus renderer 中的作用:

ResponseWriter writer = context.getResponseWriter();
UIComponent forComponent = SearchExpressionFacade.resolveComponent(
        context, focus, focus.getFor());

String clientId = forComponent.getClientId(context);

writer.write("$(function(){");
writer.write("PrimeFaces.focus('" + clientId + "');");
writer.write("});");

你可以简单地在一个动作中做同样的事情:

public void focus(String expression) {
  FacesContext context = FacesContext.getCurrentInstance();
  UIComponent forComponent = SearchExpressionFacade.resolveComponent(
    context,
    UIComponent.getCurrentComponent(context),
    expression
  );
  String clientId = forComponent.getClientId();
  RequestContext.getCurrentInstance().execute("PrimeFaces.focus('" + clientId + "');");
}

请注意,我使用触发该操作的命令按钮作为搜索表达式的来源,您不需要在此处使用$(function(){...}

您唯一需要做的是,不要将clientId 作为操作方法的参数,而是创建代码来确定哪个组件应该获得焦点。

用 XHTML 测试:

<h:form id="main">
  <p:inputText id="text1"/>
  <p:inputText id="text2"/>
  <p:commandButton value="Focus 1" action="#{myBean.focus('text1')}"/>
  <p:commandButton value="Focus 2" action="#{myBean.focus('text2')}"/>
  <p:commandButton value="Form" action="#{myBean.focus('@form')}"/>
</h:form>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-05-22
  • 2017-02-04
  • 1970-01-01
  • 2013-12-21
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多