3

I am displaying some records in table format on my Visualforce Page. I want to check if a Map instance is empty before displaying it. I have tried with:

.Size()

and also with:

rendered="{!If(NOT(ISBLANK(cons[0])),true,false)}"

But it is not working. I know one workaround to use a Boolean property in the controller and set the rendered attribute based on that. But I don't want to create extra variables in the controller. Can we achieve this logical check in the Visualforce Page itself?

  • With rendered="{!NOT(ISBLANK(cons[0]))}" ? – SF_user Jan 3 '17 at 14:21
  • 3
    Possible duplicate of Is it possible to test list size from a VisualForce page? – Adrian Larson Jan 3 '17 at 15:24
  • I think whilst the "solution" is the same, the difference in the wording and context of the question means this might be a valid question/answer as would be expected to find in a search. People looking to find if a "map is empty" in visualforce might not search for "how to test a list size" ? (just my thoughts) – Simon Lawrence Jan 3 '17 at 17:19
  • Just because we close as a dupe doesn't mean it's a bad question! But it helps link them as essentially the same issue, which I think they are here. And it doesn't at all hurt the search-ability of this question. If it did, I'd probably reconsider my vote. – Adrian Larson Jan 3 '17 at 17:57
  • @AdrianLarson while it should be a dupe, since maps and lists SHOULD work the same, unfortunately they don't; using map.size as would work on a list, comes up with a compile time error. – Aequitas Nov 24 '17 at 3:31
9

The below solution does not work reporting this compile error when the page is saved:

Unknown property 'cons.size'

If cons is a map field of the controller, I would expect this to work:

rendered="{! cons.size > 0 }"

as a reference to cons is a reference to the map keys.

  • 1
    For Map , Size is not valid in visual force page . Thanks – veera Jan 4 '17 at 10:47
  • @veera Just tried it and similar permutations and you are right... Looks like an extra controller property is needed. – Keith C Jan 4 '17 at 11:25
5

I have had success with this approach:

rendered="{!NOT(myMap.empty)}"

Note you can always replace IF(condition, true, false) with simply condition. The statements are functionally equivalent, but the former is redundant and bloats compile size.

  • 1
    It is not working for Map. Please suggest any other way to do. Thanks – veera Jan 4 '17 at 10:47
0

It seems that you cannot directly reference the size of a Map in VF. You can add a small helper to return the size, however:

public Integer mapSize {get{
    mapSize = mapVariable.values().size();
    return mapSize;
    }set;}

It is less convenient than getting the value directly on the VF but it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.