mawburn
mawburn

Reputation: 2336

How to check if element is null or empty in a field constructor?

Similar to hasErrors

<div class="form-group @if(elements.hasErrors) {error}">

    @** this does not work **@
    @if(!elements.label.isEmpty && elements.label != null)
        <label for="@elements.id">@elements.label</label>
    }

    @elements.input

    @** this does not work **@
    @if(!elements.infos.isEmpty && elements.infos != null) {
      <p class="help-inline">@elements.infos.mkString(", ")</p>
    }

    @if(elements.hasErrors) {
        <p class="help-inline">@elements.errors.mkString(", ")</p>
    }
</div>

Even checking for an empty string would be fine. I can't figure out how to do either.

In the view:

@inputText(
    loginForm("member"),
    'placeholder -> "email or username",
    '_help -> "",
    '_label -> null,
    'class -> "form-control"
)

I am using Play Framework 2.2.x

Upvotes: 2

Views: 5567

Answers (2)

estmatic
estmatic

Reputation: 3449

First, you have to flip your logic around. You always check for null first, otherwise you're potentially trying to call a method on a null.

Second, it would help if you included the actual error you are getting when you post a question here. Don't just say it "throws errors".

From my quick test it looked like it was complaining about the isEmpty method not existing for Scala's Any class. It does, however, have a toString which you can call first to get what you want.

@if(elements.label != null && !elements.label.toString.isEmpty) {
  ...
}

Upvotes: 4

Dylan
Dylan

Reputation: 13924

I think you have a mistake in your boolean logic. Your title says "null or empty" but your code says "not(empty) or not(null)".

You probably want to use "and" instead of "or", i.e.

@if(elements.label != null && !elements.label.isEmpty) {
  <label>...</label>
}

Upvotes: 1

Related Questions