问题
I have a problem with my code and of course, I'm beginner in Symfony;).
Explanation of what I want to do:
I have a list of button (each button represents an information in my database). When I click on it, i would like to have a form to update this information and of course send it in my database.
I already did on other form for other entities but this one doesn't work and i don't see why.
Now: When i click on a button, i can see in my console that i have everything i need to send to my controller using javascript.
However, I have this message in Symfony Profiler : "Unable to transform value for property path "commentState": Expected a Boolean."
So, i show you my code.
My entity Information:
<?php
namespace App\RenseignementBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use JsonSerializable;
/**
* @ORM\Entity(repositoryClass="App\RenseignementBundle\Repository\InformationRepository")
* @ORM\Table(name="Information")
*/
class Information implements JsonSerializable
{
/**
* @ORM\Id()
* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class="App\PuyDuFou\SqlGuidGeneratorBundle\Doctrine\SQLGuidGenerator")
* @ORM\Column(type="bigint", name="In_id")
*/
private $id;
/**
* @ORM\Column(type="string", length=50, name="In_label")
*/
private $label;
/**
* @ORM\Column(type="boolean", name="In_commentstate")
*/
private $commentState;
/**
* @ORM\Column(type="boolean",name="In_archive")
*/
private $archive;
/**
* @ORM\Column(type="integer", name="In_order")
*/
private $order;
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
public function getCommentState(): ?int
{
return $this->commentState;
}
public function setCommentState(int $commentState): self
{
$this->commentState = $commentState;
return $this;
}
public function getArchive(): ?bool
{
return $this->archive;
}
public function setArchive(int $archive): self
{
$this->archive = $archive;
return $this;
}
/**
* @ORM\ManyToOne(targetEntity="App\RenseignementBundle\Entity\Category", inversedBy="informations")
* @ORM\JoinColumn(name="fk_category", referencedColumnName="Ca_id")
*/
private $category;
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
/**
* @ORM\OneToMany(targetEntity="App\RenseignementBundle\Entity\RecordToInformation", mappedBy="information")
*/
private $recordToInformations;
public function __construct()
{
$this->recordToInformations = new ArrayCollection();
}
/*
/**
* @return Collection|RecordToInformation[]
*/
public function getRecordToInformations()
{
return $this->recordToInformations;
}
/*
public function addRecordToInformation(RecordToInformation $recordToInformation){
$this->recordToInformations->add($recordToInformation);
}
public function removeRecordToInformation(RecordToInformation $recordToInformation){
}
*/
public function jsonSerialize()
{
$Arr = get_object_vars($this);
return $Arr;
// array(
// 'id' => $this->id,
// 'barcode'=> $this->barcode,
// 'salle' =>
// );
}
public function getOrder(): ?int
{
return $this->order;
}
public function setOrder(string $order): self
{
$this->order = $order;
return $this;
}
}
My controller:
<?php
namespace App\RenseignementBundle\Controller;
use App\RenseignementBundle\Entity\Information;
use App\RenseignementBundle\Form\InformationFormType;
use App\RenseignementBundle\Form\InformationForRecordFormType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
/**
* Zone Controller
*
* @Route("/informations/information")
*/
class InformationController extends AbstractController
{
/**
* @Route("/", name="information.list")
* @param EntityManagerInterface $em
* @return \Symfony\Component\HttpFoundation\Response
*/
public function index(EntityManagerInterface $em, Request $request)
{
$categinformation = $em->getRepository('RenseignementBundle:Category')->findAll();
$informations = $em->getRepository('RenseignementBundle:Information')->findInformation();
return $this->render('RenseignementBundle/Informations/listInformation.html.twig', array(
'categinformations' => $categinformation,
'informations' => $informations,
));
}
/**
* @Route("/add", name="information.new")
* @param EntityManagerInterface $em
* @return \Symfony\Component\HttpFoundation\Response
*/
public function add(EntityManagerInterface $em, Request $request)
{
$information = new Information();
$form = $this->createForm(InformationFormType::class);
$form->handleRequest($request);
if ($request->isMethod('POST')) {
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$information->setCategory($data['category']);
$information->setLabel($data['label']);
$information->setCommentState($data['commentState']);
$information->setArchive($data['archive']);
$em->persist($information);
$em->flush();
$this->addFlash('success', 'Renseignement ajouté');
return $this->redirectToRoute('information.list');
}
}
return $this->render('RenseignementBundle/Informations/newInformation.html.twig', [
'recordForm' => $form->createView()
]);
}
/**
* @Route("/update/{id}/", name="information.update")
* @param EntityManagerInterface $em
* @return \Symfony\Component\HttpFoundation\Response
*/
public function update($id, EntityManagerInterface $em, Request $request)
{
$information = $em->getRepository('RenseignementBundle:Information')->find($id);
$form = $this->createForm(InformationFormType::class, $information);
$form->handleRequest($request);
if ($request->isMethod('POST')) {
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($information);
$em->flush();
$this->addFlash('success', 'Renseignement modifié');
return $this->redirectToRoute('information.list');
}
}
return $this->render('RenseignementBundle/Informations/newInformation.html.twig', [
'recordForm' => $form->createView(),
'information' => $information
]);
}
}
My javascript: require('../js/app.js');
var moment = require('moment');
global.moment = moment;
moment().format();
require('../plugins/jquery.dataTables.min.js');
require('../plugins/dataTables.bootstrap4.min.js');
require('../plugins/tempusdominus-bootstrap-4.min.js');
/********************************************************************************/
/***************************Valid passage****************************************/
/********************************************************************************/
function affichagearchive(){
if($(".categoryarchive").hasClass('hiden')){
$(".btnlist").removeClass('hiden');
}else{
$(".categoryarchive").addClass('hiden');
}
if($(".categinformationarchive").hasClass('hiden')){
$(".btncat").removeClass('hiden');
}else{
$(".categinformationarchive").addClass('hiden');
}
}
$(".btncat").click(function(){
$(".collapse").collapse('hide');
});
$(document).ready(function() {
$( "#ckarchive" ).click(function() {
affichagearchive();
});
$('.resultupdate').hide();
});
$("#btnaddinformation").click(function(){
$.get('add/', null, function (datax) {
$('.formulaire').html(datax);
$('form[name="information_form"]').on("submit", function(e){
// e.preventDefault();
var Category = $('#information_form_category').val();
var Label = $('#information_form_label').val();
var CommentState = $('input[type=checkbox][name="information_form[commentState]]"]:checked').val();
var Archive = $('input[type=checkbox][name="information_form[archive]"]:checked').val();
var token = $('#information_form__token').val();
$.post('add',
{
'information_form[category]':Category,
'information_form[label]':Label,
'information_form[commentState]':CommentState,
'information_form[archive]':Archive,
'information_form':{_token:token}
}, function(datax2){
});
})
})
})
$(".btnlist").click(function(){
getinformationupdate($(this).attr('id'));
})
function getinformationupdate(idinformation) {
$.get('update/'+ idinformation +'/', null, function (datax) {
$('.formulaire').html(datax);
$('form[name="information_form"]').on("submit", function(e){
var Category = $('#information_form_category').val();
var Label = $('#information_form_label').val();
var CommentState = $('input[type=checkbox][name="information_form[commentState]]"]:checked').val();
var Archive = $('input[type=checkbox][name="information_form[archive]"]:checked').val();
var token = $('#information_form__token').val();
$.post('update/'+ idinformation +'/',
{
'information_form[category]':Category,
'information_form[label]':Label,
'information_form[commentState]':CommentState,
'information_form[archive]':Archive,
'information_form':{_token:token}
}, function(datax){
});
})
})
}
My formType:
<?php
namespace App\RenseignementBundle\Form;
use App\RenseignementBundle\Entity\Category;
use App\RenseignementBundle\Entity\Information;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class InformationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'label',
'required' => true
])
->add('label', TextType::class)
->add('commentState', CheckboxType::class, array(
'label' => 'Commentaire',
'required' => false)
)
->add('archive', CheckboxType::class, array(
'label' => 'Archive',
'required' => false)
);
}
}
Perhaps a new look will find the mistake.
Edit: I passed 2 days, blocked on this problem. And when I wrote on StackOverflow, I find the solution just after !! If someone have this problem, check your entity. In my case, it was that I put the type int on my var and it should be a boolean.
回答1:
There is some inconsistancy in your add method. It should seems like your update method:
$form->handleRequest($request);
map request fields into entity properties with correct data transformer. So you error could be here if it occurs on add behavior.
Also you have to pass the entity to the form to let the magic happens:
$information = new Information();
$form = $this->createForm(InformationFormType::class, $information);
Now we know that u don't have to set property manually.
$data = $form->getData();
$information->setCategory($data['category']);
$information->setLabel($data['label']);
$information->setCommentState($data['commentState']);
$information->setArchive($data['archive']);
can be removed.
I don't have the full InformationFormType code but i assume you put your resolver like:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Information::class,
]);
}
Edit:
I didn't pay attention to your entity but our setter isn't not correct too
If you declare a property with annotation Column(type="boolean")
you must type your setter/getter as the same type
public function getCommentState(): ?bool
{
return $this->commentState;
}
public function setCommentState(bool $commentState): self
{
$this->commentState = $commentState;
return $this;
}
来源:https://stackoverflow.com/questions/56099253/unable-to-transform-value-for-property-path-expected-boolean