如何使用CollectionType编辑和更新json字符串

问题描述 投票:0回答:1

我的数据库中有json字符串。字符串看起来像[{“ x”:“ 1”,“ y”:“ 22”}]。因此,基本上它为一个点存储了两个坐标。我希望能够使用CollectionType表单和数据转换器进行编辑和保存。

这是我的场景实体

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。但是我总是收到错误消息:类型为“ array or(\ Traversable and \ ArrayAccess)”的期望参数,给定的“ string”似乎错误在树枝上无处不在。任何帮助将不胜感激。

symfony twig symfony-forms symfony-4.3 data-transform
1个回答
0
投票

我通过放弃表格中的数据转换器解决了这个问题,因为字段“点”的类型是TextArea,并且要显示数组的数据,我需要一个Collection类型。

因此,在实体“场景”中引入了一个附加字段“ pointsArray”以及将json转换为数组的方法,反之亦然。在SceneController中调用了方法,并将“类型”字段添加到了“ pointsArray”属性的表单类型。

© www.soinside.com 2019 - 2024. All rights reserved.