0

Rookie question here, I have an <input> that I'd like to display a User's nested property using Thymeleaf

  • Each User has a Department
  • Every Department has a name

I attempt to access it like by sending a List of User objects to my form

<select id="user">                      
    <option value="" th:text="-Select-"></option>
    <option 
        th:each="user: ${users}" 
        th:value="${user.id}"  
        th:text="${user.name}"
        th:attr="data-department=${user.department.name}">
    </option>
</select>

Thymeleaf can locate the nested department object (returns [object, Object]), but when trying to access the department name a SpringExpressionLanguage Exception when trying to access the name of the department.

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'name' cannot be found on null

I'm still going through the documentation, but haven't found how to access this yet which is probably extremely simple. Any ideas?

1
  • seems to be something wrong with department class. could you provide the code of it? Commented Feb 4, 2016 at 6:43

1 Answer 1

6

Obviously, one of users has no department, hence departemnt is null. Thymeleaf can't get value of property of null. That's why you get error. Try to check that department is not null before output:

<select id="user">                      
        <option value="" th:text="-Select-"></option>
        <option 
            th:each="user: ${users}" 
            th:value="${user.id}"  
            th:text="${user.name}"
            th:attr="data-department=${user.department!=null}?${user.department.name}:'not specified'">
        </option>
    </select>
Sign up to request clarification or add additional context in comments.

1 Comment

First thing I should have checked for. This worked thanks much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.