我有一个同时具有名称(字符串)和文件(也是表示文件名的字符串)的实体.这是"Icon"实体.我有另一个名为"Category"的实体,它有一个名字(字符串)和一个Icon(OneToMany)的关系.我希望表单允许用户选择类别的图标.
所以我可以在表格中显示它:
$builder->add('icon', 'entity', array(
'class' => 'CroltsMainBundle:Icon',
'expanded' => true,
'multiple' => false
));
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是在每个单选按钮的枝条中显示这样的东西:
<div>
<label for="something"><img src="/icons/{{icon.file }}" />{{icon.name}}</label>
<input type="radio" name="something" value="{{ icon.id }}" />
</div>
Run Code Online (Sandbox Code Playgroud)
有没有一种很好的方法可以用Symfony形式制作这种类型的无线电形式?就像我想要的定制类型一样?我真的没有用自定义类型做太多,知道这有多大可能.
小智 9
不确定这是最好的方法,但这是我如何管理这种情况:
创建一个新的formtype是作为代表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';
}
}
Run Code Online (Sandbox Code Playgroud)在你的表格中
...
->add('icon', 'iconcheck', array(
'class' => 'CroltsMainBundle:Icon',
'property'=>'formField',
'multiple'=>false,
'expanded'=>true
))
...
Run Code Online (Sandbox Code Playgroud)
注意property=>'formField',这意味着__toString它不会返回as标签,而是从实体类中返回函数getFormField所需的任何内容.
所以,在你的实体类中:
class Icon {
....
public function getFormField() {
return $this; /* or an array with only the needed attributes */
}
....
}
Run Code Online (Sandbox Code Playgroud)然后您可以渲染自定义字段
{% 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 %}
Run Code Online (Sandbox Code Playgroud)