J'ai ajouté un champs qui n'est pas un attribut de mon objet "etudiant" en le mettant un 'mapped'=>false.
Mais le problème c'est que je n'arrive pas à reccuperer le champs après la soumission du formulaire dans mon controller.
NB: le champs en question est un checkbox.
code du formulaire
->add('frais_annexe',CheckboxType::class, [
'label' => 'Frais annexe',
'required' => true,
'attr'=>['required'=>'required', 'checked'=>'checked', 'disabled'=>'disabled','value'=>200000],
'mapped'=>false,
'method' => 'POST'
])
Et après la soumission du formulaire je fais ceci pour réccuperer la valeure:
$form->get('frais_annexe')->getData();
mais sa me renvoir null, comment faire?
Bonjour, as tu bien fait un $form->handleRequest($request)
Apres la soumission ?
Salut,
Lorsque tu soumets ton formulaire ta checkbox est cochée ou non ?
Si tu regardes dans le Devtools tu vois quelle valeur dans le payload ?
@David-CCO la checkbox est bien cochée lors de la soumission par contre je ne vois pas l'element dans le payload
Oui voici le code du controller
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Etudiant;
use App\Entity\Structure;
use App\Form\EtudiantType;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;
use phpDocumentor\Reflection\Types\Null_;
#[Route('/etudiant')]
class EtudiantController extends AbstractController
{
public function __construct(){}
#[Route('/add/{id<\d+>?0}', name: 'app_etudiant_add')]
public function add(Request $request,ManagerRegistry $doctrine, SluggerInterface $slugger, Etudiant $etudiant=Null): Response
{
$structureRepository = $doctrine->getRepository(Structure::class);
$structures = $structureRepository->findAll();
$mes = 'Etudiant modifié avec succès !';
if(!$etudiant){
$etudiant = new Etudiant();
$mes = 'Etudiant ajouté avec succès !';
}
$form = $this->createForm(EtudiantType::class, $etudiant);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// foreach($structures as $structure){
// }
// $etudiant = $form->getData();
// dd($request->request);
$photo = $form->get('photo')->getData();
if ($photo) {
$originalFilename = pathinfo($photo->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$photo->guessExtension();
// Move the file to the directory where brochures are stored
try {
$photo->move(
$this->getParameter('etudiant_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
$etudiant->setPhoto($newFilename);
}
$entityManager = $doctrine->getManager();
$etudiant->setClasse($form->get('classe')->getData());
$entityManager->persist($etudiant);
$entityManager->flush();
$repository = $doctrine->getRepository(Etudiant::class);
// $etudiant = $repository->recupUser();
// return $this->redirectToRoute ('app_home', [ 'id' =>$etudiant[0]->getId() ]);
$this->addFlash(
'success',
$mes
);
}
return $this->render('etudiant/add.html.twig',[
'form' => $form->createView(),
'structures' => $structures
]);
}
Tu aimerai récuperer recup $form->get('frais_annexe')->getData(); je ne le vois pas dans le controller, je pourrai avoir le EtudiantType ?
je l'ai retirer pour le moment etant donné que cela ne marchait pas !
voici le code de EtudiantType
namespace App\Form;
use App\Entity\Etudiant;
use App\Entity\Classe;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\Validator\Constraints\File;
class EtudiantType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('Nom', TextType::class, [
'attr' => ['class' => 'form-control',
'placeholder' => 'Ex: Dupont'],
])
->add('prenom', TextType::class, [
'attr' => ['class' => 'form-control',
'placeholder' => 'Ex: patrick']
])
->add('dateNais',DateType::class, [
'widget' => 'single_text',
'attr' => ['class' => 'form-control',
'placeholder' => 'Ex: 2023/04/02']
])
->add('lieuNais', TextType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: Daloa']
])
->add('adresse',TextType::class, [
'attr' => ['class' => 'form-control', 'placeholder' => 'Ex: Abattoir 1']
])
->add('email',EmailType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: exemple@gmail.com']
])
->add('tel',NumberType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: 050797190795']
])
->add('contact_p',NumberType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: 050797190795']
])
->add('etablis_orig',TextType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: Lycée Antoine Gauze'],
])
->add('sexe', ChoiceType::class, [
'choices' => [
'Féminin' => 'f',
'Masculin' => 'm',
],
'attr' => ['class' => 'form-control']
])
->add('serie_bac',TextType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: C']
])
->add('identifiant_p',TextType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: GDES1909990001']
])
->add('matricule',TextType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: 10456654R']
])
->add('num_tab',TextType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: 104566542']
])
->add('statut',ChoiceType::class, [
'choices' => [
'Affecté' => 'Affecté',
'Non affecté' => 'Non affecté',
],
'attr' => ['class' => 'form-control']
])
->add('redoublant', ChoiceType::class, [
'choices' => [
'Oui' => true,
'Non' => false,
],
'attr' => ['class' => 'form-control']
])
->add('nationalite', ChoiceType::class, [
'choices' => [
'Ivoirienne' => 'Ivoirienne',
'Malienne' => 'Malienne',
'Burkinabé' => 'Burkinabé',
'Guineénne' => 'Guineénne',
],
'attr' => ['class' => 'form-control']
])
->add('remise', NumberType::class, [
'attr' => ['class' => 'form-control','placeholder' => 'Ex: 12000']
])
->add('photo_num',ChoiceType::class, [
'choices' => [
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
],
'attr' => ['class' => 'form-control']
])
->add('bac_leg',CheckboxType::class, [
'label' => 'Bac légalisé',
'required' => false,
])
->add('fiche_inscription',CheckboxType::class, [
'label' => 'Fiche d\'inscription',
'required' => false,
])
->add('extrait',CheckboxType::class, [
'label' => 'extrait',
'required' => false,
])
->add('rame',CheckboxType::class, [
'label' => 'rame',
'required' => false,
])
->add('marqueur',CheckboxType::class, [
'label' => 'marqueur',
'required' => false,
])
->add('copie_piece',CheckboxType::class, [
'label' => 'Photocopie de la pièce',
'required' => false,
])
->add('frais_annexe',CheckboxType::class, [
'label' => 'Frais annexe',
'required' => true,
'attr'=>['required'=>'required', 'checked'=>'checked', 'disabled'=>'disabled','value'=>200000],
'mapped'=>false,
'method' => 'POST'
])
->add('droit_inscription',CheckboxType::class, [
'label' => 'Droit d\'inscription',
'required' => true,
'attr'=>['required'=>'required', 'checked'=>'checked', 'disabled'=>'disabled','value'=>13000],
'mapped'=>false,
])
->add('Soumettre', SubmitType::class, [
'attr' => ['class' => 'btn btn-primary
'],
])
->add('classe',EntityType::class,[
'attr' => ['class' => 'form-control'],
'mapped'=>false,
'class' => Classe::class,
'query_builder'=>function (EntityRepository $er){
return $er->createQueryBuilder('h')
->orderBy('h.id', 'DESC');
},
'choice_label'=>'designation'
])
->add('photo', FileType::class, [
'label' => 'Photo',
// unmapped means that this field is not associated to any entity property
'mapped' => false,
// make it optional so you don't have to re-upload the PDF file
// every time you edit the Product details
'required' => false,
// unmapped fields can't define their validation using annotations
// in the associated entity, so you can use the PHP constraint classes
'constraints' => [
new File([
'maxSize' => '3000k',
'maxSizeMessage' => 'Image trop lourde max 3Mo',
'mimeTypes' => [
'image/png',
'image/jpg',
'image/jpeg'
],
'mimeTypesMessage' => 'Veillez choisir une image valide',
])
],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Etudiant::class,
]);
}
}
Le champ "frais_annexe" est un champ de type CheckboxType et est configuré comme non mappé ('mapped' => false). Cela signifie que cette valeur n'est pas directement liée à une propriété de votre entité Etudiant.
Pour récupérer cette valeur, votre approche est correcte :
"$fraisAnnexe = $form->get('frais_annexe')->getData();" tu peux esseyer de debug
if ($form->isSubmitted() && $form->isValid()) {
$fraisAnnexe = $form->get('frais_annexe')->getData();
dump($fraisAnnexe); // Vérifiez ce que cela renvoie
// ... votre logique ici ...
}
le champs est disabled, la majorité des navigateurs ne passent pas la valeur dans le formulaire