我有一个具有名称(字符串)和文件(也是表示文件名的字符串)的实体。这是“图标”实体。 我有另一个名为“类别”的实体,它有一个名称(字符串)和与图标(OneToMany)的关系。我希望表单允许用户为类别选择图标。
所以我可以将其显示为以下形式:
$builder->add('icon', 'entity', array(
'class' => 'CroltsMainBundle:Icon',
'expanded' => true,
'multiple' => false
));
但我真正想要的是在每个单选按钮的 Twig 中显示类似这样的内容:
<div>
<label for="something"><img src="/icons/{{icon.file }}" />{{icon.name}}</label>
<input type="radio" name="something" value="{{ icon.id }}" />
</div>
有没有好的方法可以用 Symfony 表单制作这种类型的广播表单?就像我想要的自定义类型吗?我确实没有对自定义类型做过太多的工作,不知道这有多少可能。
最佳答案
不确定这是最好的方法,但这是我处理这种情况的方法:
创建一个新的表单类型,代表
entityType
,例如IconCheckType
: (http://symfony.com/doc/master/cookbook/form/create_custom_field_type.html)namespace .....\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormView; use Symfony\Component\Form\FormInterface; class IconCheckType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilder $builder, array $options) { $builder -> setAttribute('dataType', $options['dataType']); } /** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form) { $view -> set('dataType', $form -> getAttribute('dataType')); } /** * {@inheritdoc} */ public function getDefaultOptions(array $options) { return array('required' => false,'dataType'=>'entity'); } /** * Returns the allowed option values for each option (if any). * * @param array $options * * @return array The allowed option values */ public function getAllowedOptionValues(array $options) { return array('required' => array(false)); } /** * {@inheritdoc} */ public function getParent(array $options) { return 'entity'; } /** * {@inheritdoc} */ public function getName() { return 'iconcheck'; } }
在您的表单中
... ->add('icon', 'iconcheck', array( 'class' => 'CroltsMainBundle:Icon', 'property'=>'formField', 'multiple'=>false, 'expanded'=>true )) ...
请注意
property=>'formField'
,这意味着它不会返回__toString
作为标签,而是会从实体类的 getFormField 函数返回您想要的任何内容因此,在您的实体类中:
class Icon { .... public function getFormField() { return $this; /* or an array with only the needed attributes */ } .... }
然后您可以渲染自定义字段
{% block iconcheck_widget %} {% for child in form %} {% set obj=child.vars.label %} <div> <label for="something"><img src="/icons/{{obj.file }}" />{{obj.name}}</label> {{ form_widget(child) }} {# the radio/checkbox #} </div> {{ form_widget(child) }}#} {% endfor %} {% endblock %}
关于Symfony2 带有名称和图像的实体类型表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11213701/