Firstly, I want to express my gratitude for Veve. However, his answer was concise and lacking in detail. I managed to convert the choice type to radio buttons by setting 'expanded => true' and 'multiple => false' parameters. For further information, refer to the Symfony Select Tag documentation.
$builder->add('risk', ChoiceType::class, [
'choices' => [
'level-0' => 1,
'level-1' => 2,
'level-2' => 3,
'level-3' => 4,
'level-4' => 5
],
'choice_attr' => function($choice, $key, $value) {
return ['class' => 'risk_'.strtolower($key)];
},
'expanded' => true,
'multiple' => false,
'placeholder' => false
]);
Subsequently, I utilized a table to exhibit the form values.
<table class="table risk-colors-table">
<tr>
<td class="risk_level-text">Text</td>
<td class="risk-option level-0">{{ form_row(form.risk[0])}}</td>
<td class="risk-option level-1">{{ form_row(form.risk[1])}}</td>
<td class="risk-option level-2">{{ form_row(form.risk[2])}}</td>
<td class="risk-option level-3">{{ form_row(form.risk[3])}}</td>
<td class="risk-option level-4">{{ form_row(form.risk[4])}}</td>
</tr>
</table>
Furthermore, I added CSS styles to enhance the visual appeal using the previously defined classes and to conceal the radio buttons and labels:
.risk_level-text {
vertical-align: center!important;
}
.level-0 {
background: #63d06c;
}
.level-1 {
background: #a7e35c;
}
.level-2 {
background: #fdf74d;
}
.level-3 {
background: #f0a725;
}
.level-4 {
background: #ee0018;
}
.risk-colors-table {
width: 100%;
padding-left: 2px;
}
.risk-colors-table tr {
border:2px solid #d9d9d9;
}
.risk-option {
float: right;
vertical-align: center!important;
border-radius: 25px;
margin-bottom: 25px;
height: 28px;
width:19%;
}
.risk-option label {
visibility: hidden;
text-align: center;
color:white;
vertical-align:middle;
}
.risk-option.active {
border:3px solid #3362b1;
}
.risk-colors-table td {
margin: 10px 1px;
}
In order to activate the radio button upon clicking on the table cell, I incorporated this JavaScript function:
$(function () {
$('.risk-option').click(
function () {
$(this).addClass('active').siblings().removeClass('active');
var $radioBtn = $('.risk-option.active input[type="radio"]');
if ($radioBtn.is(':checked') === true) {
$radioBtn.filter('input[type="radio"]').prop('checked', true);
}
}
);
});
I dedicated considerable effort to this task, hoping that it may benefit others. The end result accurately resembles the image depicted in my initial query.