Как редактировать и обновлять строку json, используя CollectionType - PullRequest
0 голосов
/ 24 октября 2019

В моей базе данных есть строка json. Строка выглядит как [{"x": "1", "y": "22"}]. Так что в основном он хранит две координаты для точки. Я хочу иметь возможность редактировать и сохранять его, используя форму CollectionType и преобразователь данных.

Это моя сущность Scene

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Scene
 *
 * @ORM\Table(name="scenes", indexes={@ORM\Index(name="house_id", columns={"house_id"})})
 * @ORM\Entity(repositoryClass="App\Repository\SceneRepository")
 */
class Scene
{
    /**
     * @var int
     *
     * @ORM\Column(name="scene_id", type="bigint", nullable=false, options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $sceneId;

    /**
     * @var string
     *
     * @ORM\Column(name="scene_title", type="string", length=50, nullable=false)
     */
    private $sceneTitle;

     /**
     * @var string
     *
     * @ORM\Column(name="points", type="text", length=65535, nullable=false)
     */
    private $points;

    /**
     * Many scenes have one house. This is owing site
     * @ORM\ManyToOne(targetEntity="House", inversedBy="scenes")
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="house_id", referencedColumnName="house_id")
     * })
     */
    private $house;

    /**
     * @return int
     */
    public function getSceneId(): int
    {
        return $this->sceneId;
    }

    /**
     * @return string|null
     */
    public function getSceneTitle(): ?string
    {
        return $this->sceneTitle;
    }

    /**
     * @return string|null
     */
    public function getPoints(): ?string
    {
        return $this->points;
    }

    /**
     * @return House
     */
    public function getHouse(): ?House
    {
        return $this->house;
    }

    /**
     * @param string $sceneTitle
     * @return Scene
     */
    public function setSceneTitle(string $sceneTitle): self
    {
        $this->sceneTitle = $sceneTitle;

        return $this;
    }

    /**
     * @param string $points
     * @return Scene
     */
    public function setPoints(string $points): self
    {
        $this->points = $points;

        return $this;
    }

    /**
     * @param House $house
     * @return Scene
     */
    public function setHouse(House $house): self
    {
        $this->house = $house;

        return $this;
    }
}

А это мой класс SceneType

namespace App\Form;

use App\Entity\Scene;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SceneType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('sceneTitle')
            ->add('points', CollectionType::class, [
                'entry_type' => PointsEmbededFormType::class,
                'block_name' => 'list',
            ])
            ->add('house');

    }

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

}

Я создал PointsEmbededFormType

namespace App\Form;

use App\Form\DataTransformer\JsonToInputTransform;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\OptionsResolver\OptionsResolver;
use App\Entity\Scene;

use Symfony\Component\Form\AbstractType;

class PointsEmbededFormType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('points');

        $builder->get('points')->addModelTransformer(new CallbackTransformer(
            function ($pointsJson){
                return json_decode($pointsJson);
            },
            function ($pointsArray){
                return json_encode($pointsArray);
            }
        ))->addViewTransformer(new CallbackTransformer(
            function ($normalizeData){
                $result =[];
                foreach($normalizeData as $item)
                {
                    $result[] =$item->x;
                    $result[] =$item->y;
                }
                return $result;

            },
            function ($viewData) {
                $result = [];
                for ($i=1; $i < count($viewData); $i+2) {

                    $temp['x'] = $viewData[$i];

                    $temp['y'] = $viewData[$i+1];

                    $tempArray = [$temp['x'], $temp['y']];
                    $result[] = json_encode($tempArray);
                }


                return $result;
            }
        ));

    }

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


}

Это код из CseneController.php

    /**
     * @Route("/{sceneId}/edit", name="scene_edit", methods={"GET","POST"})
     * @param Request $request
     * @param Scene $scene
     * @return Response
     */
    public function edit(Request $request, Scene $scene): Response
    {

        $form = $this->createForm(SceneType::class, $scene);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('scene_index');
        }

        return $this->render('crud/scene/edit.html.twig', [
            'scene' => $scene,
            'form' => $form->createView(),
        ]);
    }

И, наконец, мой _form.html.twig

    <ul>
                {% for point in form.points %}

                    <li>
                        {{ form_widget(point) }}
                    </li>
                {% endfor %}
            </ul>

Я хочучтобы получить набор входов для редактирования x и y для каждой точки. Но я продолжаю получать сообщение об ошибке: ожидаемый аргумент типа «массив или (\ Traversable and \ ArrayAccess)», «заданная строка» Кажется, что ошибка где-то в ветке. Любая помощь будет по достоинству оценена.

1 Ответ

0 голосов
/ 28 октября 2019

Я решил эту проблему, отказавшись от преобразователя данных в форме, поскольку тип поля «точки» был TextArea, а для отображения данных массива мне требовался тип Collection.

Итак, дополнительное поле "pointsArray" и методы для преобразования json в массив и наоборот были введены в сущность "Scene". Методы были вызваны в SceneController, а поле типа Collection было добавлено в тип формы для свойства pointsArray.

...