mercredi 18 novembre 2020

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 App\Entity;
use Symfony\Component\Validator\Constraints as Assert;

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

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

Step 2: SeachPlayerType

<?php
namespace App\Form;

use app\Entity\SearchPlayerData;

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




Aucun commentaire:

Enregistrer un commentaire