Symfony3自定义EntityType选项的标签

时间:2016-05-03 15:12:43

标签: forms symfony

我搜索解决方案以自定义EntityType选择的标签。

实体

发布

class Post
{
    // ...

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Item", cascade={"persist"})
     */
    private $items;

    // ...
}

项目

class Item
{
    // ...

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=127)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255, nullable=true)
     */
    private $image;

    // ...

    public function __toString(){
        return $this->title;
    }
}

表格

class PostType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('items', EntityType::class, array(
                'class' => 'AppBundle\Entity\Item',
                'multiple' => true,
                'expanded' => true,
            ))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Post'
        ));
    }
}

结果

我知道如何修改DOM以获取:

<ul>
    <li>
        <input type="checkbox" id="post_items_1" name="post[items][]" value="1">
        <label for="post_items_1">Item 1</label>
    </li>
    <li>
        <input type="checkbox" id="post_items_2" name="post[items][]" value="2">
        <label for="post_items_2">Item 2</label>
    </li>

    <!-- ... -->
</ul>

但我想从Item选项中获取其他信息(如属性图片):

<ul>
    <li>
        <input type="checkbox" id="post_items_1" name="post[items][]" value="1">
        <label for="post_items_1">
            Item 1
            <img src="/uploads/item/lorem.jpg" alt="" /> <!-- path store into item #1 -->
        </label>
    </li>
    <li>
        <input type="checkbox" id="post_items_2" name="post[items][]" value="2">
        <label for="post_items_2">
            Item 2
            <img src="/uploads/item/ipsum.jpg" alt="" /> <!-- path store into item #2 -->
        </label>
    </li>

    <!-- ... -->
</ul>

有没有人有解决方案?

1 个答案:

答案 0 :(得分:1)

设置choice_label是您正在寻找的内容:

$builder->add('users', EntityType::class, array(
    'class' => 'AppBundle:User',
    'choice_label' => 'username',
));

来源:http://symfony.com/doc/current/reference/forms/types/entity.html

如果要在标签中使用图像,可以自定义表单模板。你可以在这里阅读: