2

Given this form item defined in a custom module;

$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet // array of options pulled from a data source
];

How can I modify the label of each option to include a small image to the right of the text? In my case, the image is stored in the same dataset alongside each label.

I'm going to guess this has something to do with adding a '#theme' attribute, but I haven't been able to determine the entire process for setting that up.

  • Unfortunately, adding images to select options is a tricky thing. See How to add images in select list? – No Sssweat Oct 2 at 19:04
  • Never done this before. Prob you'll have to use template_preprocess_select and create a new variable for the URL. Then copy to your theme's template and modify select.html.twig add the style="background-image:url(image.png) part – No Sssweat Oct 2 at 19:11
  • @NoSssweat yes, that is tricky, but this isn't about select elements — it's about a set of radios. – Aaron Silber Oct 3 at 18:56
  • Ah! then I think my answer below might work, not tested. But Obviously it's hard coded, so all you gotta do is make it dynamic. – No Sssweat Oct 4 at 1:59
0

You'll need to massage the $optionsSet array so it's structured like this:

$optionsSet = [
  'option1' => '<img scr="../images/option1.jpg"/>option 1',
  'option2' => '<img scr="../images/option2.jpg"/>option 2',
];

$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet,
];

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.