Search code examples
javaarraysjsffaceletsselectmanycheckbox

selectManyCheckbox elements are not copying to array when items are checked


Okay, I am not sure why it is saying that my target is not a collection or array because I am trying to put the results of a selectManyCheckbox into an integer array. It is simply a checkbox of 1-50 where the user can select multiple numbers to be stored in an array and displayed later but I keep getting the error message "Target model Type is no a Collection or Array" error reported. Is this something that needs to be saved in an Object array instead of an integer array? I know there are other threads dealing with this same issue but the others that I saw was generally someone using the wrong type of checkbox or someone not storing in an array or collection. Any help would be really appreciated.

<p>
        Pick Your Lotto Numbers
        <h:selectManyCheckbox value="#{lottoBean.numbersPicked}"
                 layout="lineDirection">
        <f:selectItems value="#{lottoBean.numberChoices}"/>
        </h:selectManyCheckbox>
  </p>
  <p>
        <h:commandButton value="Submit"
                         action="next.xhtml"/>
  </p>

And myLottoBean class...

int[]choices = new int[50];
int[]picked;
int[]actual;
int test = 5;

/**
 * Creates a new instance of LottoBean
 */
@SuppressWarnings("empty-statement")
public LottoBean() {
    picked = new int[6];
    actual = new int[6];
}

public void setNumbersPicked(int[] chosen)
{
    for(int i =0; i < 6; i++)
    {
        picked[i] = chosen[i];
    }
}

@SuppressWarnings("empty-statement")
public String getNumbersPicked()
{
    return Arrays.toString(picked);
}

public int[] getNumberChoices()
{
    for (int i = 0; i < 50; i++) 
    {
        choices[i] = i + 1;
    }
    return choices;
}

public String getNumbersDrawn()
{
    Random num = new Random();
    for (int i = 0; i < 6; i++)
    {
        int nextNum = num.nextInt(50);
        int number  = nextNum + 1;
        actual[i] = number;
    }
    return Arrays.toString(actual);
}
}

Solution

  • You selectManyCheckobox value is #{lottoBean.numbersPicked}. This means that you should have property named numbersPicked which is Collection or Array. Example with array:

    private int[] numbersPicked;
    
    public int[] getNumberPicked() {
      return numbersPicked;
    }
    
    public void setNumberPicked(int[] numbersPicked) {
      this.numbersPicked = numbersPicked;
    }
    

    You should have this in your backing bean. Problem is that your getter method returns String.