Symfony 2:保存json并显示值

时间:2014-02-15 20:19:05

标签: php json forms symfony entity

我实际上正在使用Symfony2开发个人项目。 我想做点什么,但我不知道该怎么做。 我有一个实体Recette,在这个实体中我有一个属性ingredients 此成分属性为json_array类型。

<?php

namespace sf2\RecetteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Recette
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="sf2\RecetteBundle\Entity\RecetteRepository")
 */
class Recette
{
    // ...

    /**
     * @var array
     *
     * @ORM\Column(name="ingredients", type="json_array")
     */
    private $ingredients;

   // ...
}

?>

在此json_array我只想保存一些信息。 例如:

["name":"potatoes","quantity":"5kg"]

在这里,您可以找到我的实体FormType:

class RecetteType extends AbstractType
{
    /**
    * @param FormBuilderInterface $builder
    * @param array $options
    */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name','text',array('label' => "test","attr"=>array('class'=>'test')))
            ->add('completionTime')
            ->add('ingredients',
                'collection',
                array(
                    'type'=>'text',
                    'prototype'=>true,
                    'allow_add'=>true,
                    'allow_delete'=>true,
                    'options'=>array(
                    )
                )
            )
            ->add('preparation')
            ->add('recetteCategories')
            ->add('Ok','submit')
        ;
    }
}

在我的表单中,我可以添加jquery添加成分的任何问题,但我的问题是我无法保存数量信息。我不知道如何在我的表格中显示两个字段而不是一个字段。

目前,当我保存一种成分时,我将这些数据存储在数据库中:

["Potatoes"]

我如何在我的表格中显示一个成分的两个字段以及如何以这种格式保存它?

["name":"potatoes","quantity":"5kg"]

感谢。

1 个答案:

答案 0 :(得分:5)

以下是doc How to Embed a Collection of Forms

的示例

首先,您必须创建名为IngredientType的Custom Form Field Type

<强> IngredientType

namespace Acme\RecetteBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class IngredientType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('quantity')
        ;
    }

    public function getName()
    {
        return 'ingredient';
    }
}

<强> services.yml

# src/Acme/RecetteBundle/Resources/config/services.yml
services:
    acme_demo.form.type.ingredient:
        class: Acme\RecetteBundle\Form\Type\IngredientType
        tags:
            - { name: form.type, alias: ingredient }

并将集合中的The field type更改为成分类型。

<强> RecetteType

         ->add('ingredients',
            'collection',
            array(
                'type'=>'ingredient',
                'prototype'=>true,
                'allow_add'=>true,
                'allow_delete'=>true,
                'options'=>array(
                )
            )
        )