Validation CheckboxType symfony

I don’t know how to validate a checkbox with a @Assert.

Returns a string "1" if checked otherwise false

Step 1: create a class: SearchPlayerData.php to test my data (without ORM)
This form is not linked to a class

<?php

namespace AppEntity;
use SymfonyComponentValidatorConstraints as Assert;

class SearchPlayerData
{
     /**
     * (length=255, nullable=true) 
     * @Assert???
     */
    public $tgg;

     /**
     * (length=255, nullable=true)
     * @Assert???
     */
    public $selection;
   ...

Step 2: SeachPlayerType

<?php
namespace AppForm;

use appEntitySearchPlayerData;

class SearchMultiType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

     $builder
            ->add('tgg', CheckboxType::class, [
                'label'             => "TGG", 
                'required'          => false,                
                'attr' => [
                    "class"         => "text-dark checkbox", 
                ], 
            ->add('selection', CheckboxType::class, [
                'label'             => "SELECTION", 
                'required'          => false,                
                'attr' => [
                    "class"         => "text-dark checkbox", 
                ], 
               ...
    
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            "data_class"    => SearchPlayerData::class
        ]);
    }

Etape 3 : Controller

    public function searchPlayers(Request $request, PlayerRepository $playerRepository)
    {
        $searchPlayerData = new SearchPlayerData(); 

        $form = $this->createForm(SearchPlayerType::class, $searchPlayerData, ["sect" => $sect]);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
        ....

Do you have an idea or another solution. I would like to keep the checkbox field if possible

Thanks for your help

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *