How can you exhibit choiceType values in Symfony as various hues?

I am struggling to find the right way to save an integer value in my database and display it as a color. Any suggestions on how to achieve this?

Here is what my Form currently looks like:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->add('risk', ChoiceType::class, [
        'choices' => 
            'level.0' => 1,
            'level.1' => 2,
            'level.2' => 3,
            'level.3' => 4,
            'level.4' => 5
        ],
    ]);
}

Ultimately, I would like the form to resemble this design: https://i.sstatic.net/LA4FF.png

Answer №1

If you want to customize the appearance of choices in Symfony forms, you can use choice_attr to assign specific CSS classes to each choice. This allows you to define corresponding styles in your CSS to render the choices according to your preferences:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $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' => 'level_'.strtolower($key)];
        }
    ]);
}

Here's an example of how you could style these choices using CSS (the given colors are just for illustration purposes):

.level_0 {
    color: red;
}
.level_1 {
    color: orange;
}
.level_2 {
    color: yellow;
}
.level_3 {
    color: light_green;
}
.level_4 {
    color: green;
}

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing CSS to Style Images in JavaFX FXML

After creating the FXML structure below, I attempted to define a border in CSS for the Image by using code in the customerform.css file: <VBox id="customerFormPane" styleClass="customerForm" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.exampl ...

Generate separation among the navigation links in HTML/CSS

Just starting out with HTML/CSS and I'm facing an issue with spacing out the items on my nav-link. Specifically, the "collections" and "spark" items are overlapping. Can anyone provide guidance on why this is happening and how I can resolve it? Should ...

Is there a timeline for when Opera will begin supporting the border-radius property

Any updates on the release date for border-radius support? I remember hearing about -o-border-radius in the past, what's the status on that now? ...

Exploring the Date Picker Component in React.js

I am working on a reservation project in React Js and I need to implement a Date picker feature. The calendar view should display time with hours on the left side row and days of the week at the top (example image https://i.sstatic.net/aJ69n.png). After ...

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

It appears that the query parameters are impacting the speed at which the page loads

I am currently developing a project on this platform. It is using c9.io, an innovative browser-based collaborative programming IDE. The index.php file includes the following script: <?php $path = ltrim($_SERVER['REQUEST_URI'], '/&ap ...

What is the method used by Bootstrap to create a darker page background behind a modal?

I am struggling to understand how Bootstrap darkens the background of a page when a modal is displayed. Even though a class is added to the body tag (modal-open), the effect on the background isn't clear to me. Learn more about Bootstrap modals here ...

Tips for effectively sizing a logo within a Bootstrap navbar

<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link ...

Is there a way to divide extensive CSS files using Python?

The issue I am facing is due to the limitations of IE 8 on CSS files. Within my Flask project, some of my CSS files exceed these limits, causing them not to render correctly. Is there a way to split CSS files using Python in order to ensure that they meet ...

Is there a way to specify both a fixed width and a custom resizable length for a Spring <form:textarea /> element?

Despite extensive research, I have yet to find an answer to my specific problem. Within a model window, I have a textarea element: <div class="form-group"> <label for="groupDescription" class="col-sm-2 control-label"> Descripti ...

What is the best way to make a linear gradient that spans the entire vertical space that is visible (or shifts to a solid color)?

I'm trying to figure out how to apply a linear gradient to the body element of my webpage. Here's the CSS code I've been using: body { background: linear-gradient(0deg, white, lightgray); } The issue I'm facing is that the gradien ...

Set default selected value for dropdown list using radio buttons

Could anyone provide guidance on how to reset a dropdown list value using a radio button selection? Specifically, I need the dropdown list to reset to its default "selected" option when a particular radio button is clicked. Any recommended approaches usin ...

The gulp-sass import feature has been acting up quietly

I'm currently attempting to transpile a scss file using gulp-scss. However, when I execute the task, it seems that the imports are not being recognized. gulpfile.js gulp.src('./app/css/app.scss', {base: './'}) .pipe(sass({inc ...

Update the color of the menu ID

Feeling frustrated trying to figure out how to modify this <nav class="mainnav "> <a id="top"/> <div class="navwrap"> <ul id="menu-top" class="menu"> <li id="menu-item-70" class="menu-item menu-item-type-custom menu-item-object- ...

Arranging text in alignment on a single line with Vuetify

I am attempting to format text in a way that it is aligned with part on the left side of the card and the other part on the right (with space between them). However, when using class="text-right", the text gets moved down. Does anyone have any ideas on h ...

The TailwindCSS breakpoints are not being recognized in the styling

I am currently working on a NextJS 14 project where I am integrating Tailwind CSS. Here is a snippet of the code I am using: <div className="text-amber-dim md:text-amber flex-1 h-screen flex items-center justify-center"> <div classNam ...

Having trouble aligning the form in the center?

Despite #container being centered, I am struggling to center the <form>. It is important for me to have all elements inside the form aligned horizontally and despite trying various techniques, it is not working as expected. <!-- Container Start - ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

What's the best way to target an input that's appearing as it slides in from the edge of the screen?

My webpage has an element called #cols that is three times wider than the <body>. This element contains three columns, each exactly as wide as the <body>. When a button is clicked, the #cols element slides over by the width of one column while ...