简体   繁体   中英

Symfony2 - Doctrine Entity array field and forms

let's say I have Post entity that has $title field (array type) and I want to allow the user to write the title of the post in multiple-language

/**
 * Post
 *
 * @ORM\Table(name="posts")
 * @ORM\Entity
 */
class Post
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var array
     *
     * @ORM\Column(name="title", type="array", nullable=true)
     */
    protected $title;
}

How can I create form type that generate those fields when user want to submit a new post?

<input type="text" name="title[en]" />
<input type="text" name="title[fr]" />

You have to create a sub type for your form :

class TitleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $builder
                    ->add('en')
                    ->add('fr');
    }

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

Then you can add this sub type in your main type :

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $builder
                    ->add('title', new TitleType());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM