【发布时间】:2012-12-21 05:14:21
【问题描述】:
我需要这方面的帮助,因为即使在阅读和检查了我在互联网上找到的所有资源后,我自己也无法弄清楚。
我有一个图像实体。它有 3 个映射属性。
- 身份证
- 位置
- thumb_location
我有自定义的 ImageSelectType 表单类型,它扩展了 AbstractType:
buildForm 函数如下所示:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$em = $options['em'];
$qb = $em->createQueryBuilder();
$result = $qb->select('i')
->from('BloggerBlogBundle:Image', 'i')
->leftJoin('i.articles', 'a')
->where('a is NULL')
;
$builder
->add('images', 'entity', array(
'class' => 'BloggerBlogBundle:Image',
'query_builder' => $result,
'required' => true,
'multiple' => false,
'expanded' => true,
)
)
->setAttribute('widget', 'imageSelect')
;
}
因此,它会获取任何文章未使用的所有图像并用它们填充表单。使用这些选项,我得到单选按钮,如下所示:
<div id="image_images">
<input type="radio" id="image_images_67" name="image[images]" required="required" value="67"><label for="image_images_67" class="required">c5252b4ffc9c50540218e25be1353b33aaa4ee05.png</label>
<input type="radio" id="image_images_68" name="image[images]" required="required" value="68"><label for="image_images_68" class="required">fcfc7d7d05d63b1f55dff8cbff0bedeb3c917dfc.jpeg</label>
</div>
我现在想要的是所有单选按钮都具有自定义 html5 数据属性 data-thumb="thumbnail/location.png",这将是该单选按钮表示的图像对象的 thumb_location 属性值。
我希望我已经足够清楚了。如果需要更多信息,我会提供。 我已经阅读了很多关于此的内容,但我认为我想象的事情比实际情况更复杂。有一次我只想说'哦,算了,我将手动渲染它'并使用:
{% for choice in form.vars.choices %}
<input type="radio" data-thumb="{{choice.thumb_location}}" />
{% endfor %}
但我真的很想使用这个令人惊叹的框架提供的良好实践......有时对我来说似乎并不像他们应该的那样明显。
【问题讨论】:
-
Symfony2 食谱有一篇关于how to create a custom form field type 的文章。
-
正如我所说,我已经阅读了它,但我仍然不明白。我真的不觉得它很广泛,或者我太愚蠢了,无法得到明显的东西......我什至开始检查 Symfony 的源代码,我看到他们在 Forms 组件内部使用 PHP 模板,而我使用 Twig .
-
我没有发现任何尝试构建自定义表单字段类型的迹象,如代码示例中该文章中所述。您何不再试一次,问问您在这样做时遇到的具体问题?