Невозможно преобразовать значение для пути свойства: ожидаемое логическое значение - PullRequest
1 голос
/ 12 мая 2019

У меня проблема с моим кодом и, конечно, я новичок в 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){
                });
            })
        })
    }

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

Возможно, новый взгляд найдет ошибку.

Редактировать: Я прошел 2 дня, заблокирован по этой проблеме.И когда я написал на StackOverflow, я нашел решение сразу после!Если у кого-то есть такая проблема, проверьте вашу сущность.В моем случае это было то, что я поместил тип int в мою переменную, и он должен быть логическим.

1 Ответ

0 голосов
/ 12 мая 2019

В вашем методе добавления есть некоторое несоответствие. Похоже, ваш метод обновления:

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

Edit:

Я не обратил внимания на вашу сущность, но наш сеттер тоже не прав Если вы объявляете свойство с аннотацией Column(type="boolean"), вы должны ввести свой установщик / получатель того же типа

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


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

    return $this;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...