Reputation: 23
I'm actually developping a personal project with Symfony2.
And i want to to do something but i don't know how to do that.
I have an entity Recette
and in this entity i have a property ingredients
This ingredients property is a json_array
type.
<?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;
// ...
}
?>
In this json_array
i just want to save a couple of information.
Ex :
["name":"potatoes","quantity":"5kg"]
Here you can find my Entity 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')
;
}
}
In my form i can add with jquery with any problem add an ingredient, but my problem is that i can't save the quantity information. i don't know how to display in my form two field instead one for an ingredient.
Currently when i save an ingredient i have this data in database :
["Potatoes"]
How i can display in my form two fields for an ingredient and how to save it in this format ?
["name":"potatoes","quantity":"5kg"]
Thanks.
Upvotes: 2
Views: 9701
Reputation: 4092
Here is an example from doc How to Embed a Collection of Forms
Firstly you must create a Custom Form Field Type named IngredientType:
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 }
And change The field type in your collection to ingredient type.
RecetteType
->add('ingredients',
'collection',
array(
'type'=>'ingredient',
'prototype'=>true,
'allow_add'=>true,
'allow_delete'=>true,
'options'=>array(
)
)
)
Upvotes: 5