I have a ChoiceType
that is rendered as a series of radio buttons:
foreach ($cards as $card) {
$choices["{$card->brand} **** **** **** {$card->last4}"] = $card->id;
}
$form = $this->createFormBuilder()
->add('card', ChoiceType::class, ['choices' => $choices,'expanded' => true, 'multiple' => false])
->add('Submit', SubmitType::class)
->getForm()
I'd like to have an incrementing id for each choice, something like 'card1', 'card2', etc., but am unsure how to actually do it. The choices themselves are dynamically created - I don't know ahead of time how many choices (if any) will be present.
Ideally, there'd be some kind of internal counter I could access in 'choice_attr' and/or 'choice_label', but I don't see anything like that in the docs. Any ideas?
Create a counter variable outside and count it for each of your choices. For adding the id use the choice_attr option:
$i = 0;
$form = $this->createFormBuilder()
->add('card', ChoiceType::class, [
'choices' => $choices,
'choice_attr' => function() use ($i) {
$i++;
return ['id' => 'choice-'.$i];
},
])