简体   繁体   中英

Symfony form builder multiple rows of same type

Hello I was wondering how to create a form in Symfony form builder that will display multiple rows of same type. For example, I have an array of images:

Array: 
[www.image1.com, www.image2.com, www.image3.com]

I want to make a form that will display a textbox field for each of this images. The number of images is not known, could be 1 or could be 30. So I would like something similar to this:

Image 1 displayed | textbox 1
Image 2 displayed | textbox 2
Image 3 displayed | textbox 3

[Save]

In the textbox I would then write titles for each file and when I click save every row should be saved in it's own row in the database, like this:

id | name                | url
------------------------------------------
1  | name from textbox 1 | www.image1.com
2  | name from textbox 2 | www.image2.com
3  | name from textbox 3 | www.image3.com

I don't know how to create this form from my Entity. How does the form create multiple textboxes but knows how to connect each of them to the right text that should go in.

First you will need to define a to-many relationship between your base entity and an image entity.

As far as the form goes, you need to use the Collection type provided by Symfony.

Here is an example:

use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ImageType;
// ...

$formBuilder->add('images', CollectionType::class, array(
    // each entry in the array will be an "image" field
    'entry_type'   => ImageType::class,
    // these options are passed to each "image" type
    'entry_options'  => array(
        'attr'      => array('class' => 'image-box')
    ),
));

Of course you can pass any built in field type to entry_type if you don't want to make your own form type.

More detailed info here: http://symfony.com/doc/current/reference/forms/types/collection.html

If you need help making your image entity there is a cookbook recipe for that: http://symfony.com/doc/2.2/cookbook/doctrine/file_uploads.html and even though it is outdated it is still relevant

Hope that helps

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