mahega
mahega

Reputation: 3351

Prevent "Target Unreachable" when entity is null

I have an focused person object in my bean. Some attributes of this focused person are connected with primefaces elements in the view.

<p:selectOneMenu id="eyeColorSelection"
    value="#{bean.focusedPerson.eyeColor}" disabled="#{bean.noPersonFocused}">
    <f:selectItems
        value="#{bean.eyeColorsToSelect}"
        var="eyeColor" itemLabel="#{eyeColor.i18nLabel}"
        itemValue="#{eyeColor}" />
    <f:ajax
        listener="#{bean.eyeColorSelectionChanged}" />
</p:selectOneMenu>

As expected I got the following exception, if no person is focused (focusedPerson = null).

Caused by: javax.el.PropertyNotFoundException: Target Unreachable, 'focusedPerson' returned null

But how can I handle this? My first idea was to not render the selectOneMenu, if no person is focused, but this is not what I want. The selectOneMenu should always be visible.

Bean code:

private Person focusedPerson

public Person getFocusedPerson() {
    return this.focusedPerson;
}

public EyeColor[] getEyeColorsToSelect() {
    return EyeColor.values();
}

public boolean isNoPersonFocused() {
    return this.focusedPerson == null;
}

Upvotes: 0

Views: 868

Answers (2)

Kukeltje
Kukeltje

Reputation: 12335

I would very simply use two selectOneMenu components, mutually exclusive

<p:selectOneMenu id="eyeColorSelection" value="" 
    rendered="#{bean.noPersonFocused}" disabled="true" />
<p:selectOneMenu id="eyeColorSelection" value="#{bean.focusedPerson.eyeColor}" 
    rendered="#{not bean.noPersonFocused}">
   <f:selectItems value="#{bean.eyeColorsToSelect}" var="eyeColor" 
      itemLabel="#{eyeColor.i18nLabel}" itemValue="#{eyeColor}" />
      <f:ajax listener="#{bean.eyeColorSelectionChanged}" /> 
</p:selectOneMenu>

Upvotes: 2

Predrag Maric
Predrag Maric

Reputation: 24433

No way around it, if the object is null, you can't target its attributes.

I would use the rendered approach, but with an addition of output label that would print an appropriate message if focusedPerson is null (it would render only if focusedPerson is null).

Another common approach (but this depends on the use case) is to keep the value of p:selectOneMenu in a separate bean attribute, and set it to focusedPerson in a separate action (save, update, or anything else).

<p:selectOneMenu id="eyeColorSelection"
    value="#{bean.eyeColor}">
...

 

public void save() {
    ...
    if (getFocusedPerson() != null) {
        getFocusedPerson().setEyeColor(getEyeColor());
    }
    ...
}

Upvotes: 1

Related Questions