无法转换属性路径的值:预期布尔值

时间:2019-05-12 12:28:32

标签: symfony4

我的代码有问题,当然,我是Symfony的初学者;)。

我要做什么的解释:

我有一个按钮列表(每个按钮代表数据库中的信息)。当我单击它时,我希望有一个表单来更新此信息,当然还要将其发送到我的数据库中。

我已经为其他实体做了另一种形式,但是这种形式不起作用,我也不知道为什么。

现在: 当我单击一个按钮时,我可以在控制台中看到我需要使用javascript发送到控制器的所有内容。

但是,我在Symfony Profiler中收到以下消息:“无法转换属性路径“ commentState”的值:预期为布尔值。”

所以,我向您展示我的代码。

我的实体信息:

<?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;
            }
        }

我的控制器:

<?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
            ]);
        }


    }

我的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){
                });
            })
        })
    }

我的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)
                );
        }
    }

也许换个新外观会发现错误。

编辑:我过了2天,在此问题上受阻。当我在StackOverflow上写文章时,我在!!之后找到了解决方案!如果有人遇到此问题,请检查您的实体。就我而言,是我将类型int放在var上,应该是布尔值。

1 个答案:

答案 0 :(得分:0)

您的添加方法存在一些不一致之处。似乎应该是您的更新方法:

$form->handleRequest($request);使用正确的数据转换器将请求字段映射到实体属性。因此,如果在添加行为上发生错误,则可能会出现错误。 另外,您还必须将实体传递给表单,以使魔术发生:

$information = new Information();
$form = $this->createForm(InformationFormType::class, $information);

现在我们知道您不必手动设置属性。

$data = $form->getData();
$information->setCategory($data['category']);
$information->setLabel($data['label']);
$information->setCommentState($data['commentState']);
$information->setArchive($data['archive']);

可以删除。

我没有完整的InformationFormType代码,但我假设您将解析器放置为:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => Information::class,
    ]);
}

编辑:

我没有关注您的实体,但我们的设置者也不正确 如果您声明带有注解Column(type="boolean")的属性,则必须将您的setter / getter输入相同的类型

public function getCommentState(): ?bool
{
    return $this->commentState;
}


public function setCommentState(bool $commentState): self
{
    $this->commentState = $commentState;

    return $this;
}