I have a dynamic list of images, that I want to have a user select via associated radio button in a form. Is there an a way I can do this with the base form api, or is this the kind of thing I'd need to create a custom theme for?
You can do this using CSS.
Add appropriated class from $form then use CSS to add images as background-image.
For example:
$form['example'] = array(
'#type' => 'radios',
'#title' => t('example'),
'#default_value' => 1,
'#options' => array(0 => ('Value 0'), 1 => ('Value 1')),
);
CSS
.form-item-example > labela[for=edit-example-0]{
background-image: url('/path/to/image-0.png');
}
-
I can see how that would work normally, but the images are dynamic - I don't know what they are until runtime, so I can't put them in ahead of time in the css. – elstevenson Sep 29 '16 at 16:01
Okay, the approach that worked with my dynamic list of images
$end_options = [];
foreach ($dynamic_list_of_items as $item)
{
$end_options[$item['option_key']] = $item['title'].'<br/><img src="/'.$item['image_path'].'"/>';
}
$form['items'] = [
'#type' => 'radios',
'#title' => $this->t('Select Item'),
'#description' => $this->t('Choose which item you'd like to use.'),
'#options' => $end_options,
];
IE, you can put rendered html into the '#options' property of a radio button and it will work. Simpler than I thought.